title,body,link,tags,view_count,is_answered,score,answer_count
Using .env files for unit testing with jest,"<p>Is it possible to load environment variables from an env file for unit testing purposes in Jest? I'm looking to run a series of tests on it like so:</p>

<pre><code>// unit tests for env file
describe('env', () =&gt; {
    it('should have a client id', () =&gt; {
        expect(process.env.CLIENT_ID).toBeDefined();
    });
    it('should have a client secret', () =&gt; {
        expect(process.env.CLIENT_SECRET).toBeDefined();
    });
    it('should have a host', () =&gt; {
        expect(process.env.HOST).toBeDefined();
    });
    it('should have a scope', () =&gt; {
        expect(process.env.SCOPE).toBeDefined();
    });
    it('should have a response type', () =&gt; {
        expect(process.env.RESPONSE_TYPE).toBeDefined();
    });
    it('should have a redirect uri', () =&gt; {
        expect(process.env.REDIRECT_URI).toBeDefined();
    });
});
</code></pre>

<p>Currently, all the above tests will fail, stating that the variables are undefined. Initially I was using a mocha/chai setup, which allowed me to just load all of my env variables via the use of dotenv. This involved running all unit tests through webpack and worked fine. </p>

<p>However, from reading the <a href=""https://facebook.github.io/jest/docs/en/webpack.html"" rel=""noreferrer"">documentation</a> Jest doesn't run tests through webpack; instead modules are mocked out via moduleNameMapper. This works fine for everything else, but I can't get the env file variables to load. So far I've tried using the setupFiles option to a js file that calls dotenv.config with the path of the env file given to it like so:</p>

<pre><code>// setup file for jest
const dotenv = require('dotenv');
dotenv.config({ path: './env' });
</code></pre>

<p>This didn't work, so I've now resorted to using just a .env.js file for unit tests and passing this file into the setupFiles option instead. However, for maintainability, and to keep it working with webpack for production, I'd like to just keep it all in one file. Here's an extract of how the .env.js file looks for reference </p>

<pre><code>// .env.js extract example
process.env.PORT = 3000;
process.env.HOST = 'localhost';
process.env.CLIENT_ID = 'your client id';
process.env.REDIRECT_URI = 'your callback endpoint';
</code></pre>
",https://stackoverflow.com/questions/50259025/using-env-files-for-unit-testing-with-jest,"['javascript', 'unit-testing', 'environment-variables', 'jestjs']",92509,TRUE,87,10
Unit Testing IServiceCollection Registration,"<p>I'm trying to figure out the easiest way to test my Service Registrations method for my framework. I'm creating dynamic services my registration looks like so:</p>

<pre><code>var messageHubConfig = new DynamicHubServiceConfiguration&lt;Message, MessageDTO&gt;();
messageHubConfig.SetDynamicHubOptions&lt;AstootContext&gt;(async (context, dto) =&gt;
{
    return await context.ConversationSubscriptions
                        .Where(x =&gt; x.ConversationId == dto.ConversationId 
                               &amp;&amp; x.IsSubscribed)
                        .Distinct()
                        .Select(x =&gt; x.User.UniqueIdentifier)
                        .ToListAsync();
});

messageHubConfig.RequiresDynamicValidator = false;
messageHubConfig.EventMapping.AddCreateEvent(async (sp, obj, dto) =&gt;
{
    var conversationService = sp.GetService&lt;IRestEzService&lt;Conversation, ConversationDTO&gt;&gt;();
    var conversationDTO = await conversationService.Get(new object[] { dto.ConversationId });
    var hubTaskQueue = sp.GetService&lt;IHubServiceTaskQueue&gt;();
    hubTaskQueue.QueueDynamicCreate(conversationDTO);
}).When(async (sp, dto) =&gt; {
    var context = sp.GetService&lt;AstootContext&gt;();
    return await context.Conversations.Where(x =&gt; x.Id == dto.ConversationId).Where(x =&gt; x.Messages.Count == 1).AnyAsync();
});

//Registers service with a hub
restConfiguration.RegisterRestService(typeof(IMessageDTOService), 
                                      typeof(MessageDTOService), 
                                      messageHubConfig);
</code></pre>

<p>Inside of my Register Rest Service Method I have a lot of different services Getting registered e.g:</p>

<pre><code>services.AddTransient(restServiceType, (IServiceProvider serviceProvider) =&gt;
{
    var restService = (IRestEzService&lt;TEntity, TDTO&gt;)
        ActivatorUtilities.CreateInstance(serviceProvider, restServiceImplementationType);
    serviceOption.EventMapping?.Register(serviceProvider, restService);

    return restService;
});
</code></pre>

<p>How can I be assure that my factory configuration is being registered properly, How can I create a Service Collection for testing?</p>
",https://stackoverflow.com/questions/51180523/unit-testing-iservicecollection-registration,"['c#', 'unit-testing', 'dependency-injection', '.net-core']",32477,TRUE,48,2
"PHP Unit, Testing laravel log messages with unit testing","<p>I'm using PHPUnit to create a Unit test for a store function that stores data in a database. </p>

<p>Currently, i have a test verifies that it has stored data.  </p>

<p>However, I also want to create a test that proves that a laravel log message has been produced if the model save function fails. </p>

<p>The code below shows the store function. The ""log::info"" is the line I want to test. </p>

<p>Thanks. </p>

<pre><code>public function store(Venue $venue){ 
    $saved =  $venue-&gt;save();
    if($saved == false){
        Log::info('Failed to Save Venue'. $venue);
    }
 }
</code></pre>

<p>This what I have so far, i pass an empty model that will cause the save to fail due to database constraints</p>

<pre><code>public function test_venue_store_failed(){
   $venue = new Venue();
   $venueRepo = new VenueRepository();
   $this-&gt;withExceptionHandling();
   $venueRepo-&gt;store($venue);
}
</code></pre>
",https://stackoverflow.com/questions/51246332/php-unit-testing-laravel-log-messages-with-unit-testing,"['php', 'laravel', 'unit-testing', 'laravel-5', 'phpunit']",15878,TRUE,7,2
Unit testing angular 5 component with @ViewChild,"<p>I am using angular 5.2.0. I have a child component</p>
<pre class=""lang-js prettyprint-override""><code>import { Component } from '@angular/core';

@Component({
  template: `&lt;div&gt;&lt;div&gt;&lt;/div&gt;&lt;/div&gt;`,
})
export class ChildComponent {

  public childMethod() {
    ...
  }
}
</code></pre>
<p>and a parent component which accesses the child via <code>ViewChild</code></p>
<pre class=""lang-js prettyprint-override""><code>import { Component, ViewChild } from &quot;@angular/core&quot;;
import { ChildComponent } from &quot;child.component&quot;;

@Component({
  template: `
  &lt;child-component #child&gt;
    &lt;child-component&gt;&lt;/child-component&gt;
  &lt;/child-component&gt;
  `,
})
export class ParentComponent {
  @ViewChild(&quot;child&quot;) child: ChildComponent;

  public parentMethod() {
    this.child.childMethod();
  }
}
</code></pre>
<p>I want a unit test proving that an invocation of <code>parentMethod</code> causes an invocation of <code>childMethod</code>. I have the following:</p>
<pre class=""lang-js prettyprint-override""><code>
import { NO_ERRORS_SCHEMA } from &quot;@angular/core&quot;;
import { ComponentFixture, TestBed } from &quot;@angular/core/testing&quot;;
import { ChildComponent } from &quot;./child.component&quot;;
import { ParentComponent } from &quot;./parent.component&quot;;

describe(&quot;ParentComponent&quot;, () =&gt; {
  let component: Parentcomponent;
  let fixture: ComponentFixture&lt;Parentcomponent&gt;;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ParentComponent, ChildComponent],
      schemas: [NO_ERRORS_SCHEMA],
    }).compileComponents();
  });

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(TaskListPaginatorComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it(&quot;should invoke childMethod when parentMethod is invoked&quot;, () =&gt; {
    const childMethodSpy: jasmine.Spy = spyOn(component.child, &quot;childMethod&quot;);
    component.parentMethod();
    expect(childMethodSpy).toHaveBeenCalled();
  });
});
</code></pre>
<p>Yet, this does not work, and I get <code>Error: &lt;spyOn&gt; : could not find an object to spy upon for childMethod()</code>.</p>
<p>Moreover, this is not a unit test, because I use the real ChildComponent instead of a mock. I tried creating a MockChildComponent and adding it to <code>declarations</code> and <code>export</code> but I got the same result. Any help?</p>
<p>I know there are similar post, but they are for different versions of angular, and they did not help.</p>
",https://stackoverflow.com/questions/51515530/unit-testing-angular-5-component-with-viewchild,"['angular', 'unit-testing', 'viewchild', 'testbed']",60527,TRUE,37,3
Unit testing WKNavigationDelegate functions,"<p>I have a UIViewController that implements some WKNavigationDelegate functions, and I want to unit test the logic in these functions. Here's an example:</p>

<pre><code>func webView(_ webView: WKWebView,
             decidePolicyFor navigationAction: WKNavigationAction,
             decisionHandler: @escaping (WKNavigationActionPolicy) -&gt; Void) {
    guard let url = navigationAction.request.url else {
        decisionHandler(.cancel)
        return
    }

    if url.absoluteString != ""https://my-approved-url"" {
        decisionHandler(.cancel)
        return
    }

    decisionHandler(.allow)
}
</code></pre>

<p>I'd like my unit test to make sure decisionHandler is called with the right WKNavigationActionPolicy based on the request.url of the WKNavigationAction.</p>

<p>I can't figure out how to test this function, however. Calling .load() on the webview does not trigger the delegate functions when I'm running my test project. I have also tried to call this function directly to test it, but it doesn't seem to be possible to instantiate a new WKNavigationAction of my own (.request is read-only).</p>

<p>What is the right way to unit test logic in WKNavigationDelegate functions?</p>
",https://stackoverflow.com/questions/49277915/unit-testing-wknavigationdelegate-functions,"['swift', 'io', 'webkit']",3869,TRUE,12,1
Unit testing DateTime.Now,"<p>Suppose there is class</p>

<pre><code>class Task
{
   public DateTime StartedDate {get; private set;}

   public Task() 
   {
      StartedDate = DateTime.Now;
   }
}
</code></pre>

<p>I want to test condition that work on a task begins after the task is created. So <code>StartedDate</code> should always be <em>21 January</em> if the task was created 21 January. I'm not sure if passing some time provider to task constructor is a good idea.</p>
",https://stackoverflow.com/questions/48364973/unit-testing-datetime-now,"['c#', '.net', 'unit-testing', 'oop', 'datetime']",904,TRUE,3,1
Elasticsearch unit testing,"<p>With the latest <code>elasticsearch 6.4.1</code> I would like to implement unit testing. Currently implemented unit testing as integration testing as <code>RestHighLevelClient</code> is not mockable.I see that <code>RestClient</code> though mockable cannot be set to the restHighLevelClient. I want to mock elasticsearch so that i can run tests anywhere. Any possible way using the <code>Node</code> and <code>Settings</code> i don't want a full blown cluster.</p>
",https://stackoverflow.com/questions/52453660/elasticsearch-unit-testing,"['java', 'elasticsearch']",1969,TRUE,3,1
Flutter: unit testing,"<p>I'm trying to test this function:</p>

<pre><code>  setToday(Map filters) {
    if (filters['today'] == false) {
      filters['yesterday'] = false;
      filters['lastWeek'] = false;
      filters['lastMonth'] = false;
      filters['customRange'] = false;
      filters['today'] =  true;
    } else
      filters['today'] = false;
  }
</code></pre>

<p>And this is the test:</p>

<pre><code>     test("""", (){
        Map&lt;String, bool&gt; filters = {
          ""today"" : false,
          ""yesterday"" : false,
          ""lastWeek"" : false,
          ""lastMonth"" : false,
          ""customRange"" : false,
        };

        expect(_kpiFilterViewController.setToday(filters), filters[""today""] == true);
      });
</code></pre>

<p>But the result is :</p>

<pre><code>Expected: &lt;true&gt;
  Actual: &lt;null&gt;
</code></pre>

<p>What is my mistake?</p>
",https://stackoverflow.com/questions/52816759/flutter-unit-testing,"['unit-testing', 'testing', 'dart', 'flutter']",2396,TRUE,3,1
Unit Testing Marten,"<p>I'm putting together an implementation of IdentityServer4, using PostgreSQL as the database, Marten as the ORM, and GraphQL as the API.  So far, it's working great at runtime.  However, I'm also trying to get unit tests in place, and am running into an issue.  I have a custom implementation of IdentityServer4's IClientStore interface, where the implementation of the FindClientByIdAsync method looks thus:</p>

<pre><code>public async Task&lt;Client&gt; FindClientByIdAsync(string clientId)
{
    var client = await _documentSession.Query&lt;dbe.Client&gt;().FirstOrDefaultAsync(c =&gt; c.ClientId == clientId);
    return _mapper.Map&lt;Client&gt;(client); // AutoMapper conversion call
}
</code></pre>

<p>This works great at runtime.  However, I have the following test that I'm trying to put in place to exorcise this code:</p>

<pre><code>[Fact]
public async Task FindClientByIdReturnsClient()
{
    var clients = new []
    {
        new dbe.Client
        {
            ClientId = ""123""
        }
    }.AsQueryable();

    var queryable = new MartenQueryable&lt;dbe.Client&gt;(clients.Provider);
    // _documentSession is a Moq Mock
    _documentSession.Setup(x =&gt; x.Query&lt;dbe.Client&gt;()).Returns(queryable);

    var store = new ClientStore(_documentSession.Object, _mapper);

    var result = await store.FindClientByIdAsync(""123"");

    Assert.NotNull(result);
    Assert.Equal(""123"", result.ClientId);
}
</code></pre>

<p>The error I get happens when the test tries to execute the FindClientByIdAsync method:</p>

<pre><code>System.InvalidCastException : Unable to cast object of type 'System.Linq.EnumerableQuery`1[StaticSphere.Persona.Data.Entities.Client]' to type 'Marten.Linq.IMartenQueryable'.
</code></pre>

<p>If anyone is familiar with Marten can could provide some insight, that would be great! I've done my Google time, and haven't found anything concrete on the subject.</p>
",https://stackoverflow.com/questions/51814633/unit-testing-marten,"['c#', 'moq', 'identityserver4', 'marten']",1508,TRUE,2,1
Unit testing in vuejs,"<p>I am trying to configure/run my first unit test for Vuejs. But I can't get past the configuration issues. I have tried installing the libraries but for some reason I keep getting errors.</p>

<p>Here is what an example of my code looks like:</p>

<h3>My directory structure:</h3>

<pre><code>   hello/
     dist/
     node_modules/
     src/
      components/
        hello.vue
     test/
      setup.js
      test.spec.js
    .babelrc
     package.json
     webpack.config.js
</code></pre>

<h3>Contents inside my files</h3>

<p>src/components/hello.vue</p>

<pre><code>&lt;template&gt; &lt;div&gt; {{message}} &lt;/div&gt; &lt;/template&gt;
&lt;script&gt;
export default {
  name: 'hello',
  data () { return message: 'Hi' },
  created () {
    // ...
  }
}
</code></pre>

<p>test/setup.js</p>

<pre><code>// setup JSDOM
require('jsdom-global')()

// make expect available globally
global.expect = require('expect')
</code></pre>

<p>test/test.spect.js</p>

<pre><code>import { shallow } from 'vue/test-utils'
import  { hello} from '../../../src/components/hello.vue'

describe('hello', () =&gt; {
  // just testing simple data to see if it works
  expect(1).toBe(1)
})
</code></pre>

<p>.babelrc</p>

<pre><code>{
  ""env"": {
    ""development"": {
      ""presets"": [
        [
          ""env"",
          {
            ""modules"": false
          }
        ]
      ]
    },
    ""test"": {
      ""presets"": [
        [
          ""env"",
          {
            ""modules"": false,
            ""targets"": {
              ""node"": ""current""
            }
          }
        ]
      ],
      ""plugins"": [
        ""istanbul""
      ]
    }
  }
}
</code></pre>

<p>package.json</p>

<pre><code>...
  ""scripts"": {
    ""build"": ""webpack -p"",
    ""test"": ""cross-env NODE_ENV=test nyc mocha-webpack --webpack-config webpack.config.js --require test/setup.js test/**/*.spec.js""
  },
""devDependencies"": {
    ""babel-core"": ""^6.26.0"",
    ""babel-loader"": ""^7.1.2"",
    ""babel-preset-env"": ""^1.6.1"",
    ""cross-env"": ""^5.1.1"",
    ""css-loader"": ""^0.28.7"",
    ""file-loader"": ""^1.1.5"",
    ""node-sass"": ""^4.7.2"",
    ""sass-loader"": ""^6.0.6"",
    ""vue-loader"": ""^13.5.0"",
    ""vue-template-compiler"": ""^2.5.9"",
    ""webpack"": ""^3.10.0"",
    ""webpack-dev-server"": ""^2.9.7"",
    ""jsdom"": ""^11.3.0"",
    ""jsdom-global"": ""^3.0.2"",
    ""mocha"": ""^3.5.3"",
    ""mocha-webpack"": ""^1.0.0-rc.1"",
    ""nyc"": ""^11.4.1"",
    ""expect"": ""^21.2.1"",
    ""@vue/test-utils"": ""^1.0.0-beta.12""
  },
  ...
""nyc"": {
    ""include"": [
      ""src/**/*.(js|vue)""
    ],
    ""instrument"": false,
    ""sourceMap"": false
  }
</code></pre>

<p>and finally my webpack.config.js
...</p>

<pre><code>if(process.env.NODE_ENV == ""test"") {
  module.exports.externals = [ require ('webpack-node-externals')()]
  module.exports.devtool = 'inline-cheap-module-source-map'
}
</code></pre>

<p>now when I run <code>npm test</code> from my root folder <code>hello/</code> I get this error: </p>

<pre><code>&gt; hello@1.0.0 test C:\Users\john\vue-learn\hello
&gt; npm run e2e


&gt; hello@1.0.0 e2e C:\Users\john\vue-learn\hello
&gt; node test/e2e/runner.js

Starting selenium server... started - PID:  12212

[Test] Test Suite
=====================

Running:  default e2e tests
 × Timed out while waiting for element &lt;#app&gt; to be present for 5000 milliseconds.  - expected ""visible"" but got: ""not found""
    at Object.defaultE2eTests [as default e2e tests] (C:/Users/john/Google Drive/lab/hello/test/e2e/specs/test.js:13:8)
    at _combinedTickCallback (internal/process/next_tick.js:131:7)


FAILED:  1 assertions failed (20.281s)

 _________________________________________________

 TEST FAILURE:  1 assertions failed, 0 passed. (20.456s)

 × test

   - default e2e tests (20.281s)
   Timed out while waiting for element &lt;#app&gt; to be present for 5000 milliseconds.  - expected ""visible"" but got: ""not found""
       at Object.defaultE2eTests [as default e2e tests] (C:/Users/john/Google Drive/lab/hello/test/e2e/specs/test.js:13:8)
       at _combinedTickCallback (internal/process/next_tick.js:131:7)

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! hello@1.0.0 e2e: `node test/e2e/runner.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the hello@1.0.0 e2e script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\john\AppData\Roaming\npm-cache\_logs\2018-04-03T23_53_15_976Z-debug.log
npm ERR! Test failed.  See above for more details.
</code></pre>

<p>I don't know why this happens. When I installed my webpack project at first I didn't install a testing library with the npm init command so there are no conflicts, but still I get that error: </p>

<h3>update (after bounty)</h3>

<p>I'm just trying to test my vuejs application. Hopefully with jasmine/karma. If anyone knows how to integrate these into a simple app and run the firsts test, I can take it from there. My problem is not writing tests but configuring it</p>
",https://stackoverflow.com/questions/49640812/unit-testing-in-vuejs,"['unit-testing', 'vue.js', 'vuejs2', 'karma-jasmine', 'vue-test-utils']",2900,TRUE,10,2
Unit Testing ViewModel,"<p>I'm trying to use MVVM design pattern and try to do some Unit Test on a View Model. In the View Model the repository implementation is injected. What I'm trying to do is to test the View Model with a mocked repository. This is my code:</p>

<p><strong>IntroViewModel</strong></p>

<pre><code>class IntroViewModel : ViewModel() {

   @Inject
   lateinit var userRepository: UserRepositoryImpl

   init {
      App.appComponent.inject(this)
   }

   var loggedIn: MutableLiveData&lt;Boolean&gt; = MutableLiveData()

   fun checkLoginStatus() {
      loggedIn.postValue(userRepository.isUserLoggedIn())
   }
}
</code></pre>

<p><strong>UserRepositoryImpl</strong></p>

<pre><code>class UserRepositoryImpl: UserRepository {
    override fun isUserLoggedIn(): Boolean {
        return FirebaseAuth.getInstance().currentUser!=null
    }
}
</code></pre>

<p><strong>IntroTest</strong></p>

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

    @get:Rule
    val rule = InstantTaskExecutorRule()

    lateinit var introViewModel: IntroViewModel

    @Before
    fun setup() {
        introViewModel = IntroViewModel()
    }

    @Test
    fun checkFirebaseState_test() {

        val shouldReturn = true

        introViewModel.checkLoginStatus()

        assertEquals(shouldReturn, introViewModel.loggedIn.value)

    }
}
</code></pre>

<p>I want at the moment of the test to use another UserRepository implementation so that the test will not rely on FirebaseAuth or other source of information.</p>
",https://stackoverflow.com/questions/51788019/unit-testing-viewmodel,"['android', 'unit-testing', 'mvvm', 'kotlin', 'viewmodel']",364,FALSE,2,0
Unit testing @Validated,"<p>Looking for some help in unit testing while @Validated is being used.
I have two methods with following signature.
Here ""A"" and ""B"" are marker interfaces.</p>

<pre><code>public void processA (@Validated(A.class) final MyRequest myRequest)

public void processB (@Validated(B.class) final MyRequest myRequest)
</code></pre>

<p>And MyRequest has validations on its attributes like this.</p>

<pre><code>@NotBlank(groups = A.class)
@NotNull(groups = B.class)
private String id;
</code></pre>

<p>In my test cases, how can I introduce which marker interface the test cases should use and apply on the bean.</p>

<p>Cheers,</p>

<p>abk</p>
",https://stackoverflow.com/questions/49725543/unit-testing-validated,"['java', 'spring', 'validation', 'junit']",63,FALSE,1,0
Unit testing RxJava,"<p>I am developing a unit test in Android to test my <code>RxJava2</code> code that interacts with <code>Socket.IO</code>. The code works well when I run from <code>MainActivity()</code>. In unit test I am using below code to test <code>Observable</code>:</p>

<pre><code>ObservableFactory.sharedInstance.connectionStatusObservable.blockingForEach(connectionStatus -&gt; {
    System.out.println(connectionStatus.getStatus());
});
</code></pre>

<p>The expected output is this:</p>

<pre><code>Connecting
Connected
</code></pre>

<p>But it actually throws <code>NullPointerException</code> in <code>EventThread</code> after showing <code>Connecting</code> state:</p>

<pre><code>Connecting
Jan 29, 2018 6:57:15 PM io.socket.thread.EventThread$2 run
SEVERE: Task threw exception
java.lang.NullPointerException
    at io.socket.engineio.client.HandshakeData.&lt;init&gt;(HandshakeData.java:21)
    at io.socket.engineio.client.HandshakeData.&lt;init&gt;(HandshakeData.java:16)
    at io.socket.engineio.client.Socket.onPacket(Socket.java:539)
    at io.socket.engineio.client.Socket.access$1000(Socket.java:36)
    at io.socket.engineio.client.Socket$5.call(Socket.java:335)
    at io.socket.emitter.Emitter.emit(Emitter.java:117)
    at io.socket.engineio.client.Transport.onPacket(Transport.java:126)
    at io.socket.engineio.client.transports.Polling.access$700(Polling.java:18)
    at io.socket.engineio.client.transports.Polling$2.call(Polling.java:127)
    at io.socket.engineio.parser.Parser.decodePayload(Parser.java:241)
    at io.socket.engineio.client.transports.Polling._onData(Polling.java:135)
    at io.socket.engineio.client.transports.Polling.onData(Polling.java:102)
    at io.socket.engineio.client.transports.PollingXHR$5$1.run(PollingXHR.java:125)
    at io.socket.thread.EventThread$2.run(EventThread.java:80)
    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)

Exception in thread ""EventThread"" java.lang.NullPointerException
    at io.socket.engineio.client.HandshakeData.&lt;init&gt;(HandshakeData.java:21)
    at io.socket.engineio.client.HandshakeData.&lt;init&gt;(HandshakeData.java:16)
    at io.socket.engineio.client.Socket.onPacket(Socket.java:539)
    at io.socket.engineio.client.Socket.access$1000(Socket.java:36)
    at io.socket.engineio.client.Socket$5.call(Socket.java:335)
    at io.socket.emitter.Emitter.emit(Emitter.java:117)
    at io.socket.engineio.client.Transport.onPacket(Transport.java:126)
    at io.socket.engineio.client.transports.Polling.access$700(Polling.java:18)
    at io.socket.engineio.client.transports.Polling$2.call(Polling.java:127)
    at io.socket.engineio.parser.Parser.decodePayload(Parser.java:241)
    at io.socket.engineio.client.transports.Polling._onData(Polling.java:135)
    at io.socket.engineio.client.transports.Polling.onData(Polling.java:102)
    at io.socket.engineio.client.transports.PollingXHR$5$1.run(PollingXHR.java:125)
    at io.socket.thread.EventThread$2.run(EventThread.java:80)
    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>

<p>I have also tried to use <code>TrampolineScheduler</code> as a rule in the beginning of test:</p>

<pre><code>@Rule
public TrampolineSchedulerRule trampolineSchedulerRule = new TrampolineSchedulerRule();
</code></pre>

<p>But still I am receiving above error message. If I run the following test then it works well:</p>

<pre><code>ConnectionStatus status = ObservableFactory.sharedInstance.connectionStatusObservable.blockingFirst();
assertTrue(status.getStatus() == ConnectionStatus.Status.Connecting);
</code></pre>

<p><strong>The problem is with <code>Connected</code> state where it successfully establish the connection with <code>Socket.IO</code> but somehow unit test is throwing error on it even if it works well in <code>MainActivity()</code>.</strong></p>

<p>Any idea what I am doing wrong?</p>
",https://stackoverflow.com/questions/48504666/unit-testing-rxjava,"['android', 'unit-testing', 'rx-java', 'rx-java2', 'rx-android']",1422,FALSE,1,1
Unit testing AWS: step function,"<p>I am beginner in AWS and i have created my first AWS step function given below, Now next step is to unit test this step function. I independently unit tested my lambda function now i got stuck and have no idea about, how can i proceed for unit testing of step function.</p>

<p>I also get a question in my mind is it worth doing unit testing of step function,some time feel can it be done or not since it is just a json.</p>

<p>I tried to search but i didn't got any clue on internet or AWS documentation 
Any help will be appreciated any blog on this or any sample use case 
Thanks </p>

<pre><code>{
""Comment"": ""An example of the Amazon States Language using a choice state."",
""StartAt"": ""LoginState"",
States"": {
""LoginState"": {
  ""Type"": ""Task"",
  ""Resource"": ""arn:aws:lambda:us-east-1:170344690019:function:myfirstLogin"",
  ""Next"": ""ChoiceState""
},
""ChoiceState"": {
  ""Type"" : ""Choice"",
  ""Choices"": [
    {
      ""Variable"": ""$.success"",
      ""BooleanEquals"": true,
      ""Next"": ""logoutState""
    },
    {
      ""Variable"": ""$.success"",
      ""BooleanEquals"": false,
      ""Next"": ""DefaultState""
    }
  ],
  ""Default"": ""DefaultState""
},

""logoutState"": {
  ""Type"" : ""Task"",
  ""Resource"": ""arn:aws:lambda:us-east-1:170344690019:function:myFirstLogout"",
  ""End"": true
},


""DefaultState"": {
  ""Type"": ""Fail"",
  ""Error"": ""DefaultStateError"",
  ""Cause"": ""No Matches!""
}

}
}
</code></pre>
",https://stackoverflow.com/questions/51095883/unit-testing-aws-step-function,"['amazon-web-services', 'unit-testing', 'aws-step-functions']",13162,TRUE,17,4
Unit testing WatchService,"<p>How can I unit test a watchservice like this:</p>

<pre><code>/**
 * Function to look for changes in a determinate directory
 * @param directory is the directory where to look for the changes
 * @return return a boolean that is true if have changes or false if not
 */

private static boolean watchDirectory(final String directory){

    boolean flag = false;

    Path path = Paths.get(directory);
    try {
        // get watch service which will monitor the directory
        WatchService watcher = path.getFileSystem().newWatchService();
        // associate watch service with the directory to listen to the event types
        path.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);
        System.out.println(""\nMonitoring directory for changes..."");
        // listen to events
        WatchKey watchKey = watcher.take();
        // get list of events as they occur
        List&lt;WatchEvent&lt;?&gt;&gt; events = watchKey.pollEvents();

        for (WatchEvent event : events) {
            flag = false;
            //check if the events refers to a new file created
            if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
                flag = true;

                System.out.println(""Created: "" + event.context().toString() + "" ;"");
            }
        }
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }
    return flag;
}
</code></pre>

<p>It is looking for changes in a directory, if a new file is created it returns a flag with value true, if i didnt find changes return the flag as false.</p>
",https://stackoverflow.com/questions/52588728/unit-testing-watchservice,"['java', 'watchservice']",1405,TRUE,1,2
Ionic unit testing,"<p>When I suppose to test a method, I got the error like</p>

<blockquote>
  <p>TypeError: Cannot read property '_getPortal' of undefined</p>
</blockquote>

<p>And my method here</p>

<pre><code>onAddRole() {
    this.roleService.getAllRoles() // Here i m getting the error.
      .take(1)
      .subscribe(
        data =&gt; {
          // stuffs
        },
        err =&gt; {
          // stuffs
        }
      );
  }
</code></pre>

<p>Can I get any help on this?</p>
",https://stackoverflow.com/questions/50675876/ionic-unit-testing,"['unit-testing', 'ionic-framework']",40,FALSE,0,0
CakePHP unit testing,"<p>I am new to php unit testing and every time I try to learn something it doesn't work as the cakephp documentation</p>

<p>1- Starting with the fixtures : I ran the command  <code>bin/cake bake fixture tablename</code> and tried to execute the test (which is basically empty) : The table gets deleted from the database (I read that its a normal behavior but its not re-created, I should create It everytimee?)</p>

<p>2- I now want to try how it actually work in the test controller and added a basic function and ran the test to this specific controller. I get the error :</p>

<pre><code>Use of undefined constant CONFIG - assumed 'CONFIG' (this will throw an Error in a future version of PHP)

/vendor/cakephp/cakephp/src/Routing/Router.php:1170
</code></pre>

<p>How can I fix all this ? </p>
",https://stackoverflow.com/questions/53339663/cakephp-unit-testing,"['cakephp', 'cakephp-3.0', 'phpunit']",330,FALSE,0,0
Symfony unit testing,"<p>Following is my directory structure:</p>

<pre><code>     |-vendor
     |---bin
     |---phpunit
     |---autoload.php
     |---psr
     |---sebastian
     |---phar-io
     |---composer
     |---symfony
     |-.htaccess
     |-composer.lock
     |-includes
     |---application_top.php
     |-routes
     |---routes.php
     |-modules
     |---Controllers
     |----CheckoutGatewayController.php
     |-tests
     |---Controllers
     |----tests_common_includes.php
     |-composer.phar
</code></pre>

<p>I am trying to run <code>./vendor/bin/simple-phpunit --bootstrap tests/tests_common_includes.php tests/Controllers/CheckoutGatewayTests.php</code> from my base directory but it gives me error <code>Class 'tests/Controllers/CheckoutGatewayTests' could not be found in 'tests/Controllers/CheckoutGatewayTests.php'.</code> </p>

<p>If I try <code>./vendor/bin/phpunit --bootstrap tests/tests_common_includes.php tests/Controllers/CheckoutGatewayTests.php</code> then I get the error <code>Unable to guess the Kernel directory</code>. I tried to look up symfony's documentation : it suggests using either <code>-c app</code> option or changing <code>phpunit.dist.xml</code> file. But I have neither of those in my directory. There is no xml file and no app folder.</p>

<p>How can I execute my tests? My test file <code>CheckoutGatewayTests.php</code> looks like this : </p>

<pre><code>     &lt;?php

     use \Controllers\CheckoutGatewayController;
     use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

     class CheckoutGatewayTests extends WebTestCase {


     public function testChargebackCallback() {
             $client = static::createClient();
             $client-&gt;request('GET', '/post/hello-world');
         }

     }
</code></pre>

<p>Edit: my composer.json file </p>

<pre><code>        {
        ""require"": {
            ""guzzlehttp/guzzle"": ""~6.0"",
            ""psr/log"": ""^1.0"",
            ""zircote/swagger-php"": ""^2.0"",
            ""sentry/sentry"": ""^1.8"",
            ""aws/aws-sdk-php"": ""^3.52"",
            ""league/flysystem-aws-s3-v3"": ""~1.0"",
            ""symfony/routing"": ""^3.4"",
            ""symfony/http-kernel"": ""^3.4"",
            ""symfony/dependency-injection"": ""^3.4"",
            ""symfony/framework-bundle"": ""^3.4"",
            ""prbdias/mbway-php"": ""0.1""
        },

        ""require-dev"": {
            ""phpunit/phpunit"": ""^6""
        },

        ""config"": {
            ""optimize-autoloader"": true
        },

        ""autoload"": {
            ""psr-4"": {
                """": [""modules/"", ""tests/"",""routes/""]
            }
        }

    }
</code></pre>
",https://stackoverflow.com/questions/51960029/symfony-unit-testing,"['php', 'symfony', 'phpunit']",217,FALSE,0,0
Unit Testing HttpContext.GetOwinContext(),"<p>I just started working on creating unit test for our codes. We're using ASP.NET MVC 4 and Owin middleware for our authentication and other data and user database operation.</p>

<p>So to start we have several controllers and based controller. On the based controller we have added the common codes like <code>UserManager</code>, <code>RoleManager</code>, etc.. These codes uses the <code>HttpContext.GetOwinContext</code>. When implementing a Unit test on one of the controller I'm required to create a unit test of the base controller which I'm currently struggling to do.</p>

<p>The codes would look like this:</p>

<pre><code>protected IAuditRepository Audit
{
    get { return _audit ?? (_audit = DependencyResolver.Current.GetService&lt;IAuditRepository&gt;()); }
}

protected UserManager UserManager
{
    get { return HttpContext.GetOwinContext().GetUserManager&lt;UserManager&gt;(); }
}
</code></pre>

<p>So I have research on how to test HttpContext.GetOwinContext however, most of the things I see was not clear and does not provide much information for me to be able create a test.</p>

<p>I have tried to use Moq successfully for Dependency Injection however I was not able in HttpContext. Please can anyone put me in the right path oh how to test these kind of codes?</p>
",https://stackoverflow.com/questions/51021282/unit-testing-httpcontext-getowincontext,"['c#', 'asp.net', 'unit-testing', 'owin']",945,TRUE,0,1
Servlets unit testing,"<p>I have a problem with testing my servlets. I think it happened because I use context listner for init my dao, but I can't fix it. App works, but tests doesn't work.</p>

<p>One of my servlets, that show list of the users:</p>

<pre><code>public class AllUsersServlet extends HttpServlet {
private static final String LIST_OF_USERS = ""/WEB-INF/view//usersList.jsp"";
private static final String DAO = ""userDao"";
private static final String USERS = ""users"";
private UserDaoImpl userDao;

@Override
public void init() throws ServletException {
    userDao = (UserDaoImpl) getServletContext().getAttribute(DAO);
}

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    List&lt;User&gt; users = userDao.getAll();
    req.getServletContext().setAttribute(USERS, users);
    req.getRequestDispatcher(LIST_OF_USERS).forward(req, resp);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    super.doPost(req, resp);
}
}
</code></pre>

<p>One of my unit tests, that check AllUsersServlet:</p>

<pre><code>public class AllUsersServletTest {
private static final String PAGE = ""/WEB-INF/view//list.jsp"";

@Test
public void whenDoGetThenReturnListPage() throws IOException, ServletException {
    AllUsersServlet allUsersServlet = new AllUsersServlet();

    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);
    RequestDispatcher dispatcher = mock(RequestDispatcher.class);
    ServletContext context = mock(ServletContext.class);

    when(request.getServletContext()).thenReturn(context);
    when(request.getRequestDispatcher(PAGE)).thenReturn(dispatcher);

    allUsersServlet.doGet(request, response);

    verify(request, times(1)).getRequestDispatcher(PAGE);
    verify(request, never()).getSession();
    verify(dispatcher).forward(request, response);
}
}
</code></pre>

<p>So when I start my test it failed with nullpointer, stacktrace:</p>

<pre><code>java.lang.NullPointerException
at ru.skilanov.controller.AllUsersServlet.doGet(AllUsersServlet.java:55)
at ru.skilanov.controller.AllUsersServletTest.whenDoGetThenReturnListPage(AllUsersServletTest.java:40)
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.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)


Process finished with exit code -1
</code></pre>
",https://stackoverflow.com/questions/50211433/servlets-unit-testing,"['java', 'unit-testing', 'testing', 'servlets', 'junit']",1064,TRUE,0,3
Jest unit testing,"<p>I am using Jest for writing coded unit test for my project, In one of the code the lambda function is inside the try and catch block like</p>

<pre><code>   try {
    ""use strict"";
    const somevalue = require(""./somefile"")

    export.somefunction = ((event,context,()=&gt;{

    return something

    }).catch((error)=&gt;{

      return error
    }

    }
    catch(exception){
    console.log(exception)
    }
</code></pre>

<p>I want to understand two things
a) What purpose does writing lambda function inside the try/catch block do, 
   considering the lambda exception is handled
b) Second how write the jest coded unit test case for try/catch block</p>
",https://stackoverflow.com/questions/53015534/jest-unit-testing,"['node.js', 'aws-lambda', 'jestjs']",84,FALSE,0,0
WebObjects unit testing,"<p>I want to do unit tests on a framework called WebObjects using java with the IDE eclipse. I have tried to use junit and wounit. The thing is I always encounter the problem, that I cannot create a WOComponent and test its method because I don't have access to a WOContext. So my question would be if someone can give me an example different than the one found on <a href=""http://hprange.github.io/wounit/usage.html"" rel=""nofollow noreferrer"">http://hprange.github.io/wounit/usage.html</a> of how to create a WOContext through the framework of wounit or is there a way to create it my self? </p>
",https://stackoverflow.com/questions/48572378/webobjects-unit-testing,"['java', 'eclipse', 'junit4', 'webobjects']",79,FALSE,0,1
Unit testing __main__.py,"<p>I have a Python package (Python 3.6, if it makes a difference) that I've designed to run as 'python -m <em>package</em> <em>arguments</em>' and I'd like to write unit tests for the __main__.py module. I specifically want to verify that it sets the exit code correctly. Is it possible to use runpy.run_module to execute my __main__.py and test the exit code? If so, how do I retrieve the exit code?</p>

<p>To be more clear, my __main__.py module is very simple. It just calls a function that has been extensively unit tested. But when I originally wrote __main__.py, I forgot to pass the result of that function to exit(), so I would like unit tests where the main function is mocked to make sure the exit code is set correctly. My unit test would look something like:</p>

<pre><code>@patch('my_module.__main__.my_main', return_value=2)
def test_rc2(self, _):
    """"""Test that rc 2 is the exit code.""""""
    sys.argv = ['arg0', 'arg1', 'arg2', …]
    runpy.run_module('my_module')
    self.assertEqual(mod_rc, 2)
</code></pre>

<p>My question is, how would I get what I’ve written here as ‘mod_rc’?</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/49412706/unit-testing-main-py,"['python', 'python-unittest', 'runpy']",6410,TRUE,8,3
AngularJS TypeScript unit testing,"<p>I am struggle with create proper unit tests for the angularjs (v1.4.9) application which contains both javascript files (with jasmine tests) and typescript files (with no tests at all, now I am trying to use Mocha, but it can be any framework). </p>

<p>Hence it hybrid and an old angularjs without modules, I decided to compile all .ts to one <code>bundle.js</code> file, due to avoid files ordering problem (which occurs when I have single .js file per .ts and inject it with gulp task to <code>index.html</code>).</p>

<p>My tsconfig.js:</p>

<pre><code>{
    ""compileOnSave"": true,
    ""compilerOptions"": {
        ""noImplicitAny"": false, 
        ""removeComments"": false,
        ""outFile"": ""./wwwroot/bundle.js"",
        ""sourceMap"": true,
        ""inlineSources"": true,
        ""module"": ""amd"",
        ""moduleResolution"": ""node"",
        ""target"": ""es5"",
        ""sourceRoot"": ""./wwwroot""        
    },
    ""include"": [
      ""wwwroot/app/**/*""
    ],
    ""exclude"": [
      ""node_modules/**/*"",
      ""tests/**/*""      
    ]
}
</code></pre>

<p>example of tested class:</p>

<pre><code>///&lt;reference path=""../models/paymentCondition.model.ts""/&gt;
///&lt;reference path=""../../../../../node_modules/@types/angular/index.d.ts""/&gt;

'use strict';


module PaymentCondition {

    export class ConnectedCustomersListController {
        name: string;

        static $inject = ['paymentCondition'];
        constructor(private paymentCondition: PaymentConditionModel) {
            this.name = paymentCondition.Name;
            this.bindData();
        }



        bindData() {
            // do something
        }                
    }

    angular
        .module('app.paymentConditions')
        .controller('ConnectedCustomersListController', ConnectedCustomersListController);
}
</code></pre>

<p>My module declaration:</p>

<pre><code>///&lt;reference path=""../../../../node_modules/@types/angular/index.d.ts""/&gt;

'use strict';

module PaymentCondition {

    angular.module('app.paymentConditions', ['ui.router', 'ui.bootstrap']);
}
</code></pre>

<p>and I am 'injecting' this module to main module file, which is already in javascript- <code>App.module.js</code>.: </p>

<pre><code>(function () {
    'use strict';

    var module = angular.module('app', [       
        'app.paymentCondition',
        'ui.router',     
        'ui.bootstrap',        
    ]);

})();
</code></pre>

<p>and finally my test class: </p>

<pre><code>///&lt;reference path=""../../../node_modules/@types/angular/index.d.ts""/&gt;
///&lt;reference path=""../../../wwwroot/app/domain/paymentConditions/connectedCustomersList/connectedCustomersList.controller.ts""/&gt;
///&lt;reference path=""../../../node_modules/@types/angular-mocks/index.d.ts""/&gt;

import { expect } from 'chai';
import ""angular-mocks/index"";
import * as angular from ""angular"";


describe(""app.paymentConditions.connectedCustomersList"", () =&gt; {
    var mock;
    // inject main module
    beforeEach(angular.mock.module('app.paymentConditions'));
    beforeEach(angular.mock.inject(($controller: ng.IControllerService) =&gt; {

        mock = {           
            connectedCustomersListModel: {
                columnDefinitions() {
                }
            },
            paymentCondition: {},
            createController(): PaymentCondition.ConnectedCustomersListController {
                return $controller&lt;PaymentCondition.ConnectedCustomersListController &gt;('ConnectedCustomersListController', {
                    connectedCustomersListModel: mock.connectedCustomersListModel,

                });
            }
        };
    }));

    describe(""ConnectedCustomersListController"", () =&gt; {
        var controller: PaymentCondition.ConnectedCustomersListController;
        beforeEach(() =&gt; {
            controller = mock.createController();
        });

        it(""should be defined"", () =&gt; {
            expect(controller).not.undefined;
        });
    });
});
</code></pre>

<p>when I am trying to run <code>mocha</code> tests with command:</p>

<pre><code>./node_modules/.bin/mocha --compilers ts:ts-node/register ./tests/**/*.spec.ts
</code></pre>

<p>I have this exception:</p>

<pre><code>ReferenceError: define is not defined
    at Object.&lt;anonymous&gt; (C:\Projects\App.Frontend\EasyFrontend\src\EasyFrontend\tests\paymentConditions\connec
edCustomersList\connectedCustomersList.controller.spec.ts:5:1)
    at Module._compile (module.js:643:30)
    at Module.m._compile (C:\Projects\App.Frontend\EasyFrontend\src\EasyFrontend\node_modules\ts-node\src\index.
s:422:23)
    at Module._extensions..js (module.js:654:10)
    at Object.require.extensions.(anonymous function) [as .ts] (C:\Projects\App.Frontend\EasyFrontend\src\EasyFr
ntend\node_modules\ts-node\src\index.ts:425:12)
    at Module.load (module.js:556:32)
    at tryModuleLoad (module.js:499:12)
    at Function.Module._load (module.js:491:3)
    at Module.require (module.js:587:17)
    at require (internal/module.js:11:18)
    at C:\Projects\App.Frontend\EasyFrontend\src\EasyFrontend\node_modules\mocha\lib\mocha.js:231:27
    at Array.forEach (&lt;anonymous&gt;)
    at Mocha.loadFiles (C:\Projects\App.Frontend\EasyFrontend\src\EasyFrontend\node_modules\mocha\lib\mocha.js:2
8:14)
    at Mocha.run (C:\Projects\App.Frontend\EasyFrontend\src\EasyFrontend\node_modules\mocha\lib\mocha.js:536:10)
    at Object.&lt;anonymous&gt; (C:\Projects\App.Frontend\EasyFrontend\src\EasyFrontend\node_modules\mocha\bin\_mocha:
82:18)
    at Module._compile (module.js:643:30)
    at Object.Module._extensions..js (module.js:654:10)
    at Module.load (module.js:556:32)
    at tryModuleLoad (module.js:499:12)
    at Function.Module._load (module.js:491:3)
    at Function.Module.runMain (module.js:684:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3
npm ERR! Test failed.  See above for more details.
</code></pre>

<p>I know it is because I am using <code>amd</code> module to compile my typescript to one js file, but I don't really know how to fix it. Or if it can't be fixed maybe you have some advices how to 'marrige' the type script to existing AngularJs solution.</p>

<p>Ps. I am using mocha with backed typescript compiler, because I have no idea how to run jasmine tests with this combination. </p>

<p>My Index.html:</p>

<pre><code>&lt;!DOCTYPE html&gt;
&lt;html&gt;

&lt;head ng-controller=""AppCtrl""&gt;
    &lt;meta charset=""utf-8"" /&gt;
    &lt;meta name=""viewport"" content=""width=device-width, initial-scale=1.0"" /&gt;
    &lt;meta lang=""da"" /&gt;
    &lt;title&gt;{{ Page.title() }}&lt;/title&gt;


   &lt;!-- endbuild --&gt;
    &lt;!-- inject:css --&gt;
    &lt;link rel=""stylesheet"" type=""text/less"" href=""less/site.less"" /&gt;
    &lt;!-- endinject --&gt;
    &lt;!-- build:remove --&gt;
    &lt;script src=""less/less.js""&gt;&lt;/script&gt;
    &lt;!-- endbuild --&gt;    
    &lt;!-- bower:js --&gt;
    &lt;script src=""lib/jquery/dist/jquery.js""&gt;&lt;/script&gt;
    &lt;script src=""lib/bootstrap/dist/js/bootstrap.js""&gt;&lt;/script&gt;
    &lt;script src=""lib/angular/angular.js""&gt;&lt;/script&gt;
    &lt;script src=""lib/toastr/toastr.js""&gt;&lt;/script&gt;
    &lt;script src=""lib/angular-ui-router/release/angular-ui-router.js""&gt;&lt;/script&gt;
    &lt;script src=""lib/angular-ui-grid/ui-grid.js""&gt;&lt;/script&gt;
    &lt;script src=""lib/angular-bootstrap/ui-bootstrap-tpls.js""&gt;&lt;/script&gt;
    &lt;script src=""lib/sugar/release/sugar-full.development.js""&gt;&lt;/script&gt;
    &lt;script src=""lib/ng-context-menu/dist/ng-context-menu.js""&gt;&lt;/script&gt;
    &lt;script src=""lib/ng-messages/angular-messages.js""&gt;&lt;/script&gt;
    &lt;script src=""lib/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js""&gt;&lt;/script&gt;
    &lt;script src=""lib/bootstrap-datepicker/dist/locales/bootstrap-datepicker.da.min.js""&gt;&lt;/script&gt;
    &lt;script src=""lib/angular-ui-tree/dist/angular-ui-tree.js""&gt;&lt;/script&gt;
    &lt;script src=""lib/angular-sanitize/angular-sanitize.js""&gt;&lt;/script&gt;
    &lt;script src=""lib/color-hash/dist/color-hash.js""&gt;&lt;/script&gt;
    &lt;script src=""lib/angular-ui-mask/dist/mask.js""&gt;&lt;/script&gt;
    &lt;script src=""lib/google-maps-js-marker-clusterer/src/markerclusterer.js""&gt;&lt;/script&gt;
    &lt;script src=""lib/ngDraggable/ngDraggable.js""&gt;&lt;/script&gt;
    &lt;script src=""lib/requirejs/require.js""&gt;&lt;/script&gt;
    &lt;!-- endbower --&gt;
    &lt;!-- endbuild --&gt;
    &lt;!-- build:site_js js/site.min.js --&gt;
    &lt;!-- inject:app:js -- &gt;   
    &lt;script src=""bundle.js""&gt;&lt;/script&gt;
    &lt;script src=""app/app.module.js""&gt;&lt;/script&gt;  
    &lt;script src=""app/app.route.config.js""&gt;&lt;/script&gt;
    &lt;script src=""app/app.module.config.js""&gt;&lt;/script&gt;
    &lt;script src=""app/app.constants.js""&gt;&lt;/script&gt;
    &lt;script src=""app/app.appCtrl.js""&gt;&lt;/script&gt;       
    &lt;!-- endinject --&gt;
    &lt;!-- endbuild --&gt;
    &lt;!-- endbuild --&gt;
    &lt;!-- build:remove --&gt;
    &lt;script src=""init.js""&gt;&lt;/script&gt;
    &lt;!-- endbuild --&gt;    
&lt;/head&gt;

&lt;body&gt;
    &lt;div class=""fluid-container""&gt;
        &lt;ee-global-context-menu&gt;&lt;/ee-global-context-menu&gt;
        &lt;ui-view&gt;&lt;/ui-view&gt;
    &lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
",https://stackoverflow.com/questions/48465835/angularjs-typescript-unit-testing,"['javascript', 'angularjs', 'typescript', 'mocha.js', 'tsc']",3398,TRUE,8,2
Chefspec unit-testing,"<p>I'm no developer and a newbie with Chef.</p>

<p>I created a simple recipe and tested it on a test Kitchen and it works well but when I upload it to Jenkins it won't pass. </p>

<p>Can you help me point out what I'm missing?</p>

<pre><code>Recipe:
# Recipe:: default
# Download VerneMQ
remote_file ""#{Chef::Config[:file_cache_path]}/vernemq_1.4.0-1_amd64.deb"" do
  source 'https://bintray.com/artifact/download/erlio/vernemq/deb/trusty/vernemq_1.4.0-1_amd64.deb'
end

# Install
dpkg_package 'vernemq_1.4.0-1_amd64.deb' do
  source ""#{Chef::Config[:file_cache_path]}/vernemq_1.4.0-1_amd64.deb""
  action :install
end

# Service Start
service 'vernemq' do
  action [:enable, :start]
end

# Configurations
template '/etc/vernemq/vernemq.conf' do
  source 'vernemq.conf.erb'
  owner 'root'
  group 'root'
  mode '0644'
end

template '/etc/vernemq/vmq.passwd' do
  source 'vmq.passwd.erb'
end
</code></pre>

<p>This is my unit test.</p>

<pre><code>Unit Test:
require 'spec_helper'
require 'chefspec'

describe 'vernemq::default' do
  let(:chef_run) { ChefSpec::SoloRunner.new(platform: 'ubuntu', version: '14.04').converge(described_recipe) }

  it 'downloads the remote_file' do
    expect(chef_run).to create_remote_file('#{Chef::Config[:file_cache_path]}/vernemq_1.4.0-1_amd64.deb')
  end

  it 'installs a dpkg_package' do
    expect(chef_run).to install_dpkg_package('vernemq')
  end

  it 'executes both actions' do
    expect(chef_run).to enable_service('vernemq')
    expect(chef_run).to start_service('vernemq')
  end

  it 'creates a file' do
    expect(chef_run).to create_directory('/etc/vernemq/vernemq.conf')
  end

  it 'creates a file' do
    expect(chef_run).to create_directory('/etc/vernemq/vmq.passwd')
  end
end
</code></pre>

<p>errors from Jenkins</p>

<p>01:06:57 tm_vernemq::default
01:06:58 [2018-07-19T01:06:58-07:00] WARN: Chef::Provider::AptRepository already exists!  Cannot create deprecation class for LWRP provider apt_repository from cookbook apt
01:06:58 [2018-07-19T01:06:58-07:00] WARN: Property <code>sensitive</code> of resource <code>apt_repository</code> overwrites an existing method. Please use a different property name. This will raise an exception in Chef 13. (CHEF-11)/tmp/d20180719-10648-933ma2/cookbooks/apt/resources/repository.rb:54:in <code>class_from_file'.
01:06:58 Please see https://docs.chef.io/deprecations_property_name_collision.html for further details and information on how to correct this problem. at /opt/chefdk/embedded/lib/ruby/gems/2.3.0/gems/chef-12.19.36/lib/chef/event_dispatch/dispatcher.rb:43:in</code>call'
01:06:58 [2018-07-19T01:06:58-07:00] WARN: AptRepository already exists!  Deprecation class overwrites Custom resource apt_repository from cookbook apt</p>

<pre><code>01:06:58   executes both actions
01:06:58   installs a dpkg_package (FAILED - 1)
01:06:58   creates a file (FAILED - 2)
01:06:58   creates a file (FAILED - 3)
01:06:58   downloads the remote_file (FAILED - 4)
01:06:58 
01:06:58 Failures:
01:06:58 
01:06:58   1) vernemq::default installs a dpkg_package
01:06:58      Failure/Error: expect(chef_run).to install_dpkg_package('vernemq')
01:06:58 
01:06:58        expected ""dpkg_package[vernemq]"" with action :install to be in Chef run. Other dpkg_package resources:
01:06:58 
01:06:58          dpkg_package[vernemq_1.4.0-1_amd64.deb]
01:06:58         
01:06:58      # ./test/unit/recipes/default_spec.rb:18:in `block (2 levels) in &lt;top (required)&gt;'
01:06:58 
01:06:58   2) tm_vernemq::default creates a file
01:06:58      Failure/Error: expect(chef_run).to create_directory('/etc/vernemq/vmq.passwd')
01:06:58 
01:06:58        expected ""directory[/etc/vernemq/vmq.passwd]"" with action :create to be in Chef run. Other directory resources:
01:06:58 
</code></pre>
",https://stackoverflow.com/questions/51417761/chefspec-unit-testing,"['unit-testing', 'chef-infra', 'chefspec']",231,FALSE,-1,1
Unit Testing with Laravel,"<p>I'm using PHP with Laravel 5.5 framework.
I recently started writing unitTests for my code and I got a few questions:</p>

<ol>
<li><p>What is the best way to interact with my database? 
Should I use InMemoryDB like SQLite or Mock everything with Mockery.</p></li>
<li><p>If I have an interaction with DB than that is still unitTesting or Integration Testing?</p></li>
</ol>

<p>Thank you for the answers in advence</p>
",https://stackoverflow.com/questions/53740130/unit-testing-with-laravel,"['laravel', 'unit-testing']",567,FALSE,5,1
Angular - Unit testing keypress,"<p>I have a function that detects a keypress and if the key pressed = escape, a function is fired.</p>

<p>I am having trouble with faking the KeyboardEvent itself to be passed in.</p>

<p>I saw <strong><a href=""https://stackoverflow.com/questions/41135875/unable-to-simulate-keypress-event-in-angular-2-unit-test-jasmine"">this post</a></strong>, but implementing this solution yields the following output (I console.logged the event itself):</p>

<blockquote>
  <p>LOG: KeyboardEvent{isTrusted: false}
  Chrome 68.0.3440 (Mac OS X 10.13.6) ConfirmationComponent should call onDeny when ESCAPE button pressed FAILED
      Expected spy onDeny to have been called.</p>
</blockquote>

<p><strong>component.ts</strong></p>

<pre><code>@HostListener('window:keyup', ['$event'])
  keyEvent(event: KeyboardEvent) {
    console.log(event);
    // Press escape - close dialog with simulated 'cancel' click
    if (event.code === 'Escape') {
      this.onDeny();
    }
  }

  onDeny() {
     // something is done here
  }
</code></pre>

<p><strong>test.ts</strong></p>

<pre><code>it('should autofocus on cancel button on init', () =&gt; {
    spyOn(component, 'onDeny');
    component.keyEvent(ESCAPE);
    expect(component.onDeny).toHaveBeenCalled();
  });
</code></pre>
",https://stackoverflow.com/questions/52095422/angular-unit-testing-keypress,"['javascript', 'angular', 'testing', 'karma-runner']",12210,TRUE,4,2
AOSP local Unit Testing,"<p>I'm working on an AOSP based distribution. And I'm trying to implement Local Unit Tests (not Instrumented or CTS), just plain local Unit Tests, using frameworks like <strong>jUnit</strong>, <strong>Mockito</strong>, <strong>Powermock</strong>, <strong>Hamcrest</strong> and if necessary <strong>Robolectic</strong>.</p>

<p>Currently, I'm able to build trough <code>Android.mk</code> an app like Launcher a simple Unit Test, and run it through CLI (Command Line Interface).
The problem is that when the unit test starts to get more complicated, I have issues with <strong>PowerMockito</strong>:</p>

<blockquote>
  <p>error: cannot access MemberModifier
  import static org.powermock.api.mockito.PowerMockito.whenNew;</p>
</blockquote>

<p>Anyway, my intention with this question is to know if anyone has some example of an AOSP project running with local Unit Tests.</p>
",https://stackoverflow.com/questions/50217560/aosp-local-unit-testing,"['android', 'unit-testing', 'local', 'android-source', 'android.mk']",552,FALSE,4,0
Unit Testing Database Queries,"<p><strong>Problem:</strong> So an issue that I have been running into lately as a beginner to unit testing, is dealing with classes that have heavy database usage.</p>

<p><strong>Technologies Used:</strong> Typescript, SinonJS, Node-Postgres and Jest</p>

<p><strong>Example:</strong> For the given function</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>public async insertUserDetails() {

  const confirmationCode = this.generateConfirmationCode();

  try {

    await this.db.query({
      text: 'INSERT INTO users (firstname, lastname, email, password, registration_date, confirmation_code) VALUES ($1, $2, $3, $4, $5, $6) RETURNING *',
      values: [this.firstname, this.lastname, this.email, this.password, this.registrationDate, confirmationCode]
    });


  } catch (error) {

    throw error;

  }

}</code></pre>
</div>
</div>
</p>

<p><strong>Question:</strong>
Would a suitable unit test be to make sure that the db.query() function is called with the correct sql such as the following? Or would this be considered a waste of time and a <strong><em>brittle</em></strong> test?</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>test(""should format correct sql"", async () =&gt; {

    //Test Setup
    const user = new User({
        firstname: ""John"",
        lastname: ""doe"",
        email: ""email@example.com"",
        password: ""some_password_hash"",
        registrationDate: ""some_random_date"",
    });

    //Mocks
    const queryStub = sinon.stub(user.db, ""query"");
    const confirmationCode = sinon.stub(user,'generateConfirmationCode').returns(""48fsakb8a-cfjdab"");

    const sampleQuery = {
        text: 'INSERT INTO users (firstname, lastname, email, password, registration_date, confirmation_code) VALUES ($1, $2, $3, $4, $5, $6) RETURNING *',
        values: [user.firstname, user.lastname, user.email, user.password, user.registrationDate, confirmationCode]
    }

    //Preform
    await user.insertUserDetails();

    //Assert
    sinon.assert.calledWith(queryStub, sampleQuery);


});</code></pre>
</div>
</div>
</p>

<p>Or should I skip unit tests all together on these type of functions and classes and set up an integration test database and test these cases via integration tests?</p>

<p>This is a very simplified example as I did not go into testing Database transactions, but testing transactions become an even larger can of worms, as there are multiple queries being preformed.</p>

<p>Thank you for any help! This is driving me crazy -__-</p>
",https://stackoverflow.com/questions/53550538/unit-testing-database-queries,"['javascript', 'node.js', 'unit-testing', 'jestjs', 'sinon']",3836,TRUE,4,1
Unit Testing AndroidViewModel classes,"<p>Im writting Unit Tests for my app and I've found a ""speed bump"" while writting them. While testing subclasses of <em>AndroidViewModel</em> im missing the <strong>Application</strong> parameter for its initialization. I've already read <a href=""https://stackoverflow.com/questions/50950654/androidviewmodel-and-unit-tests"">this question that uses Robolectric</a>. </p>

<p>This is what I already tried so far:</p>

<ul>
<li><strong>Using Robolectric as the question describes</strong>. As far as I understand, Robolectric can use your custom Application class for testing, the thing is im not using a custom application class as I dont need it. (the app is not that complex).</li>
<li><strong>Using mockito</strong>. Mockito throws an exception saying that the Context class cannot be mocked. </li>
<li><strong>Using the InstrumentationRegistry</strong>. I moved the test classes from the test folder to the androidTest folder, giving me access to the <em>androidTestImplementation</em> dependencies, I tried using the InstrumentationRegistry.getContext() and parse it to Application, of course this didn't worked, throwing a cast exception. I felt so dumb trying this but again, it was worth the shot.</li>
</ul>

<p>I just want to instanciate my AndroidViewModel classes so I can call their public methods, but the Application parameter is needed. What can I do for this?</p>

<pre><code>fun someTest() {
   val testViewModel = MyViewModelThatExtendsFromAndroidViewModel(**missing application parameter**)
   testViewModel.foo() // The code never reaches here as the testViewModel cant be initializated
}
</code></pre>
",https://stackoverflow.com/questions/51487892/unit-testing-androidviewmodel-classes,"['android', 'unit-testing']",2494,TRUE,4,1
Unit testing handlebar partials,"<p>I want to unit test my application using Jest which is using Handlebar as a templating engine. </p>

<p>I am able to unit test the Handlebar helpers but not able to test the Handlebar partials.</p>

<p>When I try to import the partials in the spec.js, I am getting an error:</p>

<blockquote>
  <p>Unexpected character '#' (1:2)</p>
</blockquote>

<p>Below is the partial.handlerbars file</p>

<pre><code>{{#with (resource 'some_selector') }}
 &lt;img alt=""{{altText}}"" src=""{{image-url}}"" /&gt;
{{/with}}
</code></pre>

<p>Below is the partial.spec.js</p>

<pre><code>import partial from './partial.handlebars';
const Handlebars = require('handlebars');
describe('partial suite', ()=&gt; {
  Handlebars.registerPartial('partial', partial);
  it('should always be true', ()=&gt; {
    expect(true).toBe(true);
  })  
})
</code></pre>

<p>Below is the error:</p>

<pre><code> D:/projects/src/components/partials/partial.handlebars: Unexpected character '#' (1:2)
  &gt; 1 | {{#with (resource 'some_selector') }}
      |   ^
</code></pre>
",https://stackoverflow.com/questions/51609823/unit-testing-handlebar-partials,"['javascript', 'node.js', 'handlebars.js', 'jestjs']",700,FALSE,4,0
Pytest ETL Unit testing,"<p>My requirement is do ETL testing through python pytest module.</p>

<p>I pass a job name into the pytest script and script will test for four table load testing using a for loop. </p>

<p>I have below two issues -</p>

<ol>
<li>I am not able to pass command line argument in the pytest script.</li>
<li>Though I written a for loop inside which pytest test functions are present. But my test scripts are not running for fours tables , it's only running for one table and coming out of the loop and showing the results. </li>
</ol>

<p>Any help in this regard would be helpful.</p>
",https://stackoverflow.com/questions/49691959/pytest-etl-unit-testing,"['python', 'unit-testing', 'etl', 'pytest']",1279,FALSE,4,0
Unit testing with ESP-IDF,"<p>Currently, I am working with an ESP-IDF and try to get unit testing to work.</p>

<p>I already found <a href=""https://esp-idf.readthedocs.io/en/latest/api-guides/unit-tests.html"" rel=""noreferrer"">https://esp-idf.readthedocs.io/en/latest/api-guides/unit-tests.html</a>, but there is a point which I don't understand.</p>

<p>But first, let me explain my setup:</p>

<ul>
<li>I work under Windows and have a MSYS32 shell.</li>
<li>My <code>IDF_PATH</code> points to ~/esp-idf, where my esp-idf suite sits.</li>
<li>My projects sit in ~/project_dir/subdir, however. They work as they should.</li>
</ul>

<p>If I follow the instructions in the unit test guides, I can build the test cases which are built into the system. But it does not find the unit tests of my application. This is clear, as they sit somewhere completely else.</p>

<p>What am I supposed to do now? Perferrably without tampering with the default unit test app too much?</p>

<p>I can see several approaches, but I don't know what is the intended way to add own components resp. their test cases into the said app:</p>

<ul>
<li>Should I add the project paths somewhere into the unit test app?</li>
<li>Should I copy the unit test app and add it to my projects?</li>
<li>Should I create a folder in my project and add a link to the unit test app?</li>
</ul>
",https://stackoverflow.com/questions/51176779/unit-testing-with-esp-idf,"['unit-testing', 'embedded', 'esp32']",3480,TRUE,11,1
Angular - Unit testing Subject()?,"<p>I have a Angular service that simply uses a Subject, but I am unsure of how to write unit tests for it.</p>

<p>I saw [this thread][1], but I didn't find it terribly helpful.</p>

<p>I have attempted to mock <code>next()</code> but I am more than a little lost.</p>
",https://stackoverflow.com/questions/52091882/angular-unit-testing-subject,"['javascript', 'angular', 'typescript', 'testing', 'karma-runner']",13408,TRUE,3,2
Unit testing D library,"<p>The built-in unit testing functionality (<code>unittest {...}</code> code blocks) seems to only be activated when running.</p>

<p>How can I activate unit tests in a library with no <code>main</code> function?</p>

<p>This is somewhat related to <a href=""https://stackoverflow.com/q/35075253/2658159"">this SO question</a>, although the accepted answer there deals with a workaround via the <code>main</code> function.</p>

<p>As an example, I would expect unit testing to fail on a file containing only this code:</p>

<pre><code>int foo(int i) { return i + 1; }

unittest {
  assert(foo(1) == 1); // should fail
}
</code></pre>

<p>You'll notice I don't have <code>module</code> declared at the top. I'm not sure if that matters for this specific question, but in reality I would have a <code>module</code> statement at the top.</p>
",https://stackoverflow.com/questions/49864803/unit-testing-d-library,"['unit-testing', 'tdd', 'd']",125,TRUE,3,1
Unit testing login method,"<p>I am developing an Android application where testing is part of development process. Testing in general is new domain for me therefore, i struggle often.      I need an advice on unit testing a method which I use to perform a user login. Since method is void and implements callbacks I assume that either class or some of the objects should be mocked. In my application I use JUnit, Robolectric and Mockito for testing purposes.</p>

<p>I was able to perform a test to check if method with its parameters is being called but I am curious(dont know) how can I test the onResponse &amp; onErrorResponse callbacks.  I have provided the code below. Thanks in advance.</p>

<pre><code> public void loginUser(String email,String pass){
        try {
            requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
            StringRequest request = new StringRequest(Request.Method.POST, Url+""/checkUser.php"", new Response.Listener&lt;String&gt;() {
                @Override
                public void onResponse(String response) {

                    if(response.contains(""present"")){
                        Toast.makeText(getActivity(), ""Welcome"", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(getActivity(), MainActivity.class);
                        startActivity(intent);
                    }
                    else{
                        Toast.makeText(getActivity(), response, Toast.LENGTH_SHORT).show();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(getActivity(), ""Error"", Toast.LENGTH_SHORT).show();
                }
            }){
                @Override
                protected Map&lt;String, String&gt; getParams() throws AuthFailureError {
                    Map&lt;String,String&gt; parameters = new HashMap&lt;String,String&gt;();
                    parameters.put(""email"",email);
                    parameters.put(""password"",pass);

                    return parameters;
                }
            };
            requestQueue.add(request);
        }catch (Exception o){Log.w(""TAG"",o.getMessage());}
    }//loginUser
</code></pre>

<hr>

<pre><code>@Test
public void testLoginCall() throws Exception {
    loginFragment = Mockito.mock(LoginFragment.class);
    doNothing().when(loginFragment).loginUser(""email"",""pass"");
    loginFragment.loginUser(""email"",""pass"");
    verify(loginFragment,times(1)).loginUser(""email"",""pass"");
}
</code></pre>
",https://stackoverflow.com/questions/53210228/unit-testing-login-method,"['java', 'android', 'testing']",2283,FALSE,3,0
Unit testing tls client,"<p>I have a function that makes an https request to a TLS server. I want to write unit tests to test the client function. I came across httptest.NewTLSServer that can be used to mock the server. But, how can I incorporate the certificates that the client uses instead of the default ones used in NewTLSServer?</p>

<p>Following is the client function that makes the request:</p>

<pre><code>func MakeDownloadRequest(url string) (*http.Response, error) {

    caCert, err := ioutil.ReadFile(""client/tlscerts/cert.pem"")
    if err != nil {
        return nil, err
    }
    caCertPool := x509.NewCertPool()
    caCertPool.AppendCertsFromPEM(caCert)

    cert, err := tls.LoadX509KeyPair(""client/tlscerts/cert.pem"",""client/tlscerts/key.pem"")
    if err != nil {
        return nil, err
    }

    client := &amp;http.Client{
        Transport: &amp;http.Transport{
            TLSClientConfig: &amp;tls.Config{
                RootCAs:      caCertPool,
                Certificates: []tls.Certificate{cert},
            },
        },
    }

    resp, err := client.Get(url)
    if err != nil {
        return nil, err
    }
    return resp, nil
}
</code></pre>

<p>Server stub:</p>

<pre><code>server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        io.WriteString(w, ""Hello"")
    }))
</code></pre>

<p>Using the server.URL to make requests gives me ""bad certificate"" error. How can I make both the client and server use the same certificate? </p>
",https://stackoverflow.com/questions/51490284/unit-testing-tls-client,"['unit-testing', 'go', 'https', 'client']",1880,TRUE,3,1
Vue.js unit testing ErrorBoundary,"<p>I've built simple ErrorBoundary component for my project in Vue.js and I'm struggling to write unit test for it. Component's code below:</p>

<pre><code>&lt;template&gt;
  &lt;div class=""overvue-error-boundary""&gt;
    &lt;slot v-if=""!error"" /&gt;
    &lt;div class=""error-message"" v-else&gt;Something went horribly wrong here.&lt;/div&gt;
  &lt;/div&gt;
&lt;/template&gt;
&lt;script&gt;
export default {
  data () {
    return {
      error: false
    }
  },
  errorCaptured (error, vm, info) {
    this.error = true;
  }
}
&lt;/script&gt;
</code></pre>

<p>I've created an ErrorThrowingComponent that throws an error on <strong>created()</strong> lifecycle hook so I can test ErrorBoundary:</p>

<pre><code>const ErrorThrowingComponent = Vue.component('error-throwing-component', {
  created() {
    throw new Error(`Generic error`);
  },
  render (h) {
    return h('div', 'lorem ipsum')
  }
});

describe('when component in slot throws an error', () =&gt; {
  it('renders div.error-message', () =&gt; {
  // this is when error is when 'Generic error' is thrown by ErrorThrowingComponent
  const wrapper = shallowMount(OvervueErrorBoundary, {
    slots: {
      default: ErrorThrowingComponent
    }});
    // below code is not executed
    expect(wrapper.contains(ErrorThrowingComponent)).to.be.false;
    expect(wrapper.contains('div.error-message')).to.be.true;
  });
});
</code></pre>

<p>The problem is that ErrorThrowingComponent throws an error when I'm trying to actually mount it (thus failing entire test). Is there any way I can prevent this from happening?</p>

<p>EDIT: What I'm trying to achieve is to actually <strong>mount</strong> the ErrorThrowing component in a default slot of <strong>ErrorBoundary</strong> component to assert if <strong>ErrorBoundary</strong> will render error message and not the slot. This is way I created the ErrorThrowingComponent in the first place. But I cannot assert ErrorBoundary's behavior, because I get an error when trying to create a wraper.</p>
",https://stackoverflow.com/questions/53462403/vue-js-unit-testing-errorboundary,"['unit-testing', 'vue.js', 'vuejs2', 'vue-test-utils']",541,TRUE,3,1
Unit testing FormGroup/FormArray,"<p>I have a function that accepts an AbstractControl variable and performs the following action:</p>

<pre><code>new(item: AbstractControl) {
  item['controls'].myArray.push(
    this.formBuilder.group({
      // my attributes here
    )}
  )
}
</code></pre>

<p>The object structure when I perform <code>console.log(item)</code> is the following (<em>I have only shown important info</em>):</p>

<pre><code>FormGroup {
  controls: {
    …,
    items: FormArray { 
      …,
      controls: Array(5) [FormGroup, FormGroup, …] 
  }
}
</code></pre>

<p>However I cannot seem to test it properly...</p>

<pre><code>it('Should add', () =&gt; {
    const fb = new FormBuilder();
    const myObject = fb.group([example]);

    component.new(myObject);

    const packagesLength = component.myFormGroup.get('data')['controls'][0]['controls']['items']['controls'].length;

    expect(packagesLength).toEqual(2);
  });
</code></pre>

<p>All I get from the console is </p>

<blockquote>
  <p><strong>Cannot read property 'push' of undefined</strong></p>
</blockquote>

<p>If I remove the array brackets from for my FormBuilder.group (ie <code>fb.group(example);</code>, I receive the message:</p>

<blockquote>
  <p><strong>customer.controls.packages.push is not a function</strong></p>
</blockquote>
",https://stackoverflow.com/questions/53853092/unit-testing-formgroup-formarray,"['angular', 'forms', 'unit-testing', 'form-control']",3578,FALSE,3,1
Unit Testing Android function,"<p>I want to unit test a function within my code, but when I try to input a ArrayList into it it gives me <code>array initializer not allowed here</code></p>

<p>here is my code:</p>

<pre><code>public class CreateActivityTest {

ArrayList&lt;String&gt; items;

public String Add(String item, ArrayList&lt;String&gt; items) {
    if (items.contains(item.toLowerCase().trim())) {
        return null;
    }
    else if (item == null || item.trim().equals("""")) {
        return null;
    } else {
        return item.toLowerCase().replaceAll(""\\s+"", """");
    }
}

@Test
public void addTest () throws Exception {
    items = {""strawberry"", ""raspberry""};
    String input = Add(""Strawberry "", items);
    String expected = null;
    assertEquals(input, expected);
}

}
</code></pre>
",https://stackoverflow.com/questions/49158665/unit-testing-android-function,"['java', 'android', 'unit-testing', 'assert']",55,TRUE,2,1
React unit testing Leaflet,"<p>I have problem with unit testing Map component.</p>
<p>My class component:</p>
<pre><code>componentDidMount() {
    const { zoom, data, center } = this.props;
    const { activeButton } = this.state;
    if (data[activeButton] != null) {
      this.map = map('map', {
        center: data[activeButton].points ? data[activeButton].points[0] : center,
        zoom,
        layers: [tileLayer(...SETTINGS.mapTileLayer)],
      });
      if (data[activeButton].points != null) {
        this.addPolyline(data[activeButton].points);
      }
    }
  }

  addPolyline = (points: Points) =&gt; {
    if (this.polyline != null) {
      this.map.removeLayer(this.polyline);
      this.map.removeLayer(this.marker.start);
      this.map.removeLayer(this.marker.stop);
    }

    if (points != null &amp;&amp; points[0] != null) {
      this.polyline = new Polyline(points, SETTINGS.polyline);

      this.marker.start = new Marker(points[0]);
      this.marker.stop = new Marker(points[points.length - 1]);

      this.polyline.addTo(this.map);
      this.marker.start.addTo(this.map);
      this.marker.stop.addTo(this.map);

      this.map.panTo(points[0]);
    }
  };
</code></pre>
<p>Unit test with Jest and Enzyme</p>
<pre><code>function getComponent(mockData) {
  return &lt;Map data={mockData} /&gt;;
}

const mockData = [
  { id: 0, name: '1', distance: '1', points: [[0, 0], [1, 1]] },
  { id: 1, name: '2', distance: '2', points: [[0, 0], [1, 1]] },
];

describe('LastActivity component', () =&gt; {  
  it('button click', () =&gt; {
    const wrapper = mount(getComponent(mockData), { attachTo: document.body });

...etc...
});
</code></pre>
<p>With this test I get</p>
<blockquote>
<p>TypeError: Cannot read property '_layerAdd' of null</p>
<p>this.polyline.<strong>addTo</strong>(this.map);</p>
</blockquote>
<p>When I comment out line this line</p>
<blockquote>
<p>this.polyline.addTo(this.map);</p>
</blockquote>
<p>Everything works fine and tests pass</p>
<p>package.json:</p>
<pre><code>&quot;enzyme-adapter-react-16&quot;: &quot;1.2.0&quot;,
&quot;enzyme&quot;: &quot;3.4.4&quot;,
&quot;react&quot;: &quot;16.4.2&quot;,
&quot;react-dom&quot;: &quot;16.4.2&quot;,
&quot;leaflet&quot;: &quot;1.3.4&quot;,
&quot;jest&quot;: &quot;23.5.0&quot;,
&quot;jest-cli&quot;: &quot;23.5.0&quot;,
</code></pre>
",https://stackoverflow.com/questions/52192422/react-unit-testing-leaflet,"['reactjs', 'unit-testing', 'leaflet', 'jestjs', 'enzyme']",3204,TRUE,2,1
Unit Testing API Call,"<p>I am using .NET Core with xUnit/Moq to create unit tests. I would like to create a unit test for the following API call:</p>

<pre><code>[HttpGet(""{zip}"")]
public IActionResult Get(int zip)
{
    //debugging here shows the repository has the object
    //but the result is always null
    Location result = repository[zip];
    if(result == null)
    {
        return NotFound();
    }
    else
    {
        return Ok(result);
    }
}
</code></pre>

<p>The unit test I have (that's failing) is:</p>

<pre><code>[Fact]
public void Api_Returns_Json_Object()
{
    //Arrange
    Mock&lt;IRepository&gt; mockRepo = new Mock&lt;IRepository&gt;();
    mockRepo.Setup(m =&gt; m.Locations).Returns(new Location[]
    {
        new Location
        {
            zip = 88012,
            type = ""STANDARD"",
            state = ""NM""
        }
    });

    //Arrange
    ApiController controller = new ApiController(mockRepo.Object);

    // Act
    var response = controller.Get(88012);

    // Assert
    Assert.True(response.Equals(HttpStatusCode.OK));
}
</code></pre>

<p>When I debug, the repository shows the correct <code>Location</code> object, but the result is always null, returning a <code>NotFound()</code> status code.</p>

<p>If I test the response with PostMan it works correctly.</p>

<p>Here are the relevant <code>IRepository</code> members:</p>

<pre><code>IEnumerable&lt;Location&gt; Locations { get; }
Location this[int zip] { get; }
</code></pre>
",https://stackoverflow.com/questions/50425584/unit-testing-api-call,"['c#', 'unit-testing', 'asp.net-core', 'moq', 'xunit']",198,TRUE,2,1
Apple pay unit testing,"<p>I'm working with apple pay on iOS 11</p>

<p>I have unit testing for our credit card tokenization. But I'm trying to tokenize an apple pay request.</p>

<p>Is it possible to unit test apple pay?</p>

<pre><code>import XCTest
import PassKit
@testable import os_ios

extension apiTests{
    func testBraintreeApplePay(){

        let expect = expectation(description: ""testBraintreeApplePay"")
        var responseReceived = false

        let number = ""4111111111111111""
        let month = ""12""
        let year = ""20""
        let securityCode = ""411""
        let postalCode = ""70433""

        let payment = PKPayment()
        // add the above info to this payment


        Braintree.paymentAuthorizationViewController(
            didAuthorizePayment: payment,
            completion: {(status: PKPaymentAuthorizationStatus,nonce:String?) in

            responseReceived = true

            // Check to see if we've received a nonce

            expect.fulfill()
        })


        waitForExpectations(timeout: expectationTimeoutDuration, handler: nil)
        XCTAssert(responseReceived)
    }
}
</code></pre>
",https://stackoverflow.com/questions/53811320/apple-pay-unit-testing,"['ios', 'swift', 'unit-testing', 'applepay']",759,FALSE,2,1
Unit Testing Bot Framework,"<p>I'm trying to figure out how to unit test a basic MS Bot Framework dialog and cannot get it to work the way everything on the internet says it should work.</p>

<p>Everything I find basically says follow this:
<a href=""https://github.com/Microsoft/BotBuilder/blob/master/CSharp/Tests/Microsoft.Bot.Sample.Tests/EchoBotTests.cs"" rel=""nofollow noreferrer"">https://github.com/Microsoft/BotBuilder/blob/master/CSharp/Tests/Microsoft.Bot.Sample.Tests/EchoBotTests.cs</a></p>

<p>Well, here's the problem with that:</p>

<p>await Conversation.SendAsync(scope, toBot);</p>

<p>That is defined as internal so it is not accessible outside of the bot.builder code. So it is totally useless unless you are programming tests for internal bot.builder stuff.</p>

<p>Is there a new way to get around this?</p>
",https://stackoverflow.com/questions/50358031/unit-testing-bot-framework,"['unit-testing', 'botframework']",479,FALSE,2,1
Unit Testing on Electron,"<p>I have a simple Electron app with no frameworks (React, Angular). I am trying to incorporate units tests with Mocha but I have problems understanding some of the concepts. I need to access the HTML that is being loaded since all my components ultimately depend on it (I have a small, custom, MVC structure).</p>

<p>I am reading examples like</p>

<pre><code>describe(""List"", function(){ 
  beforeEach(() =&gt; { 
    this.list = document.getElementById(""ul""); 
  }); 
  it(""updates from a given collection"", () =&gt; { 
    expect(this.list.querySelectorAll(""li"").length).toBe(2); 
  }); 
}
</code></pre>

<p>Where is the <code>document</code> taken from?</p>
",https://stackoverflow.com/questions/48418855/unit-testing-on-electron,"['javascript', 'node.js', 'unit-testing', 'mocha.js', 'electron']",1488,TRUE,2,1
Unit testing DevForce EntityManager.InvokeServerMethod,"<p>In a WPF application I have a view model that retrieves data from the server using a DevForce Entity Manager <code>InvokeServerMethod</code> call. I would like to unit test by view model.</p>

<p>Using Moq, I mocked the <code>IEntityManagerProvider</code> and setup the <code>InvokeServerMethod</code>.</p>

<pre><code>var mockManager = new Mock&lt;MyEntities&gt;(MockBehavior.Loose, false, null, 
    EntityServiceOption.UseDefaultService, ""Fake"");

var mockProvider = new Mock&lt;IEntityManagerProvider&lt;MyEntities&gt;&gt;(MockBehaviour.Loose);

mockProvider.Setup(m =&gt; m.Manager).Returns(mockManager.Object);

mockManager
    .Setup(m =&gt; m.InvokeServerMethod(It.IsAny&lt;ServerMethodDelegate&gt;())
    .Returns(new List&lt;int&gt;());
</code></pre>

<p>But when I run the test, I get</p>

<blockquote>
  <p>""Invalid setup on non-virtual member"".</p>
</blockquote>

<p>Next, I went into my <code>IEntityManagerProvider</code> interface and created this method</p>

<pre><code>object MockableServerMethod(ServerMethodDelegate method, params object[] 
    parameters); 
</code></pre>

<p>Then I implemented this new method</p>

<pre><code>public object MockableServerMethod(ServerMethodDelegate method, params 
    object[] parameters)
{
    return Manager.InvokeServerMethod(method, params);
}
</code></pre>

<p>This allows me to mock the server call, but requires me to change the production code, which I really shouldn't have to do.</p>

<p>What is the correct way to write a unit test when the method being tested calls <code>InvokeServerMethod()</code>?</p>
",https://stackoverflow.com/questions/49928385/unit-testing-devforce-entitymanager-invokeservermethod,"['c#', 'unit-testing', 'moq', 'devforce']",55,TRUE,1,1
redux unit testing Store.dispatch(),"<p>i have a basic react component like this.</p>

<pre><code>import React from 'react';
import store from 'src/home/store';
class PageLoading extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            message: this.props.message
        };
    }

    componentDidMount(){
        store.dispatch({ type: 'SET_NOTIFICATION_DIALOG', status: '200', message: this.state.message, model: 'LOADING' });
    }

    render(){
        return(&lt;div /&gt;);
    }
}


export default PageLoading;
</code></pre>

<p>how to unit this component ..?</p>

<p>i am using karma with ezyme.
i have written this below code but this is not working </p>

<pre><code>import configureMockStore from 'redux-mock-store';
import PageLoading from 'src/home/components/PageLoading';

const middlewares = [];
const mockStore = configureMockStore(middlewares);

Enzyme.configure({ adapter: new Adapter() });

describe(""Page Loading"",()=&gt;{
    it(""testing shoul dispatch action on calling componentdid mount"",()=&gt;{
        const initialState = {}
        const store = mockStore(initialState)
        const wrapper = mount(&lt;PageLoading message=""loading""/&gt;);
         const actions = store.getActions();
        const expectedPayload = {type: 'SET_NOTIFICATION_DIALOG', status: '200', message:""loading"", model: 'LOADING' };
         expect(actions).toEqual([expectedPayload])
    })
})
</code></pre>

<p>i think it is not getting the store. </p>
",https://stackoverflow.com/questions/50188335/redux-unit-testing-store-dispatch,"['reactjs', 'react-redux', 'karma-jasmine', 'enzyme', 'redux-mock-store']",9149,TRUE,1,2
Setup in Unit Testing,"<p>I'm trying to set up for unit testing using php yet i'm stucked at this note, where i can check if the tests succeeded or not, or is it in process...
so how can I make the ./vendor/bin/phpunit work?</p>

<p>Btw I followed a certain tutorial <a href=""https://www.youtube.com/watch?v=cQucsmbOkpE"" rel=""nofollow noreferrer"">https://www.youtube.com/watch?v=cQucsmbOkpE</a> @ 5.21.</p>

<p><a href=""https://i.stack.imgur.com/TawPf.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/TawPf.jpg"" alt=""""></a></p>
",https://stackoverflow.com/questions/51355452/setup-in-unit-testing,"['php', 'unit-testing', 'cmd']",33,FALSE,1,0
Unit testing Custom MessageHandler,"<p>I have a custom handler as below:</p>

<pre><code>public class LoggingHandler : DelegatingHandler
{

    public LoggingHandler()
    {         
    }

    protected override async Task&lt;HttpResponseMessage&gt; SendAsync(
        HttpRequestMessage request,
        CancellationToken cancellationToken)
    {

        var logger = new Logger(new something1(), param2, param3);

        logger.LogInformation(
            $""Incoming request: {request.Method} {request.RequestUri} );
         .
         .
         .
         .
        return httpResponse;
     }
}
</code></pre>

<p>I am familiar with Moq and I am able to moq the request and response message and assert successfully on that.</p>

<p>However as you can see I have a logger initialization done in the <code>SendAsync</code> method and log information regarding request, response and errors.</p>

<p>How can I test the logger in this workflow?.</p>
",https://stackoverflow.com/questions/50828056/unit-testing-custom-messagehandler,"['c#', 'unit-testing', 'asp.net-web-api', 'moq', 'message-handlers']",1255,TRUE,1,1
Unit Testing in Jasmine,"<p>I am testing a custom service made in angular JS where there is an error which is occurring. It is as follows:- 
Error during loading: Uncaught ReferenceError: angular is not defined in <a href=""http://localhost:63342/EmailTests/Unit%20Tests/jasmine-standalone-3.3.0/src/emailService.js"" rel=""nofollow noreferrer"">http://localhost:63342/EmailTests/Unit%20Tests/jasmine-standalone-3.3.0/src/emailService.js</a> line 3
Here is the code </p>

<pre><code>describe('Email Service', function(){
var emailService;
beforeEach(function () {
    module('bahmni.registration');
    inject(function () {
        emailService = $injector.get('emailService');
    });
});
it('should have a valid Email ID',function () {
    var parameters={
                    access_key : {parameter:'sdasdafassfa'},
                    smtp: {parameter:1}
                };

    var result=emailService.validateEmailService('https://apilayer.net/api/check',parameters,'someEmail');
    expect(result.toEqual(true));
   })
});
</code></pre>

<p>How can I solve this?</p>
",https://stackoverflow.com/questions/53257637/unit-testing-in-jasmine,"['angularjs', 'unit-testing', 'testing', 'jasmine']",37,FALSE,1,0
Unit Testing using ezyme,"<p>can anybody please explain me the Difference between the two packages <code>enzyme</code> and <code>jasmine-enzyme</code>...</p>

<pre><code>import Enzyme from 'enzyme';
import jasmineEnzyme from 'jasmine-enzyme';
</code></pre>

<p>I want to know how differently they work. I couldn't found any promising answer  in my research</p>

<p>Thanks in advance</p>
",https://stackoverflow.com/questions/49062504/unit-testing-using-ezyme,"['javascript', 'reactjs', 'jasmine', 'karma-jasmine', 'enzyme']",238,TRUE,1,1
Unit Testing Flink Functions,"<p>I am using Flink v.1.4.0.</p>

<p>I have implemented a module, as part of a package I am developing, whose role is to deduplicate a stream. The module is quite simple: </p>

<pre><code>public class RemoveDuplicateFilter&lt;T&gt; extends RichFlatMapFunction&lt;T, T&gt; {

static final ValueStateDescriptor&lt;Boolean&gt; SEEN_DESCRIPTOR = new ValueStateDescriptor&lt;&gt;(""seen"", Boolean.class);
private ValueState&lt;Boolean&gt; seen;

@Override
public void open(Configuration configuration) {
  RuntimeContext runtimeContext = this.getRuntimeContext();
  seen = runtimeContext.getState(SEEN_DESCRIPTOR);  
}

@Override
public void flatMap(T value, Collector&lt;T&gt; out) throws Exception {
  Boolean hasBeenSeen = seen.value();

  if(hasBeenSeen == null || !hasBeenSeen) {
    out.collect(value);
    seen.update(true);
  }  
}
</code></pre>

<p>The question is: how do I test this code without having to instantiate an actual <code>Flink</code> ValueState? i.e. using Mockito?</p>

<p>I have tried a number of things but, essentially, when it comes down to calling:</p>

<pre><code>RuntimeContext runtimeContext = Mockito.mock(RuntimeContext.class);
...
when(runtimeContext.getState(SEEN_DESCRIPTOR)).thenReturn(seen);
</code></pre>

<p>The call always fails. I have tried replacing the <code>SEEN_DESCRIPTOR</code> with <code>Matchers.any()</code> but still no luck.</p>

<p>Any suggestions?</p>
",https://stackoverflow.com/questions/48791161/unit-testing-flink-functions,"['java', 'unit-testing', 'mockito', 'apache-flink']",2171,TRUE,1,1
Unit testing Java Threads,"<p>I have a main program that creates a Thread to do something.</p>

<p>The worker thread calls a long running service and uses some sort
of callback function to notify about its response.</p>

<pre><code>public class TestingThreads {
    public static void main(String[] args) {
        Thread workerThread = new Thread(new WorkerThread());
        workerThread.run();
    }

    public static class WorkerThread implements Runnable {
        private ConfigService service;

        @Override
        public void run() {

            Response response = new Response() {
                @Override
                public void onResponse(String result) {
                    //Do something on the response
                }
            };

            Request request = new Request();
            service.callSomething(request, response);

            //Wait for response before exiting this run loop
        }

    }

    public static abstract class Response {
        public abstract void onResponse(String result);
    }

    public static class Request {
    }

    public static class ConfigService {
        public void callSomething(Request request, Response response) {
            // Call Long Running Process
        }
    }
}
</code></pre>

<p>I am having problem creating JUnit test case for this use case.
Do you have any idea how can I perform Unit Test for this class?</p>

<p>I wanted to actually mock up my response but I dont know how to do this.
In my Unit Test, I dont want to actually call my ConfigService class.</p>
",https://stackoverflow.com/questions/51297522/unit-testing-java-threads,"['java', 'unit-testing', 'junit']",1304,FALSE,1,2
Unit Testing a static method,"<p>I am trying to write a test case for the method decrypt here.</p>

<pre><code>    private static Codec codec;

    static {
        try {
            codec = new Codec(encryptionType, encryptionKey, false, true, false);
        } catch (CodecException e) {
            throw new RuntimeException(""Codec initialisation failed"", e);
        }
    }


    public static String decrypt(final String toDecrypt) throws CodecException {
        String decrypted = codec.decryptFromBase64(toDecrypt);
        if (decrypted.endsWith("":"")) {
            decrypted = decrypted.substring(0, decrypted.length() - 1);
        }
        return decrypted;
    }
</code></pre>

<p>Test Case: </p>

<pre><code>    @Mock
    private Codec codec;
    @Test
    public void test_decrypt_Success() throws CodecException {
        when(codec.decryptFromBase64(TestConstants.toDecrypt)).thenReturn(TestConstants.decrypted);
        assertEquals(DocumentUtils.decrypt(TestConstants.toDecrypt), TestConstants.decrypted);
    }
</code></pre>

<p>Since this is a static method, I can't inject an instance of the class in the test suite and mock its codec. The above code throws an error from the codec library at assert as expected.</p>

<p>What is your approach to testing static methods like this? Or should I not be writing tests for this at all?</p>
",https://stackoverflow.com/questions/53703857/unit-testing-a-static-method,"['java', 'unit-testing', 'testing', 'static', 'mockito']",57420,TRUE,9,3
Unit Testing HTTP Interceptors,"<p>I am using HTTP interceptor to show a loader every time any HTTP request is made from my page. Here is the implementation of the interceptor.</p>

<pre><code>@Injectable()
export class LoaderInterceptor implements HttpInterceptor {
private requests: HttpRequest&lt;any&gt;[] = [];
constructor(private loaderService: LoaderService) {}

removeRequest(req: HttpRequest&lt;any&gt;) {
    const i = this.requests.indexOf(req);
    if (i &gt;= 0) {
      this.requests.splice(i, 1);

    }
    this.loaderService.isLoading.next(this.requests.length &gt; 0);
  }

  intercept(req: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {
    this.requests.push(req);
    this.loaderService.isLoading.next(true);
    return Observable.create(observer =&gt; {
      const subscription = next.handle(req)
        .subscribe(
        event =&gt; {
          if (event instanceof HttpResponse) {
            this.removeRequest(req);
            observer.next(event);
          }
        },
        err =&gt; { this.removeRequest(req); observer.error(err); },
        () =&gt; { this.removeRequest(req); observer.complete(); });

      return () =&gt; {
        this.removeRequest(req);
        subscription.unsubscribe();
      };
    });
</code></pre>

<p>}
}</p>

<p>It works well and I would like to unit test it.</p>

<p>All I am doing is, whenever a HTTP request is made I am setting the <code>isLoading</code> flag to true.</p>

<p>I need to write an unit test for this. I went through lot of HTTP interceptor testing, but they are focused around testing the HTTP request by modifying it (like adding header, etc).</p>

<p>I want to know how can I test whether the flag is set whenever any HTTP request is made.</p>
",https://stackoverflow.com/questions/51249397/unit-testing-http-interceptors,"['angular', 'unit-testing', 'angular-http-interceptors']",309,FALSE,1,0
Angularjs component unit testing,"<p><strong>component.js</strong></p>

<pre><code>import template from './app-profile-image-uploader-dialog.html';

class ProfileImageUploaderDialogController {
  constructor() {
    'ngInject';
    this.name = 'appProfileImageUploaderDialog';
  }

  close() {
    this.dismiss({ $value: 'cancel' });
  }

  crop(croppedImage) {
    this.close({ $value: croppedImage });
  }
}

export const ProfileImageUploaderDialog = {
  selector: 'appProfileImageUploaderDialog',
  template: template,
  controller: ProfileImageUploaderDialogController,
  controllerAs: 'vm',
  bindings: {
    close: '&amp;',
    dismiss: '&amp;'
  }
};
</code></pre>

<p><strong>component.html</strong></p>

<pre><code>&lt;app-profile-image-uploader close-fn=""vm.close()"" crop-fn=""vm.crop(croppedImage)""&gt;&lt;/app-profile-image-uploader&gt;
</code></pre>

<p><strong>component.spec.js</strong></p>

<pre><code>import {ProfileImageUploaderDialog} from ""../../../../app/features/common/components/app-profile-image-uploader-dialog/app-profile-image-uploader-dialog.component"";
import 'angular-mocks';


describe('appProfileImageUploaderDialog', () =&gt; {

  const  bindings = {
    close: jasmine.createSpy('close'),
    dismiss: jasmine.createSpy('dismiss')
  };

  beforeEach(() =&gt; {
    angular.mock.module('innoApp');
  });

  let $componentController;

  describe('appProfileImageUploaderDialog controller tests', () =&gt; {

    let component;
    beforeEach(inject((_$componentController_) =&gt; {
      $componentController = _$componentController_;
    }));

    beforeEach(() =&gt; {
      component = $componentController(ProfileImageUploaderDialog.selector, {}, bindings);
    });

    it('should have set the parameters ', () =&gt; {
      expect(component.name).toBe('appProfileImageUploaderDialog');
    });

    it('should close the modal window if close button is pressed', (() =&gt; {
      component.close();
      expect(bindings.dismiss).toHaveBeenCalledWith({ $value: 'cancel'});
    }));

    it('should close the modal window if close button is pressed', (() =&gt; {
      let croppedImage = '';
      component.crop(croppedImage);
      expect(bindings.close).toHaveBeenCalledWith({ $value:  croppedImage});
    }));
  });
});
</code></pre>

<blockquote>
  <p>In this test one spec is failing. Can not figure out why.</p>
</blockquote>

<pre><code>it('should close the modal window if close button is pressed', (() =&gt; {
      component.close();
      expect(bindings.dismiss).toHaveBeenCalledWith({ $value: 'cancel'});
    }));
</code></pre>

<p>This is the error I am getting.</p>

<pre><code>Expected spy dismiss to have been called with [ Object({ $value: 'cancel' }) ] but it was never called.
</code></pre>
",https://stackoverflow.com/questions/50736471/angularjs-component-unit-testing,"['angularjs', 'unit-testing', 'jasmine']",231,TRUE,1,1
Unit Testing: (JUnit) Fixture,"<p>Can somebody help me understand what exactly the Fixture in JUnit and how it works. I googled for the same but failed to understand the same.
Thanks for your help in advance.</p>
",https://stackoverflow.com/questions/50678209/unit-testing-junit-fixture,['java'],1410,FALSE,1,0
Unit testing API responses,"<p>I came across a scenario in which I am not sure how test. </p>

<p>My application communicates back and forth with the Zoho CRM API, using the official PHP SDK. Here is the portion of my user class that I am having trouble with:</p>

<pre><code>class App_ZCRM_User {

    protected $record;


    public function __construct( ZCRMRecord $record ) {
        $this-&gt;record = $record;
    }


    public function create_default_tasks( array $tasks ) {
        $records = [];

        foreach( $tasks as $task ) {
            $record = ZCRMRecord::getInstance( 'Tasks', null ); // Create empty ZCRMRecord
            $record-&gt;setFieldValue( 'Subject', $task );
            $record-&gt;setFieldValue( 'User', $this-&gt;record );

            $records[] = $record;
        }

        $tasks  = ZCRMModule::getInstance( 'Tasks' );
        $insert = $tasks-&gt;createRecords( $records );

        // Returns array of EntityResponse objects
        return $insert-&gt;getEntityResponses();
    }
}
</code></pre>

<p>This class is instantiated with a Zoho CRM record using a contacts unique ID</p>

<pre><code>// ZCRMRecord object
$record = ZCRMRecord::getInstance( 'Contacts', 'xxxxxxxxxx' );

$user = new App_ZCRM_User( $record );
$user-&gt;create_default_tasks( array(
     'Choose vehicle make',
     'Choose vehicle model',
) );
</code></pre>

<p>The <code>create_default_tasks()</code> method communicates with the Zoho API. </p>

<p>The concern I am running into is that I do not want these records inserted into the CRM everytime the test is run. </p>

<p>I tried mocking the ZCRMModule for Tasks, but the class has a private constructor and uses a static method <code>getInstance()</code>. Using <code>$tasks = ZCRMModule::getInstance( 'Tasks' );</code> and calling <code>$tasks-&gt;createRecords()</code> on this class will result in a live API request.</p>

<p>My test is below, but it returns the message: </p>

<blockquote>
  <p>Static method ""getInstance"" cannot be invoked on mock object</p>
</blockquote>

<pre><code>public function test_create_default_tasks() {
        $tasks = array(
            'Task 1',
            'Task 2'
        );

        $records = [];

        foreach( $tasks as $task ) {
            $record = ZCRMRecord::getInstance( 'Tasks', null );
            $record-&gt;setFieldValue( 'Subject', $task );
            $record-&gt;setFieldValue( 'User', $this-&gt;record );

            $records[] = $record;
        }

        $user = new App_ZCRM_User( $this-&gt;record );
        $user-&gt;create_default_tasks( $tasks ); // Does API request


        /**
         * I want to mock the ZCRMModule tasks and simulate the createRecords() method
         */
        $tasks = $this-&gt;getMockBuilder( 'ZCRMModule' )
                      -&gt;disableOriginalConstructor() // Constructor is private
                      -&gt;getMock();

        $tasks::getInstance( 'Tasks' );
        $insert = $tasks-&gt;createRecords( $records ); // Method returns null

        $created = $insert-&gt;getEntityResponses();

        // Not sure how to assert the value here...
        //$this-&gt;assertEquals(  );
    }
</code></pre>

<p>I am lost trying to wrap my head arounds this... how can I test this method without using a live API request to Zoho ?</p>
",https://stackoverflow.com/questions/52744080/unit-testing-api-responses,"['php', 'api', 'unit-testing', 'phpunit']",251,FALSE,1,0
ionic3 SQLite unit testing,"<p>I'm using ionic3 and am trying to unit test (using Jasmine/karma) the following code.  Can anyone offer any guidance.</p>

<pre><code>createTable(databaseName: string): Promise&lt;any&gt; {

let sql = 'CREATE TABLE IF NOT EXISTS table)';

return new Promise((resolve, reject) =&gt; {
  this.sqlite.create({
    name: databaseName + '.db',
    location: 'default'
  }).then((db: SQLiteObject) =&gt; {
    db.executeSql(sql, [])
      .then(() =&gt; {
        console.info('Executed SQL');
      })
      .catch((e) =&gt; {
        console.error('createTable Error', e.message);
        reject(e);
      });
  });
})
}
</code></pre>

<p>Here's my work in progress attempt to test</p>

<pre><code>describe('createTable()', () =&gt; {

let db: SQLiteObject;

it('Should call function createTable', () =&gt; {
  spyOn(service.sqlite, 'create').and.returnValue(Promise.resolve(

  ));

  let databaseName = 'testDatabase';
  service.createEncounterTable(databaseName);
  expect(service.sqlite.create).toHaveBeenCalled();

});
});
</code></pre>

<p>I'm getting the following error return ERROR: 'Unhandled Promise rejection:', 'Cannot read property 'executeSql' of undefined', and dont seem to be able to gain access to executeSql.</p>

<p>As far as I can tell, from the lack of online resource on testing SQLite I have to assume that most people don't test this.  Thanks in advance to any guidance.</p>
",https://stackoverflow.com/questions/53152087/ionic3-sqlite-unit-testing,"['sqlite', 'ionic3']",102,FALSE,1,0
Jest/Enzyme unit testing,"<p>I have the following function which needs to be tested.</p>

<pre><code>    export function buildOptions(options) { 
        var oList=[];   
        for (var i=0; i &lt; options.length; i++) {
            oList.push (
              &lt;option key={""optId""+i} value={options[i][""id""]}&gt;
                  {options[i][""name""]}
              &lt;/option&gt;
            )
         }    
         return oList;
      }
</code></pre>

<p>I have a testcase as follows</p>

<pre class=""lang-js prettyprint-override""><code>it ('should return an array containing the populated options', () =&gt; {
    let teams = [{""name"":""A"",""id"":1},{""name"":""B"",""id"":2}]

     expect(JSON.stringify(Helper.buildOptions(teams))).toMatch(
         JSON.stringify([&lt;option value={1}&gt;A&lt;/option&gt;, &lt;option value={2}&gt;B&lt;/option&gt;])
      );

});
</code></pre>

<p>I am getting an error <strong>as the keys</strong> <strong>differ</strong> between the expected and received response. Could you please let me know how to get over the error/mock the keys?</p>

<p>Expected value to match:</p>

<pre><code>""[{\""type\"":\""option\"",\""key\"":null,\""ref\"":null,\""props\"":{\""value\"":1,\""children\"":\""A\""},\""_owner\"":null,\""_store\"":{}},{\""type\"":\""option\"",\""key\"":null,\""ref\"":null,\""props\"":{\""value\"":2,\""children\"":\""B\""},\""_owner\"":null,\""_store\"":{}}]""
</code></pre>

<p>Received:</p>

<pre><code>""[{\""type\"":\""option\"",\""key\"":\""optId1\"",\""ref\"":null,\""props\"":{\""value\"":1,\""children\"":\""A\""},\""_owner\"":null,\""_store\"":{}},{\""type\"":\""option\"",\""key\"":\""optId2\"",\""ref\"":null,\""props\"":{\""value\"":2,\""children\"":\""B\""},\""_owner\"":null,\""_store\"":{}}]""
</code></pre>
",https://stackoverflow.com/questions/51238670/jest-enzyme-unit-testing,"['reactjs', 'unit-testing', 'mocking', 'jestjs', 'enzyme']",144,TRUE,1,1
NServiceBus unit testing ConfigureHowToFindSaga,"<p>I would like to test <code>ConfigureHowToFindSaga</code> method in my NServiceBus Saga. Just had what seems like an avoidable issue where I'd forgotten to put the Unique attribute on Saga Data. </p>

<p>I could use Moq or similar but it awkward to verify the unique constraints on the Saga.</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/48682535/nservicebus-unit-testing-configurehowtofindsaga,"['unit-testing', 'nservicebus5']",128,FALSE,1,2
Failing Jest unit testing,"<p>I have a component in which I wrote test for. It worked great but now something is going wrong and I cannot figure out what.</p>

<p>This is the simple component which takes two numbers and returns their sum:</p>

<pre><code>import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/css/bootstrap-theme.css';
import React from 'react';
import ReactDOM from 'react-dom';
import { LogOutButton } from './LogOutButton.js';

class Home extends React.Component {
displayName = Home.name;

state = {
  result: 0,
  val1: 0,
  val2: 0,
};

handleChangeOne = event =&gt; {
  this.setState({ val1: event.target.value });
};

handleChangeTwo = event =&gt; {
  this.setState({ val2: event.target.value });
};

add = () =&gt; {
  this.setState({ 
    result: parseInt(this.state.val1) + parseInt(this.state.val2)
  });
};

onLogoutClick = () =&gt; {
  window.location.href = 'https://www.MICROSOFT.com';
}

render() {
  return (
    &lt;div&gt;
      &lt;h1&gt;Hello world! The result is: {this.state.result}&lt;/h1&gt;
      &lt;input type=""text"" onChange={this.handleChangeOne} /&gt;
      +
      &lt;input type=""text"" onChange={this.handleChangeTwo} /&gt;
      = &lt;br /&gt;
      &lt;button onClick={this.add}&gt;Add&lt;/button&gt;
      &lt;br/&gt;&lt;br/&gt; 
      &lt;LogOutButton onLogout={this.onLogoutClick} /&gt; 
    &lt;/div&gt;
  );
}
}

  export default Home;
</code></pre>

<p>And this is the test which used to work great:</p>

<pre><code>import React from 'react';
import { shallow } from 'enzyme'
import ReactDOM from 'react-dom';
import App from './App';
import { Home } from './components/Home';

describe('Home /&gt;', () =&gt; {
  it('Renders a sum', () =&gt; {
      const home = shallow(&lt;Home /&gt;);
      var first_value = home.state().val1;
      var second_value = home.state().val2;
      var result = first_value + second_value;
      expect(result).toBe(0);

      const inputs = home.find('input');
      inputs.at(0).simulate('change', {target: {value: 5} } );
      inputs.at(1).simulate('change', { target: { value: 8 } });
      home.find('button').simulate('click');
      home.update();
      expect(home.state().result).toBe(13);
  });
});
</code></pre>

<p>This is the error that I get:</p>

<pre><code> FAIL  src/Home.test.js
  ● Test suite failed to run

C:/Users/Itay/Documents/Experiments/WebApplication1/WebApplication1/ClientApp/src/components/Home.js: Unexpected token (8:12)

  Jest encountered an unexpected token
  This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.
  By default, if Jest sees a Babel config, it will use that to transform your files, ignoring ""node_modules"".
  Here's what you can do:
   • To have some of your ""node_modules"" files transformed, you can specify a custom ""transformIgnorePatterns"" in your config.
   • If you need a custom transformation specify a ""transform"" option in your config.
   • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the ""moduleNameMapper"" config option.
  You'll find more details and examples of these config options in the docs:
  https://jestjs.io/docs/en/configuration.html
  Details:
     6 |
     7 | class Home extends React.Component {
  &gt;  8 | displayName = Home.name;
       |             ^
     9 |
    10 |     state = {
    11 |       result: 0,
</code></pre>

<p>What's going on here? I have tried several things but nothing helped so far.</p>
",https://stackoverflow.com/questions/53103299/failing-jest-unit-testing,"['javascript', 'reactjs', 'unit-testing', 'jestjs']",409,TRUE,1,2
DocumentDB Repository Unit testing,"<p>I got reference from this <a href=""https://stackoverflow.com/questions/48349659/how-to-should-i-mock-documentclient-for-documentdb-unit-testing/48432085#48432085"">post</a> and it seems they have a working solution on unit testing for DocumentDB Repository class.</p>

<pre><code>[TestClass]
public class DocumentDBRepositoryShould {
    /// &lt;summary&gt;
    /// Fake IOrderedQueryable IDocumentQuery for mocking purposes
    /// &lt;/summary&gt;        
    public interface IFakeDocumentQuery&lt;T&gt; : IDocumentQuery&lt;T&gt;, IOrderedQueryable&lt;T&gt; {

    }

    [TestMethod]
    public async Task ExecuteQueryAsync() {
        //Arrange
        var description = ""BBB"";
        var expected = new List&lt;MyDocumentClass&gt; {
            new MyDocumentClass{ Description = description },
            new MyDocumentClass{ Description = ""ZZZ"" },
            new MyDocumentClass{ Description = ""AAA"" },
            new MyDocumentClass{ Description = ""CCC"" },

        };
        var response = new FeedResponse&lt;MyDocumentClass&gt;(expected);

        var mockDocumentQuery = new Mock&lt;IFakeDocumentQuery&lt;MyDocumentClass&gt;&gt;();
        mockDocumentQuery
            .SetupSequence(_ =&gt; _.HasMoreResults)
            .Returns(true)
            .Returns(false);

        mockDocumentQuery
            .Setup(_ =&gt; _.ExecuteNextAsync&lt;MyDocumentClass&gt;(It.IsAny&lt;CancellationToken&gt;()))
            .ReturnsAsync(response);

        var client = new Mock&lt;IDocumentClient&gt;();

        client
            .Setup(_ =&gt; _.CreateDocumentQuery&lt;MyDocumentClass&gt;(It.IsAny&lt;Uri&gt;(), It.IsAny&lt;FeedOptions&gt;()))
            .Returns(mockDocumentQuery.Object);

        var cosmosDatabase = string.Empty;

        var documentsRepository = new DocumentDBRepository&lt;MyDocumentClass&gt;(cosmosDatabase, client.Object);

        //Act
        var query = documentsRepository.GetQueryable(); //Simple query.

        var actual = await documentsRepository.ExecuteQueryAsync(query);

        //Assert
        actual.Should().BeEquivalentTo(expected);
    }
}
</code></pre>

<p>Basically the code is to compare the query result and the expected result. But I don't understand where do they get the query result? and where is the ""fake"" database that they query from? For example, for this line of code:</p>

<p><code>var actual = await documentsRepository.ExecuteQueryAsync(query);</code> </p>

<p>Which database is it calling? </p>
",https://stackoverflow.com/questions/49887276/documentdb-repository-unit-testing,"['c#', 'unit-testing', 'azure', 'repository', 'azure-cosmosdb']",1055,TRUE,1,1
Angular unit-testing idea,"<p>I'm a newbie in the world of web development and especially of unit testing since it wasn't my main subject during self-studying. Now I have to write unit-tests to my Angular code and I'm curious <em>what</em> I should test. Whether it should be only functions which do some calculations or should I also test some UI behaviour (e.g. check whether button really becomes disabled as expected or similar. Yep I know about e2e but it's more global I think).</p>

<p>So to make it clear what the question is about is ""what should I test in unit-tests"" (specifically Angular if it differs).</p>

<p>Because, I've seen the basic tests generated by CLI which are about 'should create' what seems ridiculous in terms of inability of app to compile if it's not working and Karma does need app to compile.</p>
",https://stackoverflow.com/questions/53526062/angular-unit-testing-idea,"['angular', 'unit-testing']",50,FALSE,1,0
Mocking BsModalRef for Unit Testing,"<p>I am using the BsModalRef for showing modals and sending data using the <code>content</code> property. So we have some like this :</p>

<pre><code>this.followerService.getFollowers(this.bsModalRef.content.channelId).subscribe((followers) =&gt; {
    this.followerList = followers;
    this.followerList.forEach((follower) =&gt; {
      follower.avatarLink = this.setUserImage(follower.userId);
      this.followerEmails.push(follower.email);
    });
  });
</code></pre>

<p>We are setting the channelId in content of bsModalRef (<code>this.bsModalRef.content.channelId</code>). It is working fine. Now i am writing a unit test for this. Problem is i am not able to mock it. I have tried overriding, spy etc but nothing seems to work. I am using the approach mentioned in this <a href=""https://codecraft.tv/courses/angular/unit-testing/mocks-and-spies/"" rel=""noreferrer"">link</a>. One alternative is to use TestBed but i am not much aware of its use. Can anyone please help me finding any approach by which this can be achieved ?</p>
",https://stackoverflow.com/questions/50249152/mocking-bsmodalref-for-unit-testing,"['unit-testing', 'typescript', 'karma-jasmine', 'angular5', 'ngx-bootstrap']",5703,TRUE,8,1
Unit Testing Lambda Expressions,"<p>I have a method that is shown as below and this in turn call multiple private methods, that I won't be posting here.</p>

<pre><code>@Bean
    public CommandLineRunner registerStartersAndReaders(final Vertx vertx, final SpringVerticleFactory springVerticleFactory,
                                                        final SpringUtil springUtil, final GslConfig gslConfig) {
        return args -&gt; {
            // Scan all the beans annotated with the @ElasticsearchBatchDataListener annotation.
            List&lt;Pair&lt;Object, Method&gt;&gt; listenerMethods = springUtil.getListenerMethods();

            // Deploy the starters per listener.
            deployVerticle(listenerMethods, jsonConfig -&gt; deployStarterVerticle(vertx, springVerticleFactory, jsonConfig), config);

            // Deploy the reader verticles.
            deployVerticle(listenerMethods, jsonConfig -&gt; deployReaderVerticle(vertx, springVerticleFactory, jsonConfig), config);
            setupTriggers(vertx, listenerMethods, config);
        };
    }
</code></pre>

<p>Then I have a test method for it :</p>

<pre><code>@Test
    public void registerStartersAndReadersTest() {
        when(springUtil.getListenerMethods()).thenReturn(value);
        CommandLineRunner runner = config.registerStartersAndReaders(vertx, springVerticleFactory, springUtil, config);
        assertNotNull(runner);
    }
</code></pre>

<p>Here, all the parameters passed into the method call are mocks. The problem is, when I run this test, it passes but it returns the value without getting into the private methods as it just returns 'args'. </p>

<p>Can someone please guide me, as to how I can make my test cover all the possible code. I am not supposed to change my code for the test.</p>
",https://stackoverflow.com/questions/50953057/unit-testing-lambda-expressions,"['unit-testing', 'lambda', 'java-8']",80,TRUE,0,1
JavaScript — Unit Testing Subtasks,"<p>They say:</p>

<blockquote>
  <p>""You should test the interface, not the implementation.""</p>
</blockquote>

<p>In other words, you should be concerned with the end result, not with how it is accomplished (<em>black box testing</em>).</p>

<p>It is also said that you should <strong>not</strong> test <em>private functions</em>, rather only the public interface that is exposed.  But my question is...</p>

<p>What do you do about a publicly exposed interface (e.g., function) that is dependent upon several subtasks that are private?  How should you go about testing that?  </p>

<p>Consider the below function <code>calculateDiscountedPrice</code>.  <strong>Let's pretend that the first function is publicly available (think export default) and the other 3 are private.</strong></p>

<pre><code>// PUBLIC TOP-LEVEL FUNCTION
export default function calculateDiscountedPrice(price, discount) {
    const dollarsOff = getDollarsOff(price, discount);
    return round(price - dollarsOff);
}

// PRIVATE SUBTASK
function getDollarsOff(price, discount) {
    return price * discount;
}

// PRIVATE SUBTASK
function round(number, precision = 2) {
    return isInt(number) 
    ? number
    : number.toFixed(precision);
}

// PRIVATE SUBTASK
function isInt(number) {
    return number % 1 === 0;
}
</code></pre>

<p>Example usage:</p>

<pre><code>console.log(calculateDiscountedPrice(100, 0.75)) // 25
</code></pre>

<p>As you can see, <code>calculateDiscountedPrice</code> is the public function we are exposing, so we should unit test that.  But what about the three other subtasks?  Why shouldn't we test those?  Would the tests that cover <code>calculateDiscountedPrice</code> cover the other three as well?</p>
",https://stackoverflow.com/questions/52838607/javascript-unit-testing-subtasks,"['javascript', 'unit-testing', 'abstraction', 'black-box']",104,TRUE,0,1
Redux reducers unit testing,"<p>I have a problem while doing the unit testing for reducers.</p>

<p>The problem is something like this: </p>

<p>I am trying the expected and result value should be equal and while creating the new state I was passing a action to create the new state 
The error is something like ...action type is not matching with the result .</p>

<p>Code sample:</p>

<pre><code>it('should transform in to new state',()=&gt; {
  const state={} 
  const action={ type: actionTypes.customerLookup, value :1 , customerRecords:{ reqStatus: false, message: 'No records found', searchResult:[{""records"":1}] } };
  const expected={ customerRecords:{ reqStatus: false, message: 'No records found', searchResult:[{""records"":2}] }};
  assert.deepEqual(createCusRecState(state,action),expected);
</code></pre>
",https://stackoverflow.com/questions/49274291/redux-reducers-unit-testing,"['reactjs', 'testing', 'redux']",47,FALSE,0,0
Chai Unit Testing Error,"<p>I am trying to write a unit test for the following file named <strong>a.js</strong></p>

<pre><code>var express = require('express');
var router = express.Router();

router.get('/getHCQ', function (req, res) {
  res.send(""OK"");
});

module.exports = router;
</code></pre>

<p>Unit test file : <strong>a.spec.js</strong></p>

<pre><code>var chai = require('chai');
var chaiHttp = require('chai-http');
var should = chai.should();

var a = require('./a');

describe('Unit Test', function () {
it('should run this', function (done) {
    chai.request(a)
        .get('/getHCQ')
        .end(function(err, res) {
            res.should.have.status(200);
            done();
        });
    });
});
</code></pre>

<p>I am running it using <strong>Mocha</strong> but getting the following error :</p>

<pre><code>Uncaught TypeError: Cannot read property 'apply' of undefined
  at Immediate.&lt;anonymous&gt; (node_modules/express/lib/router/index.js:635:14)
</code></pre>

<p>Can someone please help me to figure out what am I doing wrong here?</p>
",https://stackoverflow.com/questions/51979431/chai-unit-testing-error,"['node.js', 'unit-testing', 'mocha.js', 'chai']",107,FALSE,0,1
unit testing - Angular 6,"<p>I am looking to make two tests.</p>

<ol>
<li><p>Check that the h1 tag contains text i.e. is not empty.</p></li>
<li><p>Check the h1 tag contains title-icon /title-icon.</p></li>
</ol>

<p><strong>COMPONENT.SPEC.TS</strong>
<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;h1 class=""head""&gt;&lt;title-icon&gt;&lt;/title-icon&gt;Confirmation&lt;/h1&gt;</code></pre>
</div>
</div>
</p>

<p><strong>COMPONENT.HTML</strong>
<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 {async,ComponentFixture,TestBed} from '@angular/core/testing';
import {CUSTOM_ELEMENTS_SCHEMA} from '@angular/core';
import {ConfirmationDemoComponent} from './confirmation-demo.component';

describe('ConfirmationDemoComponent', () =&gt; {
    let component: ConfirmationDemoComponent;
    let fixture: ComponentFixture &lt; ConfirmationDemoComponent &gt; ;
    let compiled;

    beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
                declarations: [ConfirmationDemoComponent],
                schemas: [CUSTOM_ELEMENTS_SCHEMA]
            })
            .compileComponents();
    }));

    beforeEach(() =&gt; {
        fixture = TestBed.createComponent(ConfirmationDemoComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
        compiled = fixture.debugElement.nativeElement;
    });

    it('should create', () =&gt; {
        expect(component).toBeTruthy();
    });

    it('-&gt; should render text inside an h1 tag', async(() =&gt; {
        expect(compiled.querySelector('h1').textContent).not.toEqual(0);
    }));

    it('-&gt; should render a &lt;title-icon&gt;&lt;title-icon&gt; within an h1 tag', async(() =&gt; {

    }));
});</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/52887729/unit-testing-angular-6,"['angular', 'typescript', 'unit-testing', 'jasmine']",1134,TRUE,0,1
frameowrk7-vue unit testing,"<p>I have a phonegap application build with framework7-vue and I would like to write some tests.</p>

<p>I have looked online for an example and I could not find any.
I know how to use mocha and chai on functions and raw javascript, but with phonegap it's just not working.</p>

<p>Can someone please give an example or share a link on how unit testing can be done?</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/52993136/frameowrk7-vue-unit-testing,"['unit-testing', 'vue.js', 'phonegap-build', 'html-framework-7']",60,FALSE,0,0
.Net Core Unit Testing,"<p>I have a web api as below, which is being called from my angularjs UI.</p>

<pre><code>public class ValuesController : Controller
{
    private static string dynamoDbTable = string.Empty;
    private readonly IDynamoDbManager&lt;MyModel&gt; _dynamoDbManager;

    public ValuesController(IOptions&lt;Dictionary&lt;string, string&gt;&gt; appSettings, IDynamoDbManager&lt;MyModel&gt; dynamoDbManager)
    {
        var vals = appSettings.Value;
        dynamoDbTable = vals[""dynamoDbTable""];
        _dynamoDbManager = dynamoDbManager;
    }

[HttpGet(""api/data"")]
public async Task&lt;IActionResult&gt; GetAllData(string status, string role)
{
    List&lt;ScanCondition&gt; conditions = new List&lt;ScanCondition&gt;();
    conditions.Add(new ScanCondition(""status"", ScanOperator.Contains, status));
    conditions.Add(new ScanCondition(""role"", ScanOperator.Contains, role));

    List&lt;MyModel&gt; model = new List&lt;MyModel&gt;();
    model = await _dynamoDbManager.GetAsync(conditions);            

    return Ok(model);
}

[HttpPost(""api/save"")]
public async Task&lt;IActionResult&gt; SaveData([FromBody] List&lt;MyModel&gt; listData, string input, string name, string type)
{
    List&lt;MyModel&gt; model = new List&lt;MyModel&gt;();
    foreach (var data in listData)
    {
        //populating data here and saving
         await _dynamoDbManager.SaveAsync(data);
    }
    return Ok();
}
}
</code></pre>

<p>}</p>

<p>Now I want to write test cases for my API endpoints. I have not written any unit test case before so need input in that. I have read basic documentation of xunit here.</p>

<p>Here is my sample test method:</p>

<pre><code>public class ValuesControllerTests
{
    private Mock&lt;IDynamoDbManager&lt;MyModel&gt;&gt; _dbManager;
    private ValuesController _valueController;

    public ValuesControllerTests()
    {
        var mockRepository = new MockRepository(MockBehavior.Loose);
        _dbManager = mockRepository.Create&lt;IDynamoDbManager&lt;MyModel&gt;&gt;();
        var options = new OptionsWrapper&lt;Dictionary&lt;string, string&gt;&gt;(new Dictionary&lt;string, string&gt;()
        {
            {""dynamoDbTable"", nameof(MyModel) }
        });
        _valueController = new ValuesController(options, _dbManager.Object);
    }

[Fact]
public async Task GetAllData_Test()
{
    var searchResult = new List&lt;MyModel&gt;()
    {
        new MyModel(){ }
    };

     //Here I am trying to use MOQ but this is not working fine
    _dbManager
     .Setup(_ =&gt; _.GetAsync(It.IsAny&lt;List&lt;ScanCondition&gt;&gt;()))
     .ReturnsAsync(searchResult);

    var result = _valueController.GetAllData(""new"", ""admin"");
    Assert.IsType&lt;OkObjectResult&gt;(result.Result);            
} 
}
 }
</code></pre>

<p>Can I test my method without using moq, if so how can I do so? Because with moq I am not able to test.
Secondly above test case I am just checking if api method returns OK. What other test cases can I write for my get and save method.</p>

<p>I have also created a git project in case anyone wants to look at project: <a href=""https://github.com/kj1981/xunit"" rel=""nofollow noreferrer"">https://github.com/kj1981/xunit</a></p>

<p>Would appreciate if someone can help me in this.</p>

<p>--Added--</p>

<p>I also tried one test as below, but is this fine? May be my thinking is wrong, with the below test I thought it would fail but it does not.</p>

<pre><code>     [Fact]
    public async Task GetAllData_Test()
    {
        var searchResult = new List&lt;MyModel&gt;()
        {
            new MyModel(){ Id =""1"", Name = ""Adam"", Role = ""User"", Status =""old"" },
            new MyModel(){ Id =""2"", Name = ""Gary"", Role = ""Admin"", Status =""new"" }
        };

        _dbManager
         .Setup(_ =&gt; _.GetAsync(It.IsAny&lt;List&lt;ScanCondition&gt;&gt;()))
         .ReturnsAsync(searchResult);

        var okResult = _valueController.GetAllData(""fail"", ""none"").Result as OkObjectResult; ;
        var items = Assert.IsType&lt;List&lt;MyModel&gt;&gt;(okResult.Value);
        Assert.Equal(2, items.Count);
    }
</code></pre>

<p>Anyone with inputs ?</p>
",https://stackoverflow.com/questions/53024148/net-core-unit-testing,"['c#', 'unit-testing', 'moq', 'xunit.net']",166,FALSE,0,0
Angular2 Unit Testing Services,"<p>I am new to Unit Testing and was wondering how I would be able to approach unit testing a component that relies on one service which in turn relies on many others. Below is my initial setup. </p>

<pre><code>beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [TestComp],
      providers: [TestService]
    }).compileComponents();
  }));
</code></pre>

<p>But doing this, it is not able to find the other services that it relies on. Then I would provide the other services like so. But then it keep growing as those services use other services etc. </p>

<pre><code>beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
          declarations: [TestComp],
          providers: [TestService, TestServiceDependencyService, TestServiceDependecyService2]
        }).compileComponents();
      }));
</code></pre>

<p>One thing I did with another unit test that relied on a service was create a mock service like so. </p>

<pre><code> beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [TestComponent],
    }).overrideComponent(TestComponent, {
      set: {
        providers: [
          { provide: TestService, useClass: MockTestService},
        ]
      }
    })
      .compileComponents();
  }));
</code></pre>

<p>Now the mock service in here was easier because there wasn't much functionality and I  was able to ""mock"" the return values.</p>

<p>In this new component - it'd be much more difficult to mock the correct return values. What would I do in this case?</p>
",https://stackoverflow.com/questions/48209185/angular2-unit-testing-services,"['angular', 'unit-testing', 'jasmine']",58,FALSE,0,2
Unit Testing for pandas,"<p>I am trying to unit test a class that I have written in Python called NeuralNetworkModel(). It is a class that takes in a file and trains a ANN model and saves it as a pickle file. Currently I have a very basic unit test that the class is reading in a file as a data frame correctly. My code is below.</p>

<pre><code>import unittest
import pandas as pd
from pandas.util.testing import assert_frame_equal
from NN_model import NeuralNetworkModel

class NeuralNetworkModel(unittest.TestCase):

    def test(self):
        self.assertTrue(True)

    @classmethod
    def set_up(cls):
        """""" SetUp """"""
        test_input_dir = '/home/student/data_analytics/prediction_model/clean_files/'
        test_file_name = '25_1.csv'
        try:
            data = pd.read_csv(test_input_dir + test_file_name, sep = ',')
        except IOError:
            print('Cannot Open File')
        cls.fixture = data

    def test_dataFrame_constrcuted_as_expected(self):
        """""" Test that the dataframe read in equals what you expect""""""
        foo = pd.DataFrame()
        assert_frame_equal(self.fixture, foo)


if __name__ == '__main__':
    unittest.main()
</code></pre>

<p>Error I get when I run this file is </p>

<pre><code>ERROR: test_dataFrame_constrcuted_as_expected (__main__.NeuralNetworkModel)
Test that the dataframe read in equals what you expect
----------------------------------------------------------------------
Traceback (most recent call last):
  File ""test_NN_model.py"", line 25, in test_dataFrame_constrcuted_as_expected
    assert_frame_equal(self.fixture, foo)
AttributeError: 'NeuralNetworkModel' object has no attribute 'fixture'

----------------------------------------------------------------------
Ran 2 tests in 0.002s

FAILED (errors=1)
</code></pre>

<p>I am very new to unit testing and I struggle with it, but I can't work out why my test isn't passing?</p>
",https://stackoverflow.com/questions/51558108/unit-testing-for-pandas,"['python', 'pandas', 'unit-testing']",978,TRUE,0,1
Unit Testing Keyup AngularJS,"<p>I am having the hardest time trying to figure out how to write unit tests for this simple directive. Any help would be greatly appreciated.</p>

<p>Quick description:
left and right arrow keys will change the focus of the test component.</p>

<pre><code>import { Directive, HostListener, QueryList, ElementRef } from '@angular/core';

@Directive({
  selector: '[giTabMenuKeyboardControls]'
})

export class TabMenuKeyboardControlsDirective {
  constructor(private el: ElementRef) { }

  @HostListener('keyup', ['$event']) onkeyup(e: KeyboardEvent) {
    const tabs: QueryList&lt;any&gt; = this.el.nativeElement.querySelectorAll('[role=""tab""]');
    const currentFocused = document.activeElement;
    const index = Array.prototype.indexOf.call(tabs, currentFocused);

    // Left Arrow
    if (e.keyCode === 37) {
      currentFocused.previousElementSibling ? tabs[index - 1].focus() : tabs[tabs.length - 1].focus();
    }
    // Right Arrow
    if (e.keyCode === 39) {
      currentFocused.nextElementSibling ? tabs[index + 1].focus() : tabs[0].focus();
    }
  }
}
</code></pre>

<p>Here's what it looks like while i'm getting started. </p>

<pre><code>import { TestBed, ComponentFixture} from '@angular/core/testing';
import { Component, DebugElement, Input} from '@angular/core';
import { By } from '@angular/platform-browser';
import { TabMenuKeyboardControlsDirective } from './tab-menu-keyboard-controls.directive';

// When creating test for a directive we need to provide a dummy component
@Component({
  template: `&lt;div class=""tab-menu"" role=""tablist"" giTabMenuKeyboardControls&gt;
  &lt;button role=""tab""&gt;test 1&lt;/button&gt;
  &lt;button role=""tab""&gt;test 2&lt;/button&gt;
&lt;/div&gt;`
})

class TestTabMenuKeyboardControlsComponent {
}

describe('Directive: TabMenuKeyboardControlsDirective', () =&gt; {

  let component: TestTabMenuKeyboardControlsComponent;
  let fixture: ComponentFixture&lt;TestTabMenuKeyboardControlsComponent&gt;;
  let buttonElement: DebugElement;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ TabMenuKeyboardControlsDirective, TestTabMenuKeyboardControlsComponent ]
    });

    fixture = TestBed.createComponent(TestTabMenuKeyboardControlsComponent);
    component = fixture.componentInstance;
    buttonElement = fixture.debugElement.query(By.css('button'));
  });

  it('on key press', () =&gt; {
    buttonElement.triggerEventHandler('keyup', null);
    fixture.detectChanges();
  });

});
</code></pre>

<p>How do I check for the individual keys and focus?</p>

<p>Thanks again.</p>
",https://stackoverflow.com/questions/48754355/unit-testing-keyup-angularjs,"['angularjs', 'unit-testing', 'angularjs-directive', 'karma-jasmine']",105,FALSE,0,0
angular 6 unit testing,"<p>I am working on a project in which I am getting reports data from multiple 3rd party apis and showing it in tables with custom filters and other things. It's working fine but I am having an issue with testing. I have 1 json file consist of credentials and endpoint of each panel. As soon as app initiates I read that file.</p>



<pre class=""lang-ts prettyprint-override""><code>// factory that reads file
export function akrpFactory(akrp: AkrpService) {
    return () =&gt; akrp.load();
}
// akrp.load method returns this.http.get(""./assets/data.json"")
// inside ngModule
providers: [
    {
        provide: APP_INITIALIZER,
        useFactory: akrpFactory,
        deps: [AkrpService],
        multi: true
    }
]
// after this data is available throughout the application
</code></pre>

<p>In dashboard component ngAfterViewInit there is one http call </p>

<pre class=""lang-ts prettyprint-override""><code>ngAfterViewInit() {
    this.getPerformingFeeds(this.selectedPanel.key, '0-100');
}
// this.selectedPanel.key contains one of data records from json file
// here I am getting error ('TypeError: Cannot read property 'key' of undefined') during testing
</code></pre>

<p>in .spec.ts file there only one test case. I tried to assign component.selectedPanel but still same error</p>

<pre class=""lang-ts prettyprint-override""><code>it('should create', () =&gt; {
    expect(component).toBeTruthy();
});
</code></pre>

<p>Well I am new to angular 2+ versions, and testing also, not sure what to do. anything would be helpful, thank you.</p>
",https://stackoverflow.com/questions/53846675/angular-6-unit-testing,"['angular', 'jasmine', 'angular-test']",186,FALSE,0,0
NodeJS &amp; MongoDB Unit Testing,"<p>Afternoon all</p>

<p>I have been struggling to find a solid solution to the following.</p>

<p>How do I <strong>unit tests</strong> NodeJS code which makes use of MongoDB ?</p>

<p>I would like to write isolated unit tests, without actually spinning up any database for the purpose of testing.</p>

<p>Example code I would like to test:</p>

<p><strong>DatabaseService.js</strong></p>

<pre><code>var mongodb       = require('mongodb');

var exports = module.exports = (function () {

  var MongoClient   = mongodb.MongoClient;
  var db            = null;

  function getDB(){
    return db;
  }

  const connect = (
    options
  ) =&gt; {

    return new Promise((resolve, reject) =&gt; {

      var host      = options.host;
      var port      = options.port;
      var dbName    = options.dbName;

      var url = 'mongodb://' + host + ':' + port;

      // Use connect method to connect to the server
      MongoClient.connect(url, function(err, client) {

        if(error){
          return reject(false);
        }

        const db = client.db(dbName);

        return resolve(true);

      });

    });
  };

  return {
    connect: connect,
    getDB: getDB
  };

})();
</code></pre>

<p><strong>UserService.js</strong></p>

<pre><code>var DatabaseService   = require(""./DatabaseService"");

var exports = module.exports = (function () {

  const createUser = (
    options
  ) =&gt; {

    return new Promise((resolve, reject) =&gt; {

      var db = DatabaseService.getDB();

      var firstName = options.firstName;
      var lastName = options.lastName;

      db.collection('users').insertOne({
          firstName: firstName,
          lastName: lastName
        },
        function(error, result) {

          if (error){
            return reject(false);
          }

          return resolve(result);

      });

    });

  };

  return {
    createUser: createUser
  };

})();
</code></pre>
",https://stackoverflow.com/questions/49939223/nodejs-mongodb-unit-testing,"['javascript', 'node.js', 'mongodb']",2577,FALSE,8,1
Laravel Unit Testing Inconsistency,"<p>Hi I am following the laravel course from <a href=""https://laracasts.com/series/laravel-from-scratch-2017/episodes/22"" rel=""nofollow noreferrer"">laracast</a>, but faced some difficulty following the course.</p>

<p>In the app, there is a Post Model with a static function that returns grouped records: </p>

<p><strong>Post.php</strong></p>

<pre><code>public static function archives()
{

    return static::selectRaw('year(created_at) as year, monthname(created_at) month, count(*) published')
    -&gt;groupBy('year', 'month')
    -&gt;orderByRaw('min(created_at) desc')
    -&gt;get()
    -&gt;toArray();
}
</code></pre>

<p>On the other hand, a test case aims to test the Post::archives() function:</p>

<p><strong>ExampleTest.php</strong></p>

<pre><code>public function testBasicTest()
{

    // GIVEN I have two records in the database that are posts,
    // and each one is posted a month apart.
    $first = factory(Post::class)-&gt;create();

    $second = factory(Post::class)-&gt;create([
       'created_at' =&gt; \Carbon\Carbon::now()-&gt;subMonth()
    ]);
    // WHEN I fetch the archives
    $posts = \App\Post::archives();
    // dd($posts);
    // THEN the response should be in the proper format
    $this-&gt;assertEquals([
        [
            ""year"" =&gt; $first-&gt;created_at-&gt;format('Y'),
            ""month"" =&gt; $first-&gt;created_at-&gt;format('F'),
            ""published"" =&gt; 1
        ],
        [
            ""year"" =&gt; $first-&gt;created_at-&gt;format('Y'),
            ""month"" =&gt; $first-&gt;created_at-&gt;format('F'),
            ""published"" =&gt; 1
        ],
    ], $posts);
}
</code></pre>

<p>However, the assertion failed, because $posts is an array of object instead of an array of array, even though <code>Post::archives()</code> specifically converted the results with <code>toArray()</code>.</p>

<p>Dumping it on tinker:</p>

<pre><code>$posts = \App\Post::archives()
[
 [
   ""year"" =&gt; 2014,
   ""month"" =&gt; ""March"",
   ""published"" =&gt; 2,
 ],
 [
   ""year"" =&gt; 2014,
   ""month"" =&gt; ""February"",
   ""published"" =&gt; 1,
 ],
 [
   ""year"" =&gt; 2013,
   ""month"" =&gt; ""February"",
   ""published"" =&gt; 1,
 ],
]
</code></pre>

<p><strong>The error on phpunit</strong></p>

<pre><code>1) Tests\Unit\ExampleTest::testBasicTest
Failed asserting that two arrays are equal.
--- Expected
+++ Actual
@@ @@
 Array (
-    0 =&gt; Array (...)
-    1 =&gt; Array (...)
+    0 =&gt; App\Post Object (...)
+    1 =&gt; App\Post Object (...)
 )
</code></pre>

<p><strong>dd($posts) derives:-</strong> </p>

<pre><code>    ..array:2 [
  0 =&gt; App\Post {#863
    #guarded: []
    #connection: ""mysql""
    #table: null
    #primaryKey: ""id""
    #keyType: ""int""
    +incrementing: true
    #with: []
    #withCount: []
    #perPage: 15
    +exists: true
    +wasRecentlyCreated: false
    #attributes: array:3 [
      ""year"" =&gt; 2018
      ""month"" =&gt; ""April""
      ""published"" =&gt; 1
    ]
    #original: array:3 [
      ""year"" =&gt; 2018
      ""month"" =&gt; ""April""
      ""published"" =&gt; 1
    ]
    #changes: []
    #casts: []
    #dates: []
    #dateFormat: null
    #appends: []
    #dispatchesEvents: []
    #observables: []
    #relations: []
    #touches: []
    +timestamps: true
    #hidden: []
    #visible: []
    #fillable: []
  }
  1 =&gt; App\Post {#864
    #guarded: []
    #connection: ""mysql""
    #table: null
    #primaryKey: ""id""
    #keyType: ""int""
    +incrementing: true
    #with: []
    #withCount: []
    #perPage: 15
    +exists: true
    +wasRecentlyCreated: false
    #attributes: array:3 [
      ""year"" =&gt; 2018
      ""month"" =&gt; ""March""
      ""published"" =&gt; 1
    ]
    #original: array:3 [
      ""year"" =&gt; 2018
      ""month"" =&gt; ""March""
      ""published"" =&gt; 1
    ]
    #changes: []
    #casts: []
    #dates: []
    #dateFormat: null
    #appends: []
    #dispatchesEvents: []
    #observables: []
    #relations: []
    #touches: []
    +timestamps: true
    #hidden: []
    #visible: []
    #fillable: []
  }
]
</code></pre>

<p>Why is it behaving as such in the TestCase?</p>
",https://stackoverflow.com/questions/49674422/laravel-unit-testing-inconsistency,"['php', 'laravel', 'unit-testing', 'laravel-5']",411,FALSE,0,1
datetime in unit testing,"<p>I am trying to test below method and i get funny dates.</p>

<pre><code>public Pool AddPool(PoolDto poolDto, int createdByWho)
    {
        var pool = _mapper.Map&lt;Pool&gt;(poolDto);

        _mycontext.Pools.Add(pool);

        _mycontext.Save();
    }
</code></pre>

<p>this is my test</p>

<pre><code>public void test_the_add_pool_method()
{
    var date = DateTime.Parse(DateTime.Now.ToString(), new CultureInfo(""en-US"", true)).Date;

    var poolDto= new PoolDto
     {
         RequestorId = 1,
         ClientId = 1,
         Description = ""Pool request"",
         PoolStates = new List&lt;PoolState&gt;(),
         BookingDate = date,
         BookingFrom = date,
         BookingTo = date.AddDays(1)
     };

     service.AddPool(poolDto,1);

      Assert.That(Pools.Count(), Is.EqualTo(1));
      Assert.That(Pools.First().RequestorId, Is.EqualTo(1));
      Assert.That(Pools.First().ClientId, Is.EqualTo(1));
      Assert.That(Pools.First().Description, Is.EqualTo(""Pool request""));
      Assert.That(Pools.First().BookingDate, Is.EqualTo(DateTime.Now.Date));
      Assert.That(Pools.First().BookingFrom, Is.EqualTo(DateTime.Now.Date));
      Assert.That(Pools.First().BookingTo, Is.EqualTo(DateTime.Now.AddDays(1).Date));
}
</code></pre>

<p>when i run the test it fails with this error Message:   </p>

<pre><code>Expected: 2018-03-20 00:00:00
  But was:  0001-01-01 00:00:00
</code></pre>

<p>i did not capture <code>0001-01-01 00:00:00</code> and it is very confusing where is that date come from. 
How can i find out the where abouts of the <code>0001-01-01 00:00:00</code> ??</p>
",https://stackoverflow.com/questions/49380375/datetime-in-unit-testing,"['c#', 'unit-testing', 'nunit-3.0']",750,TRUE,-1,2
Unit Testing Ajax calls,"<p>I need some advice on unit testing. I am using mocha and sinon.</p>

<p>I have an httpService module that deals with all the ajax requests (written by me). The file being tested requires the httpService module.</p>

<p>I am unit testing a function that makes a call to a private function in the same file which in turn calls the httpService.get()</p>

<p>What is the best way to unit test this?</p>

<p>The options I have come up with:</p>

<p>1) I could use the sinon FakeXMLHttpRequest to fake the Ajax response. However because the ajax request is being made from the httpService module I am now testing the functionality of the httpService module. Is this not integration testing?</p>

<p>2) I could require the httpService module into my unit test file and stub the httpService.get() function. Is requiring a module into my unit test acceptable practice even if it is to just stub function?</p>

<p>Nothing else is exposed from the file being tested.</p>

<p>Any other options?</p>

<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/49005614/unit-testing-ajax-calls,"['javascript', 'unit-testing', 'mocha.js', 'sinon']",791,TRUE,0,1
Angular 6 - Unit Testing Mat-Select,"<p>1: The mat-select has 4 values, 1,2,3,4. </p>

<p>The code below works good for the select. So I'd like to share if it helps the readers.</p>

<pre><code>it('check the length of drop down', async () =&gt; {

    const trigger = fixture.debugElement.query(By.css('.mat-select-trigger')).nativeElement;
    trigger.click();
    fixture.detectChanges();
    await fixture.whenStable().then(() =&gt; {
        const inquiryOptions = fixture.debugElement.queryAll(By.css('.mat-option-text'));
        expect(inquiryOptions.length).toEqual(4);
    });
});
</code></pre>

<p>2: I need another test to verify the default value in the same
mat-select is 3 or not. When page loads the default value for the drop down is set to 3.</p>

<pre><code>it('should validate the drop down value if it is set by default', async () =&gt; {

    const trigger = fixture.debugElement.query(By.css('.mat-select-trigger')).nativeElement;
    trigger.click();
    fixture.detectChanges();
    await fixture.whenStable().then(() =&gt; {
        const inquiryOptions = fixture.debugElement.queryAll(By.css('.mat-option-text'));
        const value = trigger.options[0].value;
        expect(value).toContain(3);
    });
});
</code></pre>

<p>Any help is appreciated. </p>
",https://stackoverflow.com/questions/52505846/angular-6-unit-testing-mat-select,"['unit-testing', 'karma-jasmine', 'angular6']",25398,TRUE,15,5
Unit testing in VS2017,"<p>I want to test my code on some data set. This is the list of files that can be updated by some users in my company. I use unit testing run before build release and don't know is testing data set is updated now. I use Microsoft.VisualStudio.TestTools.UnitTesting. Now I write code like this:</p>

<pre><code>[TestMethod]
public void Test1()
{
     foreach (var src in testDataSetFiles)
     {
           Assert.IsNotNull(someMethodForTest(src), ""fail"");    
     }
}
</code></pre>

<p>When the assert is triggered unit testing is stopped for Test1. Its as it works, I know. But maybe there is a way to continue test runs after some <code>src</code> is failed? I don't want to write separate TestMethod for every <code>src</code>. Thanks!</p>
",https://stackoverflow.com/questions/51503485/unit-testing-in-vs2017,"['c#', '.net', 'visual-studio', 'unit-testing']",52,FALSE,0,1
c# Unit testing functions,"<p>I have a function like,</p>

<pre><code>public void UpdateData()
{
  Data data = GetDataFromDatabase()

  if(!data.IsDefault)
  {  
   // Do some change in data object
     SaveData(data);
  }
}
</code></pre>

<p>I want write unit test for SaveData(Data data) function,</p>

<pre><code>public bool SaveData(Data data)
{
  // Code for saving data in database
}
</code></pre>

<p>Above function contains code for saving data in database and there are no validations. Validations are done before calling this function.</p>

<p>Applications requirement is default data should not be updated. So while writing unit test should I consider this requirement?</p>

<p>If I write Unit Test like,</p>

<pre><code>public void SaveData_DefaultData()
{
   SaveData(defaultData);
   Assert.IsTrue(); // Some condition in assert to check whether the default data is updated.
}
</code></pre>

<p>By looking at the SaveData function I know that this test case is going to fail.
So my question is do I need to consider this test case?</p>
",https://stackoverflow.com/questions/51510452/c-unit-testing-functions,"['c#', 'unit-testing']",149,TRUE,0,3
Laravel Unit testing Routes,"<p>My test method has:</p>

<pre><code> $this-&gt;visitRoute('route.name')-&gt;see('something');
</code></pre>

<p>Response:</p>

<pre><code>There was 1 failure:

1) Tests\Unit\MyTest::testRoute
A request to [http://localhost/route.name] failed. Received status code [500].
Caused by
PDOException: SQLSTATE[HY000]: General error: 1 no such table 'tableThatExists'
</code></pre>

<p>BUT when I test:</p>

<pre><code>$this-&gt;visit('/')
</code></pre>

<p>As provided in Laravel documentation, it works, what is wrong??</p>

<p>And also if I just want to test responses without ""see"" condition how do I do it?</p>

<p>If anybody knows simple basic laravel unit tests it could help as well</p>
",https://stackoverflow.com/questions/50201933/laravel-unit-testing-routes,"['php', 'laravel', 'unit-testing', 'server', 'routes']",1086,TRUE,0,2
Unit testing: Input/output,"<p>I am trying to run a unit test for the following code: This code below only checks if the function is true.</p>

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

<pre><code>  import {encodeLengthHex, toHex } from './utils';

// testing new function 
describe('EncodeLengthHex', () =&gt; {   //mocking the method
test('Testing Function toHex ', () =&gt; { // declaring the method
const str = 128 // initial value
const actual = encodeLengthHex(str) // calculate the value
expect(actual).toMatchSnapshot(); // checking whether is true
})
});
</code></pre>

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

<pre><code> export function encodeLengthHex(n) {
if (n &lt;= 127) {
  return toHex(n);
}
const nHex = toHex(n);
const lengthOfLengthByte = 128 + nHex.length / 2;
  return toHex(lengthOfLengthByte) + nHex;
</code></pre>

<p>Function is passing. But how could I add a few inputs to test and compare when this function pass or fail. Thanks</p>
",https://stackoverflow.com/questions/53936832/unit-testing-input-output,"['javascript', 'unit-testing', 'jestjs']",1118,FALSE,0,0
xsl unit testing (java),"<p>The output of xsl is ""xml""
</p>

<p>Is there a way we can have a sample XML and compare it with the output of the XSLT ? 
could someone please give me an example on how to write unit test for the below. </p>

<pre><code>&lt;xsl:variable name=""variableA""&gt;
            &lt;xsl:choose&gt;
                &lt;xsl:when test=""normalize-space(field1)='1' and $variableB and
                                (translate(normalize-space($variableC), $ucletters,$lcletters)='x' or
                                translate(normalize-space($variableC), $ucletters,$lcletters)='y')""&gt;
                    &lt;xsl:text&gt;5&lt;/xsl:text&gt;
                &lt;/xsl:when&gt;
                &lt;xsl:otherwise&gt;
                    &lt;xsl:text&gt;6&lt;/xsl:text&gt;
                &lt;/xsl:otherwise&gt;
            &lt;/xsl:choose&gt;
        &lt;/xsl:variable&gt;
</code></pre>
",https://stackoverflow.com/questions/48653448/xsl-unit-testing-java,"['xml', 'unit-testing', 'xslt-1.0', 'xsl-stylesheet']",156,FALSE,0,1
Unit testing Drools File,"<p>I am trying to Unit test drools files. I pass in the directory for the file adn the drools file itself as a String</p>

<pre><code>public ObjectToRunDroolsOn runDrools(ObjectToRunDroolsOn objectToRunDroolsOn, String droolsFileDirectory, String droolsFile) {

    KieServices kieServices = KieServices.Factory.get();
    KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
    kieFileSystem.write(droolsFileDirectory, droolsFile);
    KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem);
    kieBuilder.buildAll();
    KieRepository kieRepository = kieServices.getRepository();
    ReleaseId krDefaultReleaseId = kieRepository.getDefaultReleaseId();
    KieContainer kieContainer = kieServices.newKieContainer(krDefaultReleaseId);
    KieSession kieSession = kieContainer.newKieSession();

    kieSession.insert(objectToRunDroolsOn);

    kieSession.fireAllRules();

    return objectToRunDroolsOn;
}
</code></pre>

<p>When I run the code through my application everything works fine but when I call the code from a unit test the everything seems as in it does not throw any errors but also does not make any changes when the rules are fired</p>

<p>Do you need to do something in the unit test (e.g. set a KIE session) ?</p>
",https://stackoverflow.com/questions/48681015/unit-testing-drools-file,"['java', 'unit-testing', 'drools', 'kie']",1561,FALSE,0,0
Button Unit Testing C#,"<p>I want to test if my button is doing what it was expected. But I even can't test this simple example:</p>

<pre><code>public int k = 0;

public void button3_Click(object sender, EventArgs e)
{
    k = 1;
}
</code></pre>

<p>Unit test:</p>

<pre><code>[TestMethod]
public void ButtonClick3_ret1()
{
    //arrange
    int x;
    int expected = 1;

    //act
    int actual;
    Form c = new Form();
    c.button3.PerformClick();
    actual = c.k;

    //assert
    Assert.AreEqual(expected,actual );
}
</code></pre>
",https://stackoverflow.com/questions/53787107/button-unit-testing-c,"['c#', 'visual-studio', 'unit-testing']",1469,TRUE,0,2
Vue Component Unit Testing,"<p>I have a counter component - pretty straight forward.</p>

<pre><code>&lt;div&gt; + &lt;/div&gt;
    &lt;input type=""text"" v-model=""countData"" /&gt;
&lt;div&gt; - &lt;/div&gt;
</code></pre>

<p>Detailed code is here - <a href=""https://github.com/Shreerang/Vue-Nuggets/blob/master/src/components/QuantitySelector/QuantitySelector.vue"" rel=""nofollow noreferrer"">https://github.com/Shreerang/Vue-Nuggets/blob/master/src/components/QuantitySelector/QuantitySelector.vue</a></p>

<p>I am trying to unit test this component.</p>

<pre><code>it('Renders a default quantity selector with the max count set to 6', () =&gt; {
    const wrapper = shallowMount(QuantitySelector);
    wrapper.find('input[type=""text""]').setValue('1');
    expect(wrapper.find('input[type=""text""]').element.value).toBe('1'); // notice here that the value is a String, whereas I expect it to be a Number

    wrapper.findAll('div').at(2).trigger('click');
    expect(wrapper.vm.countData).toBe('2'); // This fails as countData becomes ""11"" instead of doing a 1 + 1 = 2 and then becoming Number 2.

    expect(wrapper.find('input[type=""text""]').element.value).toBe(2); // You can notice the same thing as above.

    wrapper.find('input[type=""text""]').setValue(wrapper.vm.countData); // Do I have to do this? This does not seem right to me :frowning:
});
</code></pre>

<p>I am not able to get this unit test to work! Any help with this is appreciated!</p>
",https://stackoverflow.com/questions/53311015/vue-component-unit-testing,"['unit-testing', 'vue.js', 'vuejs2', 'jestjs', 'vue-component']",196,TRUE,0,1
ES6 unit testing without compilation,"<p>I'm not able to find any examples of Mocha or any other unit test framework running directly on ES6 code via Gulp. (No Babel, Webpack, etc.)</p>

<p>I've tracked down one example of Mocha (with some modification) running in a browser on ES6 code, but it was not automated. </p>

<p>Is anyone testing ES6 code directly yet?</p>

<p>(I understand this isn't the 'proper' format of an SO question, but I'm in the 'where do I start' phase here.)</p>
",https://stackoverflow.com/questions/49762892/es6-unit-testing-without-compilation,"['unit-testing', 'ecmascript-6', 'gulp', 'mocha.js']",1466,FALSE,8,2
Python Unit Testing Google Bigquery,"<p>I am having trouble in unit testing the following code block:</p>

<pre><code>from google.cloud import bigquery
from google.oauth2 import service_account

def run_query(query, gcp_ser_acc):
    credentials = 
    service_account.Credentials.from_service_account_info(gcp_ser_acc)
    client = bigquery.Client(gcp_ser_acc['project_id'], credentials)
    query_job = client.query(query)
    results = query_job.result()
    return results
</code></pre>

<p>I am new to mocking and I have tried the following test:</p>

<pre><code>def test_run_a_query_with_real_key(self):
    gcp_ser_acc = {
                'project_id': 'my_project_id',
                'private_key': 'my_private_key',
                'token_uri': 'my_token_uri',
                'client_email': 'my_client_email'
                }
    with mock.patch('service_account.Credentials', call_args=gcp_ser_acc, return_value={}):
        with mock.patch('bigquery.Client', call_args=(gcp_ser_acc['project_id'], {}), return_value={}):
            run_query('SELECT 1+1 as col', gcp_ser_acc)
            assert service_account.Credentials.called
            assert bigquery.Client.called
</code></pre>

<p>Can anybody mock the google stuff and write a unit test please?</p>
",https://stackoverflow.com/questions/53700181/python-unit-testing-google-bigquery,"['python', 'unit-testing', 'google-bigquery']",7901,TRUE,7,2
Rx Unit testing takeWhile,"<p>I have the following method that I have not clue how can I make its unit testing:</p>

<pre><code>private Completable checkMachineStatus(){
        return deviceDriver.getNotification(new OperationKey(""HMINotification""),
                HMI_DESCRIPTION, REQUIRED_HMI_BYTE_NUMBER)
                .takeWhile(data -&gt; {
                    MachineStatus status = MachineStatus.getMachineState(data.array()[MACHINE_STATUS_CHECK_POSITION]);
                    return status != MachineStatus.READY;
                }).ignoreElements();
    }
</code></pre>

<p>getNotification method is an Observable </p>

<p>What I am trying to do is this:</p>

<pre><code>    @Test
    public void testPowerBrewSuccess() {
        when(deviceDriver.getNotification(any(OperationKey.class), any(CharacteristicDescription.class), any(Integer.class)))
                .thenReturn(byteBufferObservable);
        when(byteBufferObservable.takeWhile(any())).thenReturn(predicateObservable);
        when(predicateObservable.ignoreElements()).thenReturn(Completable.complete());

        brew.brew(BrewParameters.POWER).test();
        verify(deviceDriver).getNotification(any(OperationKey.class), any(CharacteristicDescription.class), any(Integer.class));
    }
</code></pre>

<p>But is failing while doing the takeWhile operation. </p>
",https://stackoverflow.com/questions/48647879/rx-unit-testing-takewhile,"['java', 'android', 'unit-testing', 'rx-java']",301,FALSE,0,0
ASP.NET MVC unit testing,"<p>I have created a program in Visual Studio 2017, and I just noticed now that I forgot to add unit testing when creating it, and I am too far gone to start over.
How can I solve this problem?</p>
",https://stackoverflow.com/questions/52387220/asp-net-mvc-unit-testing,['c#'],40,TRUE,-2,1
"Angular 4, unit testing","<p>I have one component which consists of one method which internally calls service and I need to do unit testing for the same.</p>

<p><strong>Component.ts:</strong></p>

<pre><code>constructor(
    private formUtils: MeasureFormService,
}

getList() {
    this.formUtils.getList()
        .subscribe((data) =&gt; {
            this.memberDetails = data.MemberDetails;
            this.chaserDetails = data.RelatedChaserDetails;
        }, error =&gt; {
        });
}
</code></pre>

<p><strong>MeasureFormService.ts:</strong></p>

<pre><code>getList() {
    return this._httpWrapperService.Get('../../../../../assets/json/overread-accept.json')
    .map((data: any) =&gt; {
        return data;
    });
}
</code></pre>

<p>I need to unit test the component method which calls service. </p>
",https://stackoverflow.com/questions/50364389/angular-4-unit-testing,"['angular', 'unit-testing', 'jasmine']",172,FALSE,0,1
Context API HOC Unit testing,"<p>I have a HOC component which wraps React's context API  as follows </p>

<pre><code>import React from 'react';
import { AppContext } from './Context';

export function withAppContext(Component) {
    return function WrapperComponent(props) {
        return (
            &lt;AppContext.Consumer&gt;
                {state =&gt; &lt;Component {...props} context={state} /&gt;}
            &lt;/AppContext.Consumer&gt;
        );
    };
}
</code></pre>

<p>and another component which uses this HOC as such</p>

<pre><code>class Hello extends Component {
    render() {
        return (
            &lt;Fragment&gt;
                &lt;p&gt;{this.props.context.state.name}&lt;/p&gt;
                &lt;p&gt;{this.props.context.state.age}&lt;/p&gt;
                &lt;p&gt;{this.props.user}&lt;/p&gt;
            &lt;/Fragment&gt;
        )
    }
}

export default withAppContext(Hello);
</code></pre>

<p>I am planning to write a unit test that is going to test the <code>Hello</code> component. In order to achieve this , I have the following unit test </p>

<pre><code>const getAppContext = (context = {
        state : {
            ""name"" : ""Jane Doe"",
            ""age"" : 28
        }
    }) =&gt; {

  // Will then mock the AppContext module being used in our Hello component
  jest.doMock('../../../context/Context', () =&gt; {
    return {
      AppContext: {
        Consumer: (props) =&gt; props.children(context)
      }
    }
  });

  // We will need to re-require after calling jest.doMock.
  // return the updated Hello module that now includes the mocked context
  return require('./Hello').Hello;
};

describe('Hello', () =&gt; {
    test('Verify state from Context API', ()=&gt; {
        const Hello = getAppContext();
        const wrapper = mount(&lt;Hello /&gt;);

    })

})
</code></pre>

<p>But it's failing at this line 
<code>const wrapper = mount(&lt;Hello /&gt;);</code>
with the following message </p>

<pre><code>Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your componentfrom the file it's defined in, or you might have mixed up default and named imports.

Check the render method of `WrapperComponent`.

  46 |      test('Verify state from Context API', ()=&gt; {
  47 |              const Hello = getAppContext();
&gt; 48 |              const wrapper = mount(&lt;Hello /&gt;);         |                              ^
  49 |              expect(wrapper.find('li').hostNodes().length).toBe(2);
  50 |              expect(wrapper.html()).toBe(""&lt;ul&gt;&lt;li&gt;Name : Jane Doe&lt;/li&gt;&lt;li&gt;Age : 28&lt;/li&gt;&lt;/ul&gt;"")
  51 |      })
</code></pre>

<p>Can you please let me know what I am doing wrong here? </p>

<p>Thanks</p>
",https://stackoverflow.com/questions/53026752/context-api-hoc-unit-testing,"['reactjs', 'jestjs', 'enzyme', 'high-order-component']",801,TRUE,5,1
Mocking SparkSession for unit testing,"<p>I have a method in my spark application that loads the data from a MySQL database. the method looks something like this.</p>

<pre><code>trait DataManager {

val session: SparkSession

def loadFromDatabase(input: Input): DataFrame = {
            session.read.jdbc(input.jdbcUrl, s""(${input.selectQuery}) T0"",
              input.columnName, 0L, input.maxId, input.parallelism, input.connectionProperties)
    }
}
</code></pre>

<p>The method does nothing else other than executing <code>jdbc</code> method and loads data from the database. How can I test this method? The standard approach is to create a mock of the object <code>session</code> which is an instance of <code>SparkSession</code>. But since <code>SparkSession</code> has a private constructor I was not able to mock it using ScalaMock. </p>

<p>The main ask here is that my function is a pure side-effecting function (the side-effect being pull data from relational database) and how can i unit test this function given that I have issues mocking <code>SparkSession</code>.</p>

<p>So is there any way I can mock <code>SparkSession</code> or any other better way than mocking to test this method? </p>
",https://stackoverflow.com/questions/49483987/mocking-sparksession-for-unit-testing,"['scala', 'unit-testing', 'apache-spark', 'mocking', 'scalamock']",11777,TRUE,5,2
Ionic unit testing: webpack version,"<p>I've been trying to set up a testing example according to the common guidelines: <a href=""https://leifwells.github.io/2017/08/27/testing-in-ionic-configure-existing-projects-for-testing/"" rel=""noreferrer"">Testing in Ionic</a>, <a href=""https://github.com/ionic-team/ionic-unit-testing-example"" rel=""noreferrer"">Ionic GitHub Example</a></p>

<p>My project's <code>package.json</code>:</p>

<pre><code>{
  ""name"": ""starter-with-testing"",
  ""version"": ""0.0.1"",
  ""author"": ""Ionic Framework"",
  ""homepage"": ""http://ionicframework.com/"",
  ""private"": true,
  ""scripts"": {
    ""clean"": ""ionic-app-scripts clean"",
    ""build"": ""ionic-app-scripts build"",
    ""lint"": ""ionic-app-scripts lint"",
    ""ionic:build"": ""ionic-app-scripts build"",
    ""ionic:serve"": ""ionic-app-scripts serve"",
    ""test"": ""karma start ./test-config/karma.conf.js""
  },
  ""dependencies"": {
    ""@angular/animations"": ""5.2.11"",
    ""@angular/common"": ""5.2.11"",
    ""@angular/compiler"": ""5.2.11"",
    ""@angular/compiler-cli"": ""5.2.11"",
    ""@angular/core"": ""5.2.11"",
    ""@angular/forms"": ""5.2.11"",
    ""@angular/http"": ""5.2.11"",
    ""@angular/platform-browser"": ""5.2.11"",
    ""@angular/platform-browser-dynamic"": ""5.2.11"",
    ""@ionic-native/core"": ""4.7.0"",
    ""@ionic-native/splash-screen"": ""4.7.0"",
    ""@ionic-native/status-bar"": ""4.7.0"",
    ""@ionic/storage"": ""2.1.3"",
    ""ionic-angular"": ""3.9.2"",
    ""ionicons"": ""3.0.0"",
    ""rxjs"": ""5.5.11"",
    ""sw-toolbox"": ""3.6.0"",
    ""zone.js"": ""0.8.26""
  },
  ""devDependencies"": {
    ""@ionic/app-scripts"": ""^3.1.10"",
    ""@types/jasmine"": ""^2.8.8"",
    ""@types/node"": ""^10.3.4"",
    ""angular2-template-loader"": ""^0.6.2"",
    ""html-loader"": ""^0.5.5"",
    ""istanbul-instrumenter-loader"": ""^3.0.1"",
    ""jasmine"": ""^3.1.0"",
    ""jasmine-spec-reporter"": ""^4.2.1"",
    ""karma"": ""^2.0.3"",
    ""karma-chrome-launcher"": ""^2.2.0"",
    ""karma-coverage-istanbul-reporter"": ""^2.0.1"",
    ""karma-jasmine"": ""^1.1.2"",
    ""karma-jasmine-html-reporter"": ""^1.1.0"",
    ""karma-sourcemap-loader"": ""^0.3.7"",
    ""karma-webpack"": ""^3.0.0"",
    ""null-loader"": ""^0.1.1"",
    ""protractor"": ""^5.3.2"",
    ""ts-loader"": ""^4.4.1"",
    ""ts-node"": ""^6.1.2"",
    ""typescript"": ""~2.6.2""
  },
  ""description"": ""An Ionic project""
}
</code></pre>

<p>Attempt at <code>$ npm test</code> results in an error:</p>

<pre><code>Chrome 67.0.3396 (Linux 0.0.0) ERROR
{
""message"": ""An error was thrown in afterAll\nUncaught Error: Module build failed: Error: You may be using an old version of webpack; please check you're using at least version 4\n    at successfulTypeScriptInstance (/home/alexey/spaces/cordova/starter-with-testing/node_modules/ts-loader/dist/instances.js:168:15)\n    at Object.getTypeScriptInstance (/home/alexey/spaces/cordova/starter-with-testing/node_modules/ts-loader/dist/instances.js:51:12)\n    at Object.loader (/home/alexey/spaces/cordova/starter-with-testing/node_modules/ts-loader/dist/index.js:16:41)""
</code></pre>

<p>That is, webpack 4.x required. Indeed,</p>

<pre><code>$ npm list webpack
starter-with-testing@0.0.1 /home/alexey/spaces/cordova/starter-with- 
testing
└─┬ @ionic/app-scripts@3.1.10
  └── webpack@3.8.1
</code></pre>

<p>What am I supposed to do?</p>

<p>UPD:</p>

<p>I've got <code>It looks like your post is mostly code; please add some more details.</code> fatal error. Your question couldn't be submitted.</p>

<p>I'm really at a loss about more details. There is a dependency hell; please, help. I'll humbly submit whatever additional details you ask.</p>
",https://stackoverflow.com/questions/50973494/ionic-unit-testing-webpack-version,"['unit-testing', 'ionic-framework', 'karma-jasmine']",1691,TRUE,5,2
Unit Testing ASP.NET Core HttpResponse.OnStarting(),"<p>I have an ASP.NET Core middleware which is responsible for adding headers to a response. In following best practices, I am executing the header changes in the context of <code>HttpResponse.OnStarting(Func&lt;Task&gt;)</code>, which ensures callback execution immediately before the response is flushed to the client.</p>

<pre><code>public class ResponseHeadersMiddleware
{
    private readonly RequestDelegate _next;

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

    public async Task Invoke(HttpContext context)
    {
        context.Response.OnStarting(() =&gt;
        {
            context.Response.Headers.Add(""X-Some-Header"", ""Foobar"");

            return Task.CompletedTask;
        });

        // Pass the request through the pipeline 
        await _next(context);
    }
}
</code></pre>

<p>This works as-intended, but I am not sure how best to write a unit test for this middleware which actually fires <code>HttpResponse.OnStarting()</code>. The only thing I could come up with was using a <code>Microsoft.AspNetCore.TestHost</code> to build a <code>TestServer</code> which integrates the middleware and executes the full request pipeline. While functional, this is more an integration test, than a true unit test.</p>

<pre><code>[Fact]
public async Task when_adding_response_headers()
{
    // ARRANGE
    var subject = new TestServer(new WebHostBuilder()
        .UseStartup&lt;TestStartup&lt;ResponseHeadersMiddleware&gt;&gt;());

    // ACT
    var response = await subject.CreateClient()
        .SendAsync(new HttpRequestMessage(HttpMethod.Get, ""/"")); // middleware fires for all requests

    // ASSERT
    Assert.True(response.Headers.TryGetValues(""X-Some-Header"", out var someHeader));
    Assert.Equals(""Foobar"", someHeader.FirstOrDefault()
}

private class TestStartup&lt;TMiddleware&gt; where TMiddleware : class
{
    public void ConfigureServices(IServiceCollection services)
    {
        RequestDelegate requestDelegate = context =&gt; Task.FromResult(0);

        services.AddSingleton(requestDelegate);
        services.AddSingleton&lt;TMiddleware&gt;();
    }

    public void Configure(IApplicationBuilder app)
    {
        dynamic middleware = app.ApplicationServices.GetService(typeof(TMiddleware));

        app.Use(async (ctx, next) =&gt;
        {
            await middleware.Invoke(ctx);
            await next();
        });
    }
}
</code></pre>

<p>Is there a way to trigger <code>HttpResponse.OnStarting()</code> on the HttpContext passed to my middleware, without an end-to-end integration test?</p>
",https://stackoverflow.com/questions/49740194/unit-testing-asp-net-core-httpresponse-onstarting,"['c#', 'unit-testing', 'asp.net-core', 'httpresponse']",4913,TRUE,5,3
Unit testing NestJS controller with request,"<p>My Controller function definition looks like that:
<code>async login(@Req() request, @Body() loginDto: LoginDto): Promise&lt;any&gt; {</code></p>

<p>How I could prepare/mockup Request to provide first argument of function from Jest test? 
Inside funciton I am setting headers using <code>request.res.set</code>. Should I somehow pass real Request object to function and then check if header is set or rather mockup whole Request object and check if set function was called?</p>
",https://stackoverflow.com/questions/51422239/unit-testing-nestjs-controller-with-request,"['unit-testing', 'express', 'nestjs']",14275,TRUE,12,2
Unit Testing On Flutter Firebase functions,"<p>Good day, I am trying to perform some unit testing on the below function that creates a document in Cloud Firestore. I have used a function in my app and it creates a document, but I want to write a test.dart file that performs unit testing for the below function and prints some output even on the console for verifications.</p>

<p>I think I am not writing my Test.dart in the proper way. I get an error.</p>

<h1>Function in file createdatabase.dart</h1>

<pre><code>Future&lt;dynamic&gt; createDoc(dataMap,collection) async {
  final TransactionHandler createTransaction = (Transaction tx) async {
    final DocumentSnapshot ds = await tx.get(db.collection(collection).document());
    final Map&lt;String, dynamic&gt; result = {};
    result.addAll(dataMap);
    result['id'] = ds.documentID;
    await tx.set(ds.reference, result);

    return result;
  };
</code></pre>

<h1>Test.dart</h1>

<pre><code>import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:test/test.dart';
import '../lib/service/createfirebase.dart';

void main() {
  CreateFirebase cf = new CreateFirebase();   
   //test    
    test('Creating doc on firestore ', () async{ 
      Object dataObj ={'name':'Dev','title':'Dev'};
      var create = await cf.createDoc(dataObj, 'crude');
      expect(true,create);
      print('The doc details are');
      print(dataObj);
    });

}
</code></pre>

<p>The error after running this test is 
MissingPluginException(No implementation found for method Firestore#runTransaction on channel plugins.flutter.io/cloud_firestore)</p>

<p>But I do not understand why since I have all the dependencies and if I call that function in another class the doc gets created. But calling inside this test gives the above error. I guess I am not doing it in the right way.</p>

<p>Any contribution or any reference I can look at that can help on testing such functions?</p>
",https://stackoverflow.com/questions/53225813/unit-testing-on-flutter-firebase-functions,"['dart', 'google-cloud-firestore', 'flutter-test']",2301,TRUE,12,2
Web Component / HtmlElement : unit testing,"<p>I'm trying to test a web component.
Here is my project structure :</p>

<pre><code>├── package.json
├── src
│   ├── app.js
│   └── index.html
└── test
    └── hello-world-test.html
</code></pre>

<p>Here is my working 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>class HelloWorld extends HTMLElement {
    connectedCallback () {
      this.innerHTML = 'Hello, World!'
    }
}
customElements.define('hello-world', HelloWorld);</code></pre>
<pre class=""snippet-code-html lang-html prettyprint-override""><code>&lt;!doctype html&gt;
&lt;html&gt;

&lt;head&gt;
    &lt;meta charset=""utf-8""&gt;
    &lt;script src=""app.js""&gt;&lt;/script&gt;
&lt;/head&gt;

&lt;body&gt;
    &lt;hello-world&gt;&lt;/hello-world&gt;
&lt;/body&gt;

&lt;/html&gt;</code></pre>
</div>
</div>
</p>

<p>I'm trying to test that web component with <code>web-component-tester</code>.
I installed the utility globally :</p>

<pre><code>npm install -g web-component-tester
</code></pre>

<p>I declared it in the <code>package.json</code> file :</p>

<pre><code>""devDependencies"": {
    ""web-component-tester"": ""^6.9.0""
}
</code></pre>

<p>then, I wrote my test in the <code>test</code> folder and saved it to <code>hello-world-test.html</code>:</p>

<pre><code>&lt;!doctype html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;meta charset=""utf-8""&gt;
    &lt;script src=""../node_modules/web-component-tester/browser.js""&gt;&lt;/script&gt;
    &lt;script src=""app.js""&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;test-fixture id=""hello-world-fixture""&gt;
            &lt;hello-world&gt;&lt;/hello-world&gt;
    &lt;/test-fixture&gt;
    &lt;script&gt;
        suite('&lt;hello-world&gt;', function(){
            let component = document.querySelector('hello-world');

            test('contains hello world string ?', () =&gt; {
                let index = component.innerText.indexOf('Hello');
                assert.isAtLeast(index, 0);
            });
        });
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p>Finally, I typed :</p>

<pre><code>wct --npm
</code></pre>

<p>Then obtained the following error in Chrome :</p>

<p><img src=""https://i.stack.imgur.com/0IjZh.png"" alt=""Here is the result in Chrome""></p>

<p>What am I missing to run the test correctly ?
The only decent materials I've found are <a href=""https://bendyworks.com/blog/native-web-components"" rel=""nofollow noreferrer"">this one</a> and <a href=""https://github.com/pearlbea/mini-form"" rel=""nofollow noreferrer"">that one</a> but they are outdated.</p>
",https://stackoverflow.com/questions/53463201/web-component-htmlelement-unit-testing,"['html', 'unit-testing', 'web-component', 'web-component-tester']",1953,TRUE,4,2
Unit testing an executor callable,"<p>I have a controller class like this that passes some executor into an instance of runnable.
This isn't how it works but just for simplicity I did it like this.</p>

<pre><code>package com.test.executor;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Controller {
    private ExecutorService executor;

    public Controller() {
        executor = Executors.newCachedThreadPool();
    }

    public void doRun() {
        MyRunner runner = new MyRunner(executor);
        Thread myRunner = new Thread(runner);
        myRunner.start();
    }

    public static void main(String[] args) {
        new Controller().doRun();
    }
}
</code></pre>

<p>The runner receives the instance of the executor and then passes certain callables.
Now, the callables are a bit diverse as some callables access the database/call some web service/file system</p>

<p>I am having some issues on how to write a proper JUnit for this case.
I wanted to have as much code coverage as possible.</p>

<pre><code>package com.test.executor;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class MyRunner implements Runnable {

    private ExecutorService executor;

    public MyRunner(ExecutorService executor) {
        this.executor = executor;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        Future&lt;Boolean&gt; ret1 = executor.submit(new SampleCall1());

        try {
            ret1.get(5, TimeUnit.MINUTES);
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            e.printStackTrace();
        }

        // Do other things

        Future&lt;List&lt;String&gt;&gt; ret2 = executor.submit(new SampleCall2());

        try {
            ret2.get(5, TimeUnit.MINUTES);
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            e.printStackTrace();
        }

        // Do other things

        Future&lt;Long&gt; ret3 = executor.submit(new SampleCall3());

        try {
            ret3.get(5, TimeUnit.MINUTES);
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            e.printStackTrace();
        }
    }

    public static class SampleCall1 implements Callable&lt;Boolean&gt; {

        @Override
        public Boolean call() throws Exception {
            // Sample Return Only
            // This will call JSON web service
            return true;
        }

    }

    public static class SampleCall2 implements Callable&lt;List&lt;String&gt;&gt; {

        @Override
        public List&lt;String&gt; call() throws Exception {
            // Sample Return Only
            // This will call Database
            return Collections.EMPTY_LIST;
        }

    }

    public static class SampleCall3 implements Callable&lt;Long&gt; {

        @Override
        public Long call() throws Exception {
            // Sample Return Only
            // This will access some file system
            return 1L;
        }

    }

}
</code></pre>

<p>My question is what is the proper way to write a unit test for this.  I am gathering some advice on how I can unit test this class?
I am not sure what to mock in my junit/mockito instance.
Should I mock each callable? And then create a test case for MyRunner.</p>

<p>I worry about the dependency..as I am connecting into a database/a web service/and file system so I would like to ask for some advice. </p>

<p><strong>UPDATE 2</strong></p>

<pre><code>package com.test.executor;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class MyRunner implements Runnable {

    private ExecutorService executor;

    public MyRunner(ExecutorService executor) {
        this.executor = executor;
    }

    @Override
    public void run() {
        executeTasks1();
        // Do other things

        executeTasks2();
        // Do other things


        executeTasks3();

    }

    public boolean executeTasks1(){
        // TODO Auto-generated method stub
        Future&lt;Boolean&gt; ret1 = executor.submit(new SampleCall1());

        try {
            return ret1.get(5, TimeUnit.MINUTES);
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            e.printStackTrace();
        }

    }

    public List&lt;String&gt; executeTasks2(){
        Future&lt;List&lt;String&gt;&gt; ret2 = executor.submit(new SampleCall2());

        try {
            return ret2.get(5, TimeUnit.MINUTES);
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            e.printStackTrace();
        }
    }

    public Long executeTasks3(){
        Future&lt;Long&gt; ret3 = executor.submit(new SampleCall3());

        try {
            return ret3.get(5, TimeUnit.MINUTES);
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            e.printStackTrace();
        }
    }

    public static class SampleCall1 implements Callable&lt;Boolean&gt; {

        @Override
        public Boolean call() throws Exception {
            // Sample Return Only
            // This will call JSON web service
            return true;
        }

    }

    public static class SampleCall2 implements Callable&lt;List&lt;String&gt;&gt; {

        @Override
        public List&lt;String&gt; call() throws Exception {
            // Sample Return Only
            // This will call Database
            return Collections.EMPTY_LIST;
        }

    }

    public static class SampleCall3 implements Callable&lt;Long&gt; {

        @Override
        public Long call() throws Exception {
            // Sample Return Only
            // This will access some file system
            return 1L;
        }

    }

}
</code></pre>
",https://stackoverflow.com/questions/51586922/unit-testing-an-executor-callable,"['java', 'unit-testing', 'junit', 'mockito']",8065,TRUE,4,2
Unit Testing with Mockito &amp; Firebase,"<p>I am attempting to implement testing for an android app that I'm building. One of the tests involves an interactor file I wrote (<code>DatabaseInteractor.java</code>) that connects to Google Firestore. The default constructor sets the <code>FirestoreFirebase</code> object to <code>FirebaseFirestore.getInstance();</code>.</p>

<p>I am using Mockito &amp; JUnit for my unit tests. When I attempt to create a DataBaseInteractor object in my Unit Test, I get the following error:</p>

<p><code>java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process null. Make sure to call FirebaseApp.initializeApp(Context) first.</code></p>

<p>Apparently this error occurs when the default constructor is called in my Unit Test. I'm not sure why this is happening. I am able to create a DataBaseInteractor object in other parts of my android app without issue. Are there perhaps limitations to when and where I can initialize a class that utilizes <code>FireBaseFireStore</code> objects? If I want to mock the behavior of FireBase for unit testing, how do I get around these restrictions?</p>

<p>EDIT: A truncated version of my <code>DataBaseInteractor.java</code> file:</p>

<pre><code>public class DatabaseInteractor {
    private static User theUser;
    private FirebaseFirestore db;
    private DocumentReference userData;


    public DatabaseInteractor() {
        db = FirebaseFirestore.getInstance();
        theUser = new User();
    }
 // ... various methods that add/retrieve Users from FireStore ... //
}
</code></pre>
",https://stackoverflow.com/questions/53473006/unit-testing-with-mockito-firebase,"['android', 'firebase', 'unit-testing', 'mockito', 'google-cloud-firestore']",11453,TRUE,11,1
Unit testing css with angular,"<p>Is there any way in which I could test say the <code>height</code> css property of an element?</p>

<p>I have a function that changes the height of a <code>div</code> and it would be nice to check in the tests that the function operates correctly...</p>

<p><strong>ie:</strong></p>

<pre><code>&lt;div #myDiv&gt;Hello world&lt;/div&gt;
</code></pre>

<hr>

<pre><code>@ViewChild('myDiv') myDiv: ElementRef;

myFunct() {
  this.myDiv.nativeElement.style.height = 500;
}
</code></pre>

<hr>

<pre><code>it('should increase div size', () =&gt; {
  // Here is where I get stuck...
});
</code></pre>

<h2>Update</h2>

<p>Implementing a test such as:</p>

<pre><code>it('should return correct height of dropdown when initialised', () =&gt; {
    component.myFunct();

    expect(component.dropdown.nativeElement.style.height).toBe(34);
  });
</code></pre>

<p>results in a test failure with message:</p>

<blockquote>
  <p>Expected '' to be 500.</p>
</blockquote>
",https://stackoverflow.com/questions/52782000/unit-testing-css-with-angular,"['html', 'css', 'angular', 'testing']",6146,TRUE,3,1
Unit testing macros in racket,"<p>I'm currently working my way through ""beautiful racket"", trying to write unit tests as I go. </p>

<p>What is the best way to unit test macros? for example, if I have a macro <code>infix</code>:</p>

<pre><code>(define-macro (infix [A B C]) #'(B A C))
</code></pre>

<p>what is the most sensible way to test the pattern matching, and the transformation? I'd like to do something like:</p>

<pre><code>(check equal? (infix '(3 - 2)) '(- 3 2))
</code></pre>
",https://stackoverflow.com/questions/51196340/unit-testing-macros-in-racket,"['unit-testing', 'racket']",192,TRUE,3,1
interpret python coverage unit testing,"<p>I am currently unit testing and was confused on the the below:</p>

<pre><code>     Name                    Stmts   Miss Branch BrPart  Cover   Missing
     -------------------------------------------------------------------
     src/__init__.py             0      0      0      0   100%  
     src/__main__.py            33      2      8      3    88%   76-78, 50-&gt;exit, 57-&gt;exit, 70-&gt;76
</code></pre>

<p>what exactly does the 50-> exit mean?</p>
",https://stackoverflow.com/questions/52593874/interpret-python-coverage-unit-testing,"['python', 'code-coverage']",710,TRUE,3,1
Vue.js unit testing best practice,"<p>It's a general question. but i am curious to ask: there are many packages for vue js unit testing. </p>

<ul>
<li><a href=""https://github.com/vuejs/vue-test-utils"" rel=""nofollow noreferrer"">Vue Test Utils</a></li>
<li><p><a href=""https://github.com/vuejs/vue-jest/tree/jest-vue"" rel=""nofollow noreferrer"">Vue Jest</a></p></li>
<li><p><a href=""https://github.com/bahmutov/cypress-vue-unit-test"" rel=""nofollow noreferrer"">Vue Cypress</a></p></li>
</ul>

<p>which one would be best practice or recommended for enterprise project?</p>
",https://stackoverflow.com/questions/53650733/vue-js-unit-testing-best-practice,"['javascript', 'vue.js', 'vuejs2', 'vue-cli-3', 'vue-test-utils']",836,TRUE,2,1
Unit testing framework for ESP8266,"<p>is there any way to unit test my classes written in c++ for ESP8266 Arduino platform? I really cannot find anything related material on the internet. I thought a widely used c++ unit testing library will work, but arduino is different as it has no try-catch blocks (thus exceptions) and other disadvantages compared to standard c++ etc etc.</p>

<p>What i need is simple: some assertion library, structuring capabilities (suites,test cases,...) and some kind of mocking and checking whether a method was called or not. 
Can anybody help?</p>
",https://stackoverflow.com/questions/48151622/unit-testing-framework-for-esp8266,"['c++', 'unit-testing', 'esp8266', 'arduino-esp8266']",1011,TRUE,2,1
Unit testing repository spring org.springframework.beans.factory.UnsatisfiedDependencyException,"<ol start=""2"">
<li><p>I'm using Spring Boot and MongoDB to create a simple school application. I want to test the methods that are defined in the service class but I get the following exception:</p>

<pre><code>org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name'com.backintime.BackInTimeSpring.Service.TeacherServiceTest': Unsatisfied dependency expressed through field 'teacherService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying     bean of type 'com.backintime.BackInTimeSpring.Service.TeacherService' available:     expected at least 1 bean which qualifies as autowire candidate. Dependency annotations:    {@org.springframework.beans.factory.annotation.Autowired(required=true)}
</code></pre></li>
<li><p>My classes are the following:</p></li>
<li><p>Repository:</p>

<pre><code>package com.backintime.BackInTimeSpring.Model.Repository;
@Component
@Repository
public interface ITeacherRepository extends MongoRepository&lt;Teacher,String&gt; {

@Query(""{}"")
Stream&lt;Teacher&gt; findAllTeachers();

List&lt;Teacher&gt; findByLastNameIgnoreCase(String lastName);
List&lt;Teacher&gt; findByFirstNameIgnoreCase(String firstName);

}
</code></pre></li>
<li><p>Service:</p>

<pre><code>package com.backintime.BackInTimeSpring.Service;
@Component
@Service
public class TeacherService {
@Autowired
private ITeacherRepository teacherRepository;

public List&lt;Teacher&gt; retrieveAllTeachers(){
    return       this.teacherRepository.findAllTeachers().sorted(Comparator.comparing(Teacher::getLastName)).collect(Collectors.toList());
}
public Teacher retrieveTeachersById(String id) {
    return this.teacherRepository.findAllTeachers().filter(t -&gt; t.getId().equals(id)).findFirst().get();
}
public List&lt;Teacher&gt; retrieveTeachersByLastName(String lastName){
    return this.teacherRepository.findByLastNameIgnoreCase(lastName);
}
public List&lt;Teacher&gt; retrieveTeachersByFirstName(String firstName){
    return this.teacherRepository.findByFirstNameIgnoreCase(firstName);
}
public void saveTeacher(Teacher t){
    this.teacherRepository.save(t);
}

public String greet() {
    return ""Hello World"";
}
</code></pre>

<p>}</p></li>
<li><p>Unittest:</p>

<pre><code>package com.backintime.BackInTimeSpring.Service;
@RunWith(SpringRunner.class)
@ComponentScan(basePackages = ""com.backintime.BackInTimeSpring"")
public class TeacherServiceTest {

@Autowired
TeacherService teacherService;
@Test
public void retrieveAllTeachers() {
    assertEquals(3, teacherService.retrieveAllTeachers().size());
}
</code></pre></li>
</ol>
",https://stackoverflow.com/questions/53721342/unit-testing-repository-spring-org-springframework-beans-factory-unsatisfieddepe,"['java', 'spring', 'mongodb', 'junit']",257,TRUE,2,1
Karma Input parameter unit testing,"<p>I'm having problems with unit testing in angular 6. I'm trying to test a simple component with one <code>input()</code> parameter. The problem was that I don't know how to continue. I receive an error when executing <code>ng test</code> :</p>

<blockquote>
  <p>TypeError: Cannot read property 'id_profile' of undefined</p>
</blockquote>

<p>My code is this: </p>

<blockquote>
  <p>Model </p>
</blockquote>

<pre><code>export class Profile {    
  id_profile: string;
  name: string;
}
</code></pre>

<blockquote>
  <p>html</p>
</blockquote>

<pre><code>&lt;div class=""card"" (click)=""clicked()""&gt;
    &lt;div id=""profile""&gt;{{profile.id_profile}}&lt;/div&gt;
    &lt;i class=""material-icons""&gt;vpn_key&lt;/i&gt;
&lt;/div&gt;
</code></pre>

<blockquote>
  <p>component</p>
</blockquote>

<pre><code>import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { Router } from '@angular/router';    
import { Profile } from 'app/models';


@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.scss']
})

export class ProfileComponent {

  @Input() profile: Profile;

  private profileShown: Profile;

  constructor(public router: Router) {
  }

  OnInit() {
    this.profileShown= this.profile;
  }

  clicked() {
    this.profileShown= this.profile;
    this.router.navigate(['pages']);
  }   
}
</code></pre>

<p>And finally, my test :</p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { ProfileComponent} from './profile.component';

describe('ProfileComponent', () =&gt; {
  let component: ProfileComponent;
  let fixture: ComponentFixture&lt;ProfileComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [RouterTestingModule],
      declarations: [ProfileComponent]
    })
      .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(ProfileComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () =&gt; {
    component.profile= {
      'id_profile': '12345678A',
      'name': 'SUMUM_D',      
    };
    fixture.detectChanges();
    expect(component).toBeTruthy();
  });
});
</code></pre>

<p>What I have to do to solve this problem? Am I doing the correct things? Thanks in advance</p>
",https://stackoverflow.com/questions/51422496/karma-input-parameter-unit-testing,"['angular', 'typescript', 'unit-testing', 'testing', 'karma-jasmine']",1676,TRUE,2,2
Unit testing Inquirer with Jest,"<p>I've been trying to understand searching various forums, but could not get to what I'm looking for. Partly because of my NodeJS ignorance. I'm just starting up.</p>

<p>My task is to unit test inquirer based CLI via Jest/Mocha. How do I mock and test this.</p>

<p>My cli.js looks like this -</p>

<pre><code>var inquirer = require('inquirer');

var question = {
  name: 'name',
  message: 'Enter your name : '
};

inquirer
.prompt([question])
.then (function(response) {
    console.log(JSON.stringify(response))
    }
);
</code></pre>

<p>If I just were to ensure that the user passed value can't be longer than 10 characters, how do I write test for this. </p>

<p>Can someone point to what would my unit test code for this via Jest would be (ofcourse using any of the mocking packages).</p>

<p>Thanks in advance for your help !</p>
",https://stackoverflow.com/questions/53463776/unit-testing-inquirer-with-jest,"['node.js', 'mocha.js', 'command-line-interface', 'jestjs', 'inquirer']",1353,TRUE,2,1
Android Accessibility Service Unit Testing,"<p>I am creating an Accessibility Service.  </p>

<p>Currently the application just Overrides the onAccessibilityEvent method, and puts into a JSON object some of the event data.  When I start the service, and run another application, the service does capture and log the events that occur on the other app.</p>

<p>How do you unit test an accessibility service></p>

<p>For example can I set up Unit Tests in my Accessibility Service to test if particular buttons on another app are clicked and control that programmatically?</p>
",https://stackoverflow.com/questions/51216239/android-accessibility-service-unit-testing,"['android', 'unit-testing', 'service', 'automated-tests', 'accessibility']",223,FALSE,2,0
Golang Unit Testing: error conditions,"<p>How do I test error conditions, &amp; other unexpected code flow, in Golang?</p>

<p>Suppose I have code as follows:</p>

<pre><code>import crypto
func A(args) error {
    x, err := crypto.B()
    if err != nil {
        return err
    }
    return nil
}
</code></pre>

<p><code>B</code> is some function. I believe that the only way for me to test this failure scenario is to change the value of <code>B</code> for my test (mock it so it returns an error). Things I have tried:</p>

<p>1) monkeypatch the function just before the test and unpatch afterwards.
This was a horrible idea. Caused all sorts of weird issues as the
tests were running.</p>

<p>2) Pass <code>B</code> as an argument to <code>A</code>. This is all well and good but it also
means that I have to change the definition for <code>A</code> and then update
every use of it every time the implementation changes. Furthermore,
<code>A</code> may be using many imported functions and putting them all in the
type definition for <code>A</code> just seems ugly and not idiomatic.</p>

<p>3) Change the value of <code>B</code> for my test, then change it back.</p>

<pre><code>import crypto.B
cryptoB = crypto.B
func A(args) error {
    x, err := cryptoB()
    if err != nil {
        return err
    }
    ...
 }

 func Test_A(t *testing.T) {
     oldB := cryptoB
     cryptoB = mockB
     // run test
     cryptoB = oldB
     ...
 }
</code></pre>

<p>I've been using method #3 as it allows me fine grained unit testing control while not creating too much overhead. That said, it's ugly and causes confusion e.g. ""Why are we renaming all of the imported functions?"".</p>

<p>What should I be doing? Please help me so my codes can be more better :)</p>
",https://stackoverflow.com/questions/50919260/golang-unit-testing-error-conditions,"['unit-testing', 'go']",4884,TRUE,2,2
ASP.NET Web Site - Unit testing,"<p>Is it possible to do any unit testing with an ASP.NET Web site (not a project or application)? If so, how can I implement them. If not, what options do I have (convert to web app, no unit testing, etc)?</p>

<p>It doesn't appear it is possible (or is fairly difficult) but I'd like to see what other options are available.</p>
",https://stackoverflow.com/questions/48156229/asp-net-web-site-unit-testing,"['c#', 'asp.net', 'webforms']",413,FALSE,2,0
unit testing observables with createSpyObj,"<p>I have a function that calls another that itself uses a http subscription, and I am having trouble testing it...</p>

<p><strong>MyComponent</strong></p>

<pre><code>id = 1;

myFunct() {
  this.myService.delete(this.id);
}
</code></pre>

<p><strong>MyService</strong></p>

<pre><code>delete(id) {
  this.http.delete(this.myUrl + '/' + id).subscribe()
}
</code></pre>

<p><strong>Test</strong></p>

<pre><code>let mockService;

beforeEach(() =&gt; {
  TestBed.configureTestingModule({
    mockService = createSpyObj(['delete']);

    imports: ...,
    declarations: ...,
    providers: [
      {provide: MyService, useValue: mockService}
    ]
  }).compileComponents();

  fixture = ...;
  component = ...;
  fixture.detectChanges();
});

it('should test delete', () =&gt; {
  mockService.delete.and.returnValue({ subscribe: () =&gt; {} });
  component.myFunct();
  expect(mockService.delete).toHaveBeenCalledTimes(1);
});
</code></pre>

<p>My test brings back the error:</p>

<blockquote>
  <p>Cannot read property 'subscribe' of undefined</p>
</blockquote>
",https://stackoverflow.com/questions/53867825/unit-testing-observables-with-createspyobj,"['angular', 'typescript', 'unit-testing', 'mocking', 'spy']",1770,TRUE,2,1
Hot Reload during Unit testing,"<p>I develop right now a small flutter app. I think as everyone, I fell in love with the hot reload feature. </p>

<p>So now I'm wondering if there is any possibility to have the same developer experience during unit test. Do have to turn a flag somewhere or is it right know just no possible.</p>

<p>If is not possible, are there any plans to make it possible?</p>
",https://stackoverflow.com/questions/49004259/hot-reload-during-unit-testing,"['testing', 'dart', 'tdd', 'flutter']",1321,TRUE,1,2
Django unit testing for Verbose_name,"<p>Below is a class in model.py </p>

<pre><code>class UnitUsers(models.Model):
    unit = models.ForeignKey(Unit, on_delete=models.CASCADE)
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
                             on_delete=models.CASCADE)
    create = models.BooleanField(default=False)
    mark = models.BooleanField(default=False)
    submit = models.BooleanField(default=True)

    def __str__(self):
        return str(self.unit) + "" - "" + str(self.user)

    class Meta:
        verbose_name = _('Unit User')
        verbose_name_plural = _('Unit Users')
</code></pre>

<p>Tried to write test case for verbose_name as below</p>

<pre><code>class UnitUsersTest(TestCase):

    @classmethod
    def setUpTestData(cls):
        unit = Unit.objects.create(name='Python', 
                                   start='2018-10-25 14:30:59', 
                                   end='2017-10-25 14:30:59',
                                   description='111', deleted='False')
        user = get_user_model().objects.create_superuser(username='admin', 
                                                  email='admin@decent.mark',
                                                  password='password')
        UnitUsers.objects.create(unit=unit, user=user, create='False', 
                                 mark='False', submit='True')


    def test_verbose_name(self):
        unit_user = UnitUsers.objects.get(id=1)
        field_label = unit_user._meta.get_field('user').verbose_name
        self.assertEquals(field_label, 'Unit User')
</code></pre>

<p>Getting error as </p>

<h2>FAIL: test_verbose_name (decentmark.tests.test_model.UnitUsersTest)</h2>

<p>Traceback (most recent call last):
  File ""C:\Users\Prabhanjan\Documents\GitHub\decentmark\decentmark\tests\test_model.py"", line 54, in test_verbose_name
    self.assertEquals(field_label, 'Unit User')
AssertionError: 'user' != 'Unit User'
- user
+ Unit User</p>

<hr>

<p>Ran 11 tests in 0.505s</p>

<p>FAILED (failures=1)</p>
",https://stackoverflow.com/questions/52600900/django-unit-testing-for-verbose-name,"['django', 'unit-testing', 'django-models']",611,TRUE,1,1
Unit testing Dart async stream,"<p>I am trying to create a list in Dart that sends events each time an object is added or removed from it, and I'm having trouble figuring out how to write a unit test for it.</p>

<p>Here's the code for the list:</p>

<pre><code>enum Action { Insert, Modify, Remove }

class ListChangeEvent {
  final int index;
  final Action action;
  final PathComponent component;

  ListChangeEvent(this.index, this.action, this.component);
}

class PathComponentList extends DelegatingList&lt;PathComponent&gt; {
  final List&lt;PathComponent&gt; _list = [];

  @override
  List&lt;PathComponent&gt; get delegate =&gt; _list;

  var changeController = new StreamController&lt;ListChangeEvent&gt;();
  Stream&lt;ListChangeEvent&gt; get onChange =&gt; changeController.stream;

  @override
  void add(PathComponent value) {
    super.add(value);
    changeController
        .add(new ListChangeEvent(this.indexOf(value), Action.Insert, value));
  }
}
</code></pre>

<p>Now what I'd like to do is create a unit test to verify that each time I insert an element, I get a ListChangeEvent delivered in the stream.</p>

<p>Here's my current attempt. This hangs forever, I'm sure because I never close the stream.</p>

<pre><code>void main() {
  group('PathComponentList', () {
    PathComponentList list = PathComponentList();
    var body = PathComponent(Path.Body);
    var chance = PathComponent(Path.Chance);
    var crossroads = PathComponent(Path.Crossroads);

    setUp(() async {
      list = PathComponentList();
    });

    test('should fire event when adding', () async {
      list.add(body);
      list.add(chance);
      list.add(crossroads);

      List&lt;ListChangeEvent&gt; events = await list.onChange.toList();
      expect(events[0].action, equals(Action.Insert));
      expect(events[0].index, equals(0));
      expect(events[0].component, equals(body));
    });
  });
}
</code></pre>

<p>I've tried to get individual element from the stream like this:</p>

<pre><code>await list.onChange.elementAt(index);
</code></pre>

<p>But if I do this more than once, the code complains that I've already listened to the stream.</p>

<p>Since I want the stream to send ListChangeEvents for the lifetime of the application, what is the best way to read the three ListChangeEvents that are written to this stream in my unit test?</p>
",https://stackoverflow.com/questions/51771121/unit-testing-dart-async-stream,"['unit-testing', 'async-await', 'dart']",1838,TRUE,1,1
Unit testing Spring throws BeanNotOfRequiredTypeException,"<p>Running a test class throws the following exception:</p>

<pre><code>BeanNotOfRequiredTypeException: Bean named 'myServiceImpl' is expected to be of type 'MyServiceImpl' but was actually of type 'com.sun.proxy.$Proxy139'
</code></pre>

<p>This error gets thrown only with unit tests, the program itself works.</p>

<p><strong>My Interface</strong></p>

<pre><code>public interface MyService {

    public String testMethod();

}
</code></pre>

<p><strong>My Implementation</strong></p>

<pre><code>@Service
public class MyServiceImpl implements MyService{

    @Autowired
    private TransactionRepository transactionRepo;

    @Autowired
    private AccountRepository accountRepository;

    @Autowired
    private BankAccountStatementFactory baStatementFactory;

    public String myMethod() {
        return ""Run My Method"";
    }

}
</code></pre>

<p><strong>My Unit Test</strong></p>

<pre><code>@RunWith(SpringRunner.class)
@SpringBootTest
public class DeleteMeTest{


    @Mock
    private TransactionRepository transactionRepo;

    @Mock
    private AccountRepository accountRepository;

    @Mock
    private BankAccountStatementFactory baStatementFactory;

    @InjectMocks
    @Resource
    MyServiceImpl myService;


    @org.junit.Before
    public void setUp() throws Exception {
        // Initialize mocks created above
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void test() {
        myService.myMethod();
        System.out.println(""My Unit Test"");
    }

}
</code></pre>

<p>Running this test class throws the following exception:</p>

<pre><code>BeanNotOfRequiredTypeException: Bean named 'myServiceImpl' is expected to be of type 'MyServiceImpl' but was actually of type 'com.sun.proxy.$Proxy139'
</code></pre>

<p>A solution here is to inject the Interface, not the implementation into the unit test but this will not allow me to inject mocks. </p>

<p>Thats because an implementation is required with the @InjectMocks annotation. When I try to inject mocks into the interface I get the following exception:</p>

<pre><code>Cannot instantiate @InjectMocks field named 'myService'! Cause: the type 'MyService' is an interface.
</code></pre>

<p>Just to be clear, all this worked in the beginning and went bad once I repackaged my classes. That could be the cause but not 100% sure.</p>

<p>Any hints on what might cause this <code>BeanNotOfRequiredTypeException</code>?</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/53337768/unit-testing-spring-throws-beannotofrequiredtypeexception,"['java', 'spring', 'unit-testing', 'exception']",643,FALSE,1,2
MVC BaseController Unit Testing Coverage,"<p>This is a best practice question. All my controllers do the same things with the only difference being in the repositories and queries that are specific to each so all the CRUD actions are in a BaseController with overrides for the specific controllers as needed.</p>

<p>So my question is, if I pick one derived controller and unit test all the actions, can I safely assume the other derived controllers are good, or should I still test each and every controller?</p>

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

<p>Here's an example to make it clearer what's taking place, and I'm fine with whatever is the best practice, I'm just making sure I'm finding the right balance between thorough testing and testing myself to death. The example below just shows one short action to keep the example small, but the BaseController also handles Create, CreatePost, Edit, EditPost, and Delete.</p>

<pre><code>public abstract class BaseController&lt;TEntity&gt; : Controller where TEntity : class
{
    public BaseController()
    { }

    public async Task&lt;IActionResult&gt; Details(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        TEntity entity = await DetailsQueryAsync(id);

        if (entity == null)
        {
            return NotFound();
        }

        return View(entity)
    }

    protected virtual Task&lt;TEntity&gt; DetailsQueryAsync(int? id)
    {
        throw new NotImplementedException();
    }
}

public class StudentsController : BaseController&lt;Student&gt;
{
    private readonly IRepository&lt;Student&gt; studentRepository;

    public StudentsController(UnitOfWork&lt;SchoolContext&gt; unitOfWork)
        : base()
    {
        studentRepository = unitOfWork.StudentRepository;
    }

    protected override async Task&lt;Student&gt; DetailsQueryAsync(int? id)
    {
        return await studentRepository.Get(id.Value)
                         .AsNoTracking()
                         .SingleOrDefaultAsync();
    }
}
</code></pre>
",https://stackoverflow.com/questions/53858533/mvc-basecontroller-unit-testing-coverage,"['asp.net-mvc', 'unit-testing']",150,TRUE,1,1
Rhino Mocks async unit testing,"<p><strong>Environment</strong><br>
Rhino Mocks version: 3.6.1<br>
Visual Studio: 2017<br>
Resharper: 2017.3.3<br>
Nunit: 2.6.4</p>

<p>I run the 2 test fixtures together using Resharper. When I do so I get an error:</p>

<blockquote>
  <p>System.InvalidOperationException : Previous method 'IService.DoThing();' requires a return value or an exception to throw.
     at Rhino.Mocks.Impl.RecordMockState.AssertPreviousMethodIsClose()
     at Rhino.Mocks.Impl.RecordMockState.Replay()
     at Rhino.Mocks.MockRepository.ReplayCore(Object obj, Boolean checkInsideOrdering)
     at Rhino.Mocks.RhinoMocksExtensions.Expect[T,R](T mock, Function<code>2 action)
     at Rhino.Mocks.RhinoMocksExtensions.Stub[T,R](T mock, Function</code>2 action)
     at MobileServices.Api.Tests.Unit.TestFixture2.d__2.MoveNext() in C:\SCM\MyProject.Tests.Unit\ExampleTests.cs:line 42
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
     at NUnit.Framework.Internal.AsyncInvocationRegion.AsyncTaskInvocationRegion.WaitForPendingOperationsToComplete(Object invocationResult)
     at NUnit.Framework.Internal.Commands.TestMethodCommand.RunAsyncTestMethod(TestExecutionContext context)</p>
</blockquote>

<p>When I run the two test fixtures multiple times, the test source for the error changes constantly between TestFixture1.Test1 to TestFixture2.Test1. When I run the test fixtures in isolation everything passes. Is this an issue with Rhino Mocks and threading?</p>

<pre><code>using Project.Tests.Unit.SupportingClasses;
using NUnit.Framework;
using System.Threading.Tasks;
using Rhino.Mocks;

namespace Project.Tests.Unit
{
    [TestFixture]
    public class TestFixture1
    {
        private IService _service;

        [SetUp]
        public void SetUp()
        {
            _service = MockRepository.GenerateMock&lt;IService&gt;();
        }

        [Test]
        public async Task Test1()
        {
            _service.Stub(s =&gt; s.DoThing()).Return(Task.FromResult(true));

            var response = await _service.DoThing();
        }
    }

    [TestFixture]
    public class TestFixture2
    {
        private IService _service;

        [SetUp]
        public void SetUp()
        {
            _service = MockRepository.GenerateMock&lt;IService&gt;();
        }

        [Test]
        public async Task Test1()
        {
            _service.Stub(s =&gt; s.DoThing()).Return(Task.FromResult(true));

            var response = await _service.DoThing();
        }
    }
}

namespace Project.Tests.Unit.SupportingClasses
{
    public interface IService
    {
        Task&lt;bool&gt; DoThing();
    }
}
</code></pre>
",https://stackoverflow.com/questions/52839947/rhino-mocks-async-unit-testing,"['c#', 'unit-testing', 'asynchronous', 'async-await', 'rhino-mocks']",866,TRUE,1,1
Unit Testing a Task&lt;ViewResult&gt;,"<p>Previously, I had a synchronous controller action method that had a unit test with the line</p>

<pre><code>ManageBillsViewModel result = controller.ManageBills(2).ViewData.Model as ManageBillsViewModel;
</code></pre>

<p>and all was well. When the action method was changed to an asynchronous <code>Task&lt;ViewResult&gt;</code> method, the above line broke. </p>

<p>I thought I could get it working by adding <code>.Result</code> as in </p>

<pre><code>ManageBillsViewModel result = controller.ManageBills(2).Result.ViewData.Model as ManageBillsViewModel;
</code></pre>

<p>but this did not work. </p>

<p>How can I appropriately access the <code>ViewData.Model</code> of an asynchronous method?</p>
",https://stackoverflow.com/questions/49101910/unit-testing-a-taskviewresult,"['c#', 'asp.net-mvc', 'unit-testing', 'xunit']",188,TRUE,1,2
Connection unit testing in Python,"<p>I am new to Python unit testing and I am not sure how i can create a unit test of this function that returns a connection?</p>

<pre><code>def connection(self):
    connection = mysql.connector.connect(host='localhost', 
                     database='test',
                     user='user', 
                     password='password',
                     auth_plugin='mysql_native_password')
    return connection
</code></pre>
",https://stackoverflow.com/questions/53255485/connection-unit-testing-in-python,"['python', 'python-unittest', 'mysql-connector-python', 'python-unittest.mock']",7511,TRUE,1,2
Unit Testing JS - using JEST,"<p>Beginner Level - Unit Testing </p>

<p>Here's the function </p>

<pre><code>export function toHex(number) {
const nstr = number.toString(16);
 if (nstr.length % 2) {
 return `0${nstr}`;
 }
 return nstr;
</code></pre>

<p>Able to figure out if the function is true or not by running the following Unit testing code:</p>

<pre><code>// testing new function 
describe('toHex', () =&gt; {   //mocking the method
test('Testing Function toHex ', () =&gt; { // declaring the method
  const str = 14 // initial value
  const actual = toHex(str) // calculate the value
  expect(actual).toMatchSnapshot(); // checking whether is true
})
});
</code></pre>

<p>Now how could I add different scenarios and make the following function to pass / Fail
Thanks</p>
",https://stackoverflow.com/questions/53837254/unit-testing-js-using-jest,"['javascript', 'unit-testing', 'jestjs']",80,FALSE,1,0
PHP Unit testing dispatched events,"<p>How does one test that events were dispatched during a function call?</p>

<pre><code>public function updateUser() {
    //Do some update stuff

    $event = new UserUpdated($user);

    $event-&gt;attach([
        new SendEmailAddressChangeEmail($emailAddress),
        new SendEmailAddressChangeEmail($oldEmailAddress),
    ]);
    $event-&gt;dispatch();
}
</code></pre>

<p>Aside from setting up an email address and seeing if an email is sent, how can I check (using PHP Unit) that the dispatcher is actually dispatching these events? I am assuming that I need to create a mock of some sort, but I am uncertain how to create a mock for a completely unrelated bit of code.</p>

<p>UserUpdated Event code:</p>

<pre><code>class UserUpdated extends BaseEvent
{

    public $user;

    public function __construct(User $user) {
        $this-&gt;user = $user;
    }
}
</code></pre>

<p>and the related SendEmailAddressChanged Handler code:</p>

<pre><code>class SendEmailAddressChangeEmail implements Contracts\HandlerInterface
{
    protected $emailAddress;

    public function __construct($emailAddress) {
        $this-&gt;emailAddress = $emailAddress;
    }

    public function handle($event) {
        EmailUtils::sendEmailAddressChangeEmail($this-&gt;emailAddress, $event-&gt;user-&gt;userName, $event-&gt;user-&gt;userID);
    }
}
</code></pre>
",https://stackoverflow.com/questions/49845580/php-unit-testing-dispatched-events,"['php', 'unit-testing', 'phpunit']",1747,TRUE,1,1
Electron unit testing multiple window,"<p>I have to build desktop application with Electron and AngularJS.
This application must be connected with a device.
I can communicate with the device with a 32bit DLL provided by the manufacturer.</p>

<p>For now, i have an issue with unit testing. I have two window who communicate with ipcRenderer.
One of the window is hidden and only do a loop ""while device is connected"".
But <strong>that freeze the hidden window and the function ""before each"" of my unit testing go into timeout.</strong></p>

<p><strong>How to do unit testing in that configuration ?
Or who to do the loop ""while device is connected"" in better way ?</strong></p>

<p>*NOTE : the loop lock the COM interface</p>

<p>Setup :
- 32 bit version of electron v3.0.4
- electron-edge-js v8.3.8
- spectron v5.0.0
- mocha v5.2.0
- angularJs v1.7.5</p>

<p>C# DLL ""While device connected""</p>

<pre><code>        // while we found epID
        while (mon_epd.EpdID &gt; 0)
        {
            securiteWhile += 1;
            // check every 2 second
            Thread.Sleep(2000);

            mon_retour.code_retour = ""004"";
            ok = OpenDevice(PortSerie, mon_epd.dosi_id);
            if (ok != 1) { EPD_Deconnect(); mon_retour.Add_message(""danger"", ""Impossible d'ouvrir le dosimètre sur le port : "" + PortSerie.ToString()); mon_retour.chaine_retour = mon_epd; return mon_retour; };

            mon_retour.code_retour = ""200"";
            ok = ReadEpdID(ref mon_epd.EpdID, ref mon_epd.HardVersion, ref mon_epd.SoftVersion, ref mon_epd.FunctionFlag);
            if (ok != 1) { EPD_Deconnect(); mon_retour.Add_message(""warning"", ""Dosimètre deconnecté""); mon_retour.chaine_retour = mon_epd; return mon_retour; };

            Commit();
            EPD_Deconnect();
        }
        return mon_retour;
</code></pre>

<p>main.js - window creation</p>

<pre><code>    function createWindow () {
  // window property
  mainWindow = new BrowserWindow({width: 1920, height: 1080, frame: false,
    webPreferences: {
             nodeIntegration: true,
             preload: __dirname+'/preload.js' }})
  // load html file
  mainWindow.loadFile('index.html')

  // when main window is close
  mainWindow.on('closed', function () {
    // On ferme les autres threads
    secondThread.close();
    mainWindow = null

  })
  createWindow2();
}
</code></pre>

<p>Javascript hidden window</p>

<pre><code>// call c# DLL send response if device is disconnected
  var DLL_WhileDosiConnected = edge.func({
     assemblyFile:'Calculate.dll',
     typeName:'Dosimetre.Startup',
     methodName:'WhileDosiConnected',
     sync:false
  });

  function WhileDosiConnected(){
     DLL_WhileDosiConnected(null, function (error, result) {
       if (error) throw error;
       // when we have a response, send it to main window
       let mainWindow = remote.getGlobal ('mainWindow');
       if (mainWindow) mainWindow.webContents.send ('dosimetrePerdu', result);
    });
  }
</code></pre>
",https://stackoverflow.com/questions/52965579/electron-unit-testing-multiple-window,['electron'],287,FALSE,1,0
unit testing cell is nil,"<p><strong><em>Issue:</em></strong></p>

<p>I loaded collectionView with 3 Dummy items. However Cell came back nil, is it because view was never loaded? How do you guys test your collectionViewCell type?</p>

<p><strong><em>Code</em></strong></p>

<pre><code>var window: UIWindow?
var sut: QuestsDataProvider!
var collectionView: UICollectionView!

override func setUp() {
    super.setUp()
    bulletinController = BulletinController(collectionViewLayout: UICollectionViewFlowLayout())
    sut = QuestsDataProvider(acceptedQuests: false, completedQuests: false)
    bulletinController.collectionView?.dataSource = sut
    bulletinController.collectionView?.delegate = sut

    window = UIWindow()
    window?.makeKeyAndVisible()
    window?.rootViewController = bulletinController
}

func testCellIsQuestCell() {
    let indexPath = IndexPath(item: 1, section: 0)
    let cell = collectionView.cellForItem(at: indexPath)
    guard let count = sut.questManager?.quests.count else {return XCTFail()}
    XCTAssertTrue(cell is QuestCell)
}
</code></pre>

<p>Edit:</p>

<p>Upon Further testing, I'm able to see the dummy Cell inside my simulator and get a accurate count from <code>numberOfitems(InSection: Int)</code>. However I have no visible Cell.</p>

<p>2nd Edit:</p>

<p>After further research, I found out the issue is <code>collectionView.cellForItem(at: indexPath)</code> only shows visible cell. Is there any other method for unit testing collection view cell type?</p>
",https://stackoverflow.com/questions/48361612/unit-testing-cell-is-nil,"['swift', 'unit-testing', 'uicollectionviewcell']",1247,FALSE,1,1
Unit Testing CorrelationId with Rebus,"<p>So assuming I have a <code>Handler</code> that looks like this:</p>

<pre><code>public async Task Handle(Message message)
{
    Guid correlationId = GetCorrelationId();

    var newMessage = new MessageReceived
    {
        horse = message.Horse,
        correlationId = correlationId
    };
}

private static Guid GetCorrelationId()
{
    if (!MessageContext.Current.Headers.TryGetValue(""rbs2-corr-id"", out string correlationId))
    {
        throw new ArgumentException();
    }

    if (!Guid.TryParse(correlationId, out Guid correlationIdGuid))
    {
        throw new ArgumentException();
    }

    return correlationIdGuid;
}
</code></pre>

<p>How would I go about unit testing this? I currently have a (faulty, obviously) test where I just set up a <code>MessageReceived</code> object and passes it on to <code>Handle</code>, but of course it fails at <code>GetCorrelationId</code> since there is no actual <code>MessageContext</code>. Would I have to set up a <code>FakeBus</code> and use that somehow?</p>
",https://stackoverflow.com/questions/50721535/unit-testing-correlationid-with-rebus,['rebus'],239,TRUE,1,1
Angular Unit Testing for ngOnDestroy,"<p>I am doing unit testing for angular components using Jasmine Karma and facing below error</p>

<pre><code>TypeError: this.subscription.unsubscribe is not a function at ScheduledNewContributionsViewComponent.ngOnDestroy (webpack:///./src/app/contributions/scheduled-new-contributions-view/scheduled-new-contributions-view.component.ts?:154:31) at callProviderLifecycles
</code></pre>

<p>This error shows in console when I run unit test for ScheduledNewContributionsViewComponent.
Although my tests are being passed but console window is full of this one error.Its keep on coming on each test.</p>

<p>Below is my ts file    </p>

<pre><code> ngOnInit(): void {
     this.subscription = this.contributionService.editContribution$.subscribe(
              data =&gt; {
                this.scheduledContributionData = data;
                this.headerTitle = this.contributionService.getLabel('ACCTTAB.COMMONREQUESTS.MANAGECONTRIBUTIONS.EDIT');
}
        this.loadEditScheduledContributionData(this.scheduledContributionData);
      });

ngOnDestroy() {
    // prevent memory leak when component destroyed
    if (this.subscription) 
      this.subscription.unsubscribe();
    // if(this.deleteSubscription)
    // this.deleteSubscription.unsubscribe();
  }
</code></pre>

<p>For contributeService Icreated stub and mocked editContribution$</p>

<pre><code> class ContributionServiceStub {

      editContribution$ = {
        subscribe: function(data) {
          return Observable.of(data);
        }
      }
</code></pre>
",https://stackoverflow.com/questions/51274377/angular-unit-testing-for-ngondestroy,"['angular', 'unit-testing', 'jasmine', 'angular5', 'karma-jasmine']",6790,TRUE,1,1
Mocking pymongo for unit testing,"<p>I have a simple application in Django REST, I am using Pymongo to connect to MongoDB.
My directory structure is like this:-</p>

<pre><code>appauth/
├── apps.py
├── controllers.py
├── databases
│   ├── initialize_databases.py
│   ├── __init__.py
│   ├── mongo_connector.py
│   ├── redis_connections.py
│   ├── redis_connector.py
├── handlers
│   ├── handlers.py
│   ├── __init__.py
├── helpers
│   ├── helpers.py
│   ├── __init__.py
│   ├── permission_loader.py
├── __init__.py
├── model
│   ├── __init__.py
│   ├── users.py
├── tests.py
├── urls.py
</code></pre>

<p>I have initialised my Mongo connection in mongo connector and imported it to initialise_databases. Then I am importing it from there throughout my application as and where I need it.</p>

<p>My main problem is, when I want to unit test, how do I specifically mock the db code.</p>

<p>For ex:</p>

<pre><code>def login()
    //code//
    last_filled = db.UserSurvey.find_one({'user_id': user_id})
    //code//
    db.UserSecurityData.count({'user_id': user_id})
    user_role = db.User.find_one({'_id': user_id})
</code></pre>

<p>In my tests, if do something like </p>

<pre><code>@patch('pymongo.collection.Collection.find_one')
@patch('pymongo.collection.Collection.update')

def test_03_validate_login(self, mocked_update, mocked_find):
    mocked_find.return_value = user_findone_return 
    //user_findone_return is a variable
    mocked_update.return_value = user_findone_return
    res = self.usr_obj.validate_login(user.email, user.password)
    self.assertEqual(res[""gender""],'Male')
    self.assertEqual(res[""password_expires_in""],45.0)
</code></pre>

<p>The test works perfectly with correct return values.But this seems to mock 
<strong>all</strong> find_one calls. My question is how to I mock different collections and their queries.</p>

<p>My DB settings:-</p>

<pre><code>MONGO_URL = ""mongodb://"" + MONGO_HOST + "":"" + MONGO_PORT + ""/"" + 
MONGO_DB
client = pymongo.MongoClient(MONGO_URL)
db = client.core
</code></pre>

<p>I have tried <code>@patch('pymongo.core.UserSurvey.find_one')</code>
and similar iterations. But nothing seems to work.</p>
",https://stackoverflow.com/questions/50813233/mocking-pymongo-for-unit-testing,"['django', 'mongodb', 'unit-testing', 'django-rest-framework', 'pymongo']",1547,FALSE,1,1
Spring Unit testing rest controller,"<p>What is the best and easiest solution to test these sample get mappings? Could you show some easy example? </p>

<pre><code>@GetMapping(""/"")
public List&lt;UserDto&gt; get() {
    return userService.getUsers().stream().map((User user) -&gt; toUserDto(user)).collect(Collectors.toList());
}

@GetMapping(path = ""/{id}"")
public HttpEntity&lt;UserDto&gt; findById(@PathVariable(name = ""id"") long id) {
    User user = userService.unique(id);
    if (user != null) {
        return new ResponseEntity&lt;&gt;(toUserDto(user), HttpStatus.OK);
    } else {
        return new ResponseEntity&lt;&gt;(HttpStatus.NOT_FOUND);
    }
}
</code></pre>
",https://stackoverflow.com/questions/48891377/spring-unit-testing-rest-controller,"['spring-boot', 'testing', 'junit', 'get-mapping']",7285,TRUE,1,1
Angular unit testing with parameter,"<p>I am writing a test for a method that takes in an id as a parameter to delete an object. The test case looks like below: </p>

<pre><code>it('should delete the car object for the given ID', () =&gt; {
    const mockId = '1';
    const carObj = component.deleteCar(mockId);
    expect(carObj).not.toEqual('1');
  });
</code></pre>

<p>The test case passes. However when I change the value for assertion from '1' to '2', it still passes the test. Where am I going wrong ? </p>
",https://stackoverflow.com/questions/53670178/angular-unit-testing-with-parameter,"['angular', 'testing', 'jasmine']",2379,FALSE,1,1
Unit Testing Generic Methods (NUnit),"<p>I have been trying to implement the repository pattern in .Net Core using a generic class. This is what i have come up with (ive taken out all but one method to keep it simple). The class / method works, but im trying to write a unit(integration) test for it, in this case the Add Method.</p>

<pre><code>public class Repository&lt;TEntity&gt; : IRepository&lt;TEntity&gt; where TEntity : class
{
    protected readonly DbContext Context;

    public Repository(DbContext context)
    {
        Context = context;
    }

     public void Add(TEntity entity)
    {
        Context.Set&lt;TEntity&gt;().Add(entity);
    }
}
</code></pre>

<p>So far my integration test is as follows,
Set Up makes a SqlLite database to save to
Sets up the DbContext
Sets up a Unit of Work - The unit of work is needed to SaveChanges the the DbContext and can be ignored for the most part</p>

<p>Then im creating a ""StorageSystem"" Domain Object and testing the Generic class. But it feels like I should be able to test it with out passing a specific domain model. Or at the very least, enter the different domain models as parameterised tests.</p>

<pre><code>[TestFixture]
public class RepositoryTests
{
    SqliteConnection _connection;
    DbContextOptions&lt;ApplicationDbContext&gt; _options;
    ApplicationDbContext _context;
    UnitOfWork _uow;

    [SetUp]
    public void SetUp()
    {
        _connection = new SqliteConnection(""DataSource=:memory:"");
        _connection.Open();

        _options = new DbContextOptionsBuilder&lt;ApplicationDbContext&gt;()
            .UseSqlite(_connection)
            .Options;

        using (var context = new ApplicationDbContext(_options))
        {
            context.Database.EnsureCreated();
        }

        _context = new ApplicationDbContext(_options);
        _uow = new UnitOfWork(_context);
    }

    [TearDown]
    public void TearDown()
    {
        _connection.Close();
    }

    [Test]
    public void Add_AddsEntityToRepository()
    {
        //arrange
        var storageSystem = new StorageSystem {Id = 1, Name = ""Storage1""};
        var repo = new Repository&lt;StorageSystem&gt;(_context);

        //act
        repo.Add(storageSystem);
        _uow.Complete();

        //assert
        Assert.AreEqual(1, _context.StorageSystems.Count());
    }
</code></pre>

<p>I am fairly new to working with Generics, The closest solution I could find was using an abstract class. However I couldnt make it working with me code with it not detecting the tests as an abstract class and not being able to make a repository of type TEntity.</p>

<p><a href=""http://codinghelmet.com/articles/how-to-write-unit-tests-for-generic-classes"" rel=""nofollow noreferrer"">Example taken from here</a></p>

<pre><code>[TestFixture]
public abstract class RepositoryTests1&lt;TEntity&gt;
{
    SqliteConnection _connection;
    DbContextOptions&lt;ApplicationDbContext&gt; _options;
    ApplicationDbContext _context;
    UnitOfWork _uow;

    [SetUp]
    public void SetUp()
    {
        _connection = new SqliteConnection(""DataSource=:memory:"");
        _connection.Open();

        _options = new DbContextOptionsBuilder&lt;ApplicationDbContext&gt;()
            .UseSqlite(_connection)
            .Options;

        using (var context = new ApplicationDbContext(_options))
        {
            context.Database.EnsureCreated();
        }

        _context = new ApplicationDbContext(_options);

        _uow = new UnitOfWork(_context);
    }

    [TearDown]
    public void TearDown()
    {
        _connection.Close();
    }

[Test]
public void Add_AddsEntityToRepository_GenericAttempt()
    {
        //arrange
        TEntity entityToAdd = this.CreateEntity();

        var repo = new Repository&lt;TEntity&gt;(_context); //ERROR HERE - TEntity must be a reference type

        //act
        repo.Add(entityToAdd);
        _uow.Complete();

        //assert
        //NO IDEA WHAT THE ASSERTION WOULD BE
    }

    protected abstract TEntity CreateEntity();
}
</code></pre>

<p>So in short, how do i unit test this Generic Repository?</p>
",https://stackoverflow.com/questions/52573168/unit-testing-generic-methods-nunit,"['c#', 'unit-testing', 'generics', 'nunit']",379,TRUE,1,1
Unit Testing for VS2017 project,"<p>I have an ASP.NET application (a basic form where I capture some input) in VS2017.</p>

<p>One of the fields on the form is Mark, which is an integer.</p>

<p>I have the following block of code for the Mark, in my .cs file.</p>

<pre><code>    [Display(Name = ""Mark"")]
    [Range(1, 10, ErrorMessage = ""Mark must be between 1 and 10"")]                              
    public int Mark{ get; set; }
</code></pre>

<p>I've created a MSTest project for this application to write Unit Tests.</p>

<p>My question is, do you write Test Cases for this block to verify the input value is in the expected range?</p>

<p>If yes, how you write that?</p>

<p>I've started with this.</p>

<pre><code>    [DataRow(0, ""Mark must be between 1 and 10"")]
    [DataRow(11, ""Mark must be between 1 and 10"")]
    [DataTestMethod]
    public void TestMark_IsMarkValid_NotValid(int mark, string expectedMsg)
    {
        //Arrange
        Student testStudent = new Student();
        testStudent.Mark = mark; //this does not throw any error, although the assigned value is outside of the defined range. But it looks like the range validation only applies to the webform.

        //Act

        string actualMsg = ""Mark must be between 1 and 10""; //this is not correct. I was thinking to capture in the actual result the error message yield by the Range validation, but assigning a value outside range doesn't yield any error message. 

        //Assert
        Assert.AreEqual(expectedMsg, actualMsg);
    }
</code></pre>

<p>Now, not sure if that block should be in scope for unit testing. If it should be, I have a feeling the approach I've taken is not correct.</p>

<p>Any thoughts, please?</p>

<p>Many thanks,
Cosmin</p>
",https://stackoverflow.com/questions/53259041/unit-testing-for-vs2017-project,"['c#', 'visual-studio', 'unit-testing', 'visual-studio-2017', 'mstest']",59,TRUE,1,1
AWS-CDK Unit-Testing and Integration Testing,"<p>What is the proper way to unit-test and integration-test my newly built constructs? </p>

<p>What should be actually tested?
How should it be tested?</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/53566862/aws-cdk-unit-testing-and-integration-testing,['aws-cdk'],11385,TRUE,15,1
Sequelize unit testing with sinon,"<p><em>I am trying to mock below code:</em></p>

<pre><code> model.findAndCountAll({
            pos: start
        }).then((data) =&gt; {
         this.success(....);
        }).error(error =&gt; {
            this.error(error, this.constants.HTTP_CODE_INTERNAL_SERVER_ERROR)
        })
</code></pre>

<p><em>Below is the code to mock above code:</em></p>

<pre><code>const findAndCountAll =  sinon.stub(model, 'findAndCountAll');
          findAndCountAll.withArgs().returns(new Promise((resolve, reject) =&gt; {
            resolve(data);
          }));
</code></pre>

<p><em>If I remove error part from code to be mocked it works otherwise it gives below error:</em></p>

<pre><code> TypeError: model.findAndCountAll(...).then(...).error is not a function
</code></pre>
",https://stackoverflow.com/questions/51541528/sequelize-unit-testing-with-sinon,['node.js'],1078,FALSE,0,1
unit testing for socket python,"<p>Can someone help on doing unit testing please? The aim for my program is to connect to the iKettle. This is my code:</p>

<pre><code>ip_address = """"
port = 2000
def handShake(self, ip_address):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.connect((ip_address, self.port))
        s.send(""HELLOKETTLE"")
        self.kettleResponse(s)
        s.close()
    except:
        print(""error connecting"")
</code></pre>
",https://stackoverflow.com/questions/48985330/unit-testing-for-socket-python,"['python', 'sockets']",1041,TRUE,0,1
WPF component in unit testing,"<p>I'm coding a Unit testing and for debug purposes I do need to see some data (please do not discus if one should be using UI for unit testing)</p>

<p>I created a UI thread and started my component like this:</p>

<pre><code>System.Threading.Thread newWindowThread = new Thread(new ThreadStart(() =&gt;
        {
            SynchronizationContext.SetSynchronizationContext(
                new DispatcherSynchronizationContext(
                    Dispatcher.CurrentDispatcher));
            plotter = new PlotterWPF();
            plotter.Closed += (s, e) =&gt;
               Dispatcher.CurrentDispatcher.BeginInvokeShutdown(DispatcherPriority.Background);

            plotter.Show();
            plotter.init();

            System.Windows.Threading.Dispatcher.Run();
        }));

    newWindowThread.SetApartmentState(ApartmentState.STA);
    newWindowThread.Start();
</code></pre>

<p>This works and the plotter appears in screen, my proble is afterwards when I want to send stuff to the plotter I do this:</p>

<pre><code>public void debugFrame(Gtec2.Frame frame)
{
    plotter.Dispatcher.Invoke(() =&gt;
    {
        plotter.Plot(frame);
    });
}
</code></pre>

<p>and it fails because the plotter is null (in the <code>plotter.Dispatcher...</code> part)</p>

<p>I tried with Applicaiton.Current.Dispatcher but .. application.Current is null.</p>

<p>I also tried to create the plotter outside the thread but .. I cannot because is not STA. I think there should be a way to let the thing now my Dispatcher is the newWindowThread and the dispatcher.Invoke should happen there but .. I have no clue how to do it ..</p>

<p>Any suggestions?  </p>
",https://stackoverflow.com/questions/49670290/wpf-component-in-unit-testing,"['wpf', 'dispatcher']",49,TRUE,0,1
Unit testing Spring REST Controller,"<p>I have a Spring boot controller with a method like this:</p>

<pre><code>// CREATE
@RequestMapping(method=RequestMethod.POST, value=""/accounts"")
public ResponseEntity&lt;Account&gt; createAccount(@RequestBody Account account,
                                            @RequestHeader(value = ""Authorization"") String authorizationHeader,
                                             UriComponentsBuilder uriBuilder) {

    if (!account.getEmail().equalsIgnoreCase("""")) {
        account = accountService.createAccount(account);
        HttpHeaders headers = new HttpHeaders();

        System.out.println( ""Account is null = "" + (null == account)); //For debugging
        headers.setLocation(uriBuilder.path(""/accounts/{id}"").buildAndExpand(account.getId()).toUri());

        return new ResponseEntity&lt;&gt;(account, headers, HttpStatus.CREATED);
    }
    return new ResponseEntity&lt;&gt;(null, null, HttpStatus.BAD_REQUEST);
}
</code></pre>

<p>I'm trying to unit test it like this:</p>

<pre><code>@Test
public void givenValidAccount_whenCreateAccount_thenSuccessed() throws Exception {
    /// Arrange
    AccountService accountService = mock(AccountService.class);
    UriComponentsBuilder uriBuilder = mock(UriComponentsBuilder.class);
    AccountController accountController = new AccountController(accountService);
    Account account = new Account(""someone@domain.com"");

    /// Act
    ResponseEntity&lt;?&gt; createdAccount = accountController.createAccount(account, """", uriBuilder);

    /// Assert
    assertNotNull(createdAccount);
    //assertEquals(HttpStatus.CREATED, createdAccount.getStatusCode());
}
</code></pre>

<p>but the account is always null. Any idea why is that ?</p>
",https://stackoverflow.com/questions/50335846/unit-testing-spring-rest-controller,"['spring', 'junit']",255,TRUE,0,2
WrongTypeOfReturnValue error while unit testing,"<p>I migrated to Spring 2.X from 1.X and some errors occured. I can not handle this one.</p>

<p>(EDIT BELOW)</p>

<p>I tried both with <code>when...</code> and with <code>doReturn</code> , none of these works.</p>

<p>Method I want to unit-test:</p>

<pre><code>@Service
public class BookRentalService {

    private final AccountRepository accountRepository;
    private final BookRepository bookRepository;
    private final BookRentalsRepository bookRentalsRepository;

    @Autowired
    public BookRentalService(BookRepository bookRepository, BookRentalsRepository bookRentalsRepository, AccountRepository accountRepository) {
        this.bookRepository = bookRepository;
        this.bookRentalsRepository = bookRentalsRepository;
        this.accountRepository = accountRepository;
    }

public String rentBook(int accountID, int bookID) {
        Account account = accountRepository.findById(accountID)
                .orElseThrow(() -&gt; new IllegalArgumentException(""Account does not exist!""));

        if (account.getAmountOfCashToPay() == 0) {
            if (bookRepository.doesBookExistsWithGivenID(bookID)) {
                Book bookToRent = bookRepository.findById(bookID)
                        .orElseThrow(() -&gt; new IllegalArgumentException(""Book does not exist!""));

                if (bookToRent.isAvailable()) {
                    updateBookAvailabilityAndSaveToDb(bookToRent);
                    BookRentals preparedBookToRent = prepareBookToRent(accountID, bookToRent);
                    bookRentalsRepository.save(preparedBookToRent);
                } else {
                    throw new IllegalArgumentException(""Book is not available"");
                }
            }
        } else {
            throw new IllegalArgumentException(""Please go to paypenalty/accountID to settle the arrears, otherwise you can not rent more books!"");
        }

        return ""Book was rented"";
    }
</code></pre>

<p>Unit-test</p>

<pre><code>@RunWith(MockitoJUnitRunner.class)
public class BookRentalServiceTest {

@Mock
public BookRentalsRepository bookRentalsRepository;
@Mock
public BookRepository bookRepository;
@Mock
public AccountRepository userRepository;

@InjectMocks
public BookRentalService bookRentalService;



@Test(expected = IllegalArgumentException.class)
public void rentBookWhenAccountNotExists() {
    Book book = createDummyBook();
    Account user = createDummyUser();

    //when(bookRepository.doesBookExistsWithGivenID(book.getId())).thenReturn(true);
    //when(bookRepository.findById(book.getId()).orElse(null)).thenReturn(book);
    //when(userRepository.doesAccountExistsWithGivenID(user.getId())).thenReturn(false);

    doReturn(book).when(bookRepository).findById(book.getId()).orElse(null);
    doReturn(true).when(bookRepository).doesBookExistsWithGivenID(book.getId());
    doReturn(false).when(userRepository).doesAccountExistsWithGivenID(user.getId());
    String expected = ""Account does not exist"";

    assertEquals(expected, bookRentalService.rentBook(user.getId(), book.getId()));
}
}
</code></pre>

<p>Stacktrace:</p>

<pre><code>java.lang.Exception: Unexpected exception, expected&lt;java.lang.IllegalArgumentException&gt; but was&lt;org.mockito.exceptions.misusing.WrongTypeOfReturnValue&gt;

at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:28)
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.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
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: org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 
Book cannot be returned by findById()
findById() should return Optional
***
If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1. This exception *might* occur in wrongly written multi-threaded tests.
Please refer to Mockito FAQ on limitations of concurrency testing.
2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - 
- with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.

at bookrental.service.book.rentals.BookRentalServiceTest.rentBookWhenAccountNotExists(BookRentalServiceTest.java:71)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
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)
... 18 more
</code></pre>

<p><strong>//EDIT</strong>
With Timothy some help. Code looks like this.</p>

<pre><code>@Test(expected = IllegalArgumentException.class)
    public void rentBookWhenAccountNotExists() {
        Book book = createDummyBook();
        Account user = createDummyUser();

        when(bookRepository.doesBookExistsWithGivenID(book.getId())).thenReturn(true);
        when(bookRepository.findById(book.getId()).orElse(null)).thenReturn(book);
        when(userRepository.doesAccountExistsWithGivenID(user.getId())).thenReturn(false);

        //doReturn(book).when(bookRepository).findById(book.getId()).orElse(null);
        //doReturn(true).when(bookRepository).doesBookExistsWithGivenID(book.getId());
        // doReturn(false).when(userRepository).doesAccountExistsWithGivenID(user.getId());

        bookRentalService.rentBook(user.getId(), book.getId());
    }
</code></pre>

<p>and Stack:</p>

<pre><code>java.lang.Exception: Unexpected exception, expected&lt;java.lang.IllegalArgumentException&gt; but was&lt;org.mockito.exceptions.misusing.WrongTypeOfReturnValue&gt;

    at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:28)
    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.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
    at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
    at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
    at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
    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: org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 
Book cannot be returned by findById()
findById() should return Optional
***
If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1. This exception *might* occur in wrongly written multi-threaded tests.
   Please refer to Mockito FAQ on limitations of concurrency testing.
2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - 
   - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.

    at bookrental.service.book.rentals.BookRentalServiceTest.rentBookWhenBookNotExist(BookRentalServiceTest.java:53)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    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)
    ... 18 more
</code></pre>
",https://stackoverflow.com/questions/53938112/wrongtypeofreturnvalue-error-while-unit-testing,"['java', 'unit-testing', 'junit', 'mockito']",10793,TRUE,0,1
react unit testing - Enzmye shallow,"<p>I am trying to setup unit testing in React with Enzyme. When i run the command ""npm-test"" the test fails. 
The console terminal indicates that it failed because of shallow(). 
I have installed enzyme using this command npm install --save enzyme enzyme-adapter-react-16 react-test-renderer. Do anyone know how to solve this issue?</p>

<p>Below is the component</p>



<pre class=""lang-jsx prettyprint-override""><code>import React from 'react';

    class Login extends Component {
      render() {
        return &lt;div&gt;&lt;input
          onChange={(event) =&gt; {
             this.setState({input: event.target.value})}}
          type=""text"" /&gt;&lt;/div&gt;;
      }
    }

    export default Login;
</code></pre>

<p>This is the unit test i have written for the Component.</p>

<pre class=""lang-jsx prettyprint-override""><code>import React from 'react';
import { configure, shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

import Login from '../../../src/components/authentication/Login';
import Enzyme from 'enzyme';

configure({adapter: new Adapter()});

  it(""should create an entry in component state with the event value"", () =&gt; {
    // given
    const component = shallow(&lt;Login/&gt;);
    const form = component.find('input');
    // when
    form.props().onChange({target: {
      name: 'myName',
      value: 'myValue'
    }});
    // then
    expect(component.state('input')).toEqual('myValue');
  });
</code></pre>

<p>Thanks for the help.</p>
",https://stackoverflow.com/questions/50135524/react-unit-testing-enzmye-shallow,"['reactjs', 'jsx', 'enzyme']",200,FALSE,0,1
unit testing umbraco 7.12 controller,"<p>i've setup a unit test project for my umbraco 7.12 installation with Our.Umbraco.Community.Tests nuget installed as well as nunit, nunit 3 test adapter and NUnitV2Driver. i have a unit test where i'm inheriting from BaseRoutingTest (from the umbraco community tests nuget) that nunit just doesn't seem to want to run:</p>

<pre><code>using System;
using System.Globalization;
using System.Web.Routing;
using System.Web.Security;
using Moq;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.Dictionary;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Profiling;
using Umbraco.Tests.TestHelpers;
using Umbraco.Web;
using Umbraco.Web.Mvc;
using Umbraco.Web.Security;
using umbraco7._12test.Models;
using Assert = NUnit.Framework.Assert;

namespace UnitTestProject1
{
    [TestFixture]
    public class UnitTest1:BaseRoutingTest
    {
        protected UmbracoContext UmbracoContext { get; set; }
    protected UmbracoHelper UmbracoHelper { get; set; }

    protected IPublishedContent Content { get; set; }

    protected RouteData RouteData { get; set; }

    [SetUp]
    public override void Initialize()
    {

        base.Initialize();

        SettingsForTests.ConfigureSettings(SettingsForTests.GenerateMockSettings());

        this.RouteData = new RouteData();
        var routingContext = this.GetRoutingContext(
            ""http://localhost"",
            -1,
            this.RouteData,
            true,
            UmbracoConfig.For.UmbracoSettings());

        this.UmbracoContext = routingContext.UmbracoContext;

        this.Content = Mock.Of&lt;IPublishedContent&gt;();


        this.UmbracoContext.PublishedContentRequest = new Umbraco.Web.Routing.PublishedContentRequest(
            new Uri(""http://localhost""),
            routingContext,
            UmbracoConfig.For.UmbracoSettings().WebRouting,
            s =&gt; new string[0])
        {
            PublishedContent = this.Content,
            Culture = new CultureInfo(""en-GB"")
        };


        var routeDefinition = new RouteDefinition
        {
            PublishedContentRequest = this.UmbracoContext.PublishedContentRequest
        };

        this.RouteData.DataTokens.Add(Constants.Web.UmbracoRouteDefinitionDataToken, routeDefinition);

        this.UmbracoHelper = new UmbracoHelper(
          this.UmbracoContext,
          this.Content,
          Mock.Of&lt;ITypedPublishedContentQuery&gt;(),
          Mock.Of&lt;IDynamicPublishedContentQuery&gt;(),
          Mock.Of&lt;ITagQuery&gt;(),
          this.ApplicationContext.Services.DataTypeService,
          this.UmbracoContext.UrlProvider,
          new Mock&lt;ICultureDictionary&gt;().Object,
          Mock.Of&lt;IUmbracoComponentRenderer&gt;(),
          new MembershipHelper(this.UmbracoContext, Mock.Of&lt;MembershipProvider&gt;(), Mock.Of&lt;RoleProvider&gt;()));
    }

    [TearDown]
    public override void TearDown()
    {

        this.UmbracoHelper = null;
        this.UmbracoContext = null;
        this.Content = null;


        base.TearDown();
    }

    [Test]
    public void TestMethod1()
    {
        var apiController = new 
            umbraco7._12test.Controllers.ApiController(this.UmbracoContext,this.UmbracoHelper);
        var result = apiController.EditContact();
        var model = (ContactModel)result.Model;

        NUnit.Framework.Assert.IsNotNull(model.FirstName);
        NUnit.Framework.Assert.IsNotNull(model.LastName);
    }

    [Test]
    public void TestMethod2() {
        Assert.AreEqual(1,1);
    }
}
}
</code></pre>

<p>as soon as i inherit from BaseRoutingTest nunit will no longer run my tests, no errors just a message saying there are no tests found - </p>

<pre><code>[01/10/2018 14:56:32 Informational] NUnit couldn't find any tests in C:\project\umbraco7.12test\UnitTestProject1\bin\Debug\UnitTestProject1.dll
[01/10/2018 14:56:32 Informational] NUnit Adapter 3.10.0.21: Test execution complete
[01/10/2018 14:56:32 Warning] No test matches the given testcase filter `FullyQualifiedName=UnitTestProject1.UnitTest1.TestMethod1` in C:\project\umbraco7.12test\UnitTestProject1\bin\Debug\UnitTestProject1.dll
</code></pre>

<p>if i don't inherit from BaseRoutingTest nunit will run tests again. i need to inherit from BaseRoutingTest though, to setup the UmbracoContext and other things that need to be mocked.
does anybody know what the problem might be?</p>
",https://stackoverflow.com/questions/52592870/unit-testing-umbraco-7-12-controller,"['unit-testing', 'nunit', 'umbraco', 'umbraco7']",239,FALSE,0,1
Mocking Response Python Unit testing,"<p>I'm trying to create a mock response and want to set the response.text to some unicode chars. </p>

<p>Here's the code:</p>

<pre><code>class TestClass(TestCase):
    @mock.patch(self, mocked_get)
    def test_func(self):
        mocked_get.side_effect = self.mocked_get
        expected_result = [u'ssemsth']
        result = self.api.query(query_params)
        self.assertEqual(result, expected_result)

def mocked_get(self, *args, **kwargs):
    class MockResponse():
        def test_result():
           res = Response()
           res.message = u'semsmth'
           return res

    # some testcondition
    mock_response = MockResponse()
    if self.api.counter == 1:
         return mock_response.test_result()
</code></pre>

<p>In the result for the response, I'm getting <code>[u'']</code>, a list with empty unicode string. I want to get <code>[u'semsmth']</code></p>

<p>Any thoughts? I'm thinking I can't set the <code>res.message = u'semsth'</code> and just return that. How do I set this attribute for the Response() object i'm sending to the calling test_function</p>
",https://stackoverflow.com/questions/48587726/mocking-response-python-unit-testing,"['python', 'unit-testing', 'unicode', 'mocking']",44,FALSE,0,0
React Native Unit Testing (Jest),"<p>I'm a student, who new to jest unit testing, I found some tutorials related to the Jest and I have written some sample code to learn this. But unfortunately it did not work. I have tried several hours to solve this problem, but couldn't find a way. </p>

<p>Here is my code. </p>

<p><strong>This is my App.js</strong></p>

<pre><code>import React, { Component } from 'react';
import {Alert, Button, TextInput, View, Text, StyleSheet, KeyboardAvoidingView, TouchableOpacity
} from 'react-native'

export default class App extends Component {

  constructor(props) {
    super(props);

    this.state = {
      username: '',
      password: '',
    };
  }

  onLogin() {
    const { username, password } = this.state;

    Alert.alert('Credentials', `${username} + ${password}`);

  }

  render() {

    return (
      &lt;KeyboardAvoidingView style={styles.container}&gt;

        &lt;TextInput 
          value={this.state.username}
          onChangeText={(username) =&gt; this.setState({ username })}
          placeholder={'Username'}
          returnKeyType = ""next""
          keyboardType = ""email-address""
          autoCapitalize = ""none""
          autoCorrect = {false}
          onSubmitEditing = {()=&gt; this.passwordInput.focus()}
          style={styles.input}/&gt;

        &lt;TextInput
          value={this.state.password}
          onChangeText={(password) =&gt; this.setState({ password })}
          placeholder={'Password'}
          secureTextEntry={true}
          returnKeyType = ""go""
          style={styles.input}
          ref = {(input) =&gt; this.passwordInput = input}/&gt;

        {/* &lt;Button
          title={'Login'}
          style={styles.input}
          onPress={this.onLogin.bind(this)}/&gt; */}

          &lt;TouchableOpacity style={styles.button} onPress={this.onLogin.bind(this)}&gt;
            &lt;Text&gt;Login&lt;/Text&gt;
        &lt;/TouchableOpacity&gt;

      &lt;/KeyboardAvoidingView&gt;
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#ecf0f1',
  },
  input: {
    width: '90%',
    height: 44,
    padding: 10,
    borderWidth: 1,
    borderColor: 'black',
    marginBottom: 10,
    marginLeft: 10,
    marginRight: 10,
  },

  button: {
    width: '90%',
    height: 44,
    padding: 10,
    borderWidth: 0,
    alignItems: 'center',
    color: '#F5FCFF',
    marginBottom: 10,
    marginLeft: 10,
    marginRight: 10,
  },

});
</code></pre>

<p><strong>This is App.test.js</strong></p>

<pre><code>import React from 'react';
import Login from './App';
import { shallow } from 'enzyme';

describe('Login', function () {
  let component;
  let textInput;
  const defaultState = {text: ''};

  beforeEach(function () {
    component = shallow(&lt;Login /&gt;);
    textInput = component.find('TextInput');
  });

  it('has default state', function () {
    expect(component.state()).to.eql(defaultState);
  });

  it('renders input field with placeholder', function () {
    const expectedPlaceholder = 'Username';
    expect(textInput).to.have.length(1);
    expect(textInput.props().placeholder).to.eql(expectedPlaceholder);
  });

});
</code></pre>

<p><strong>package.json</strong></p>

<pre><code>{
  ""name"": ""AwsomProject"",
  ""version"": ""0.0.1"",
  ""private"": true,
  ""scripts"": {
    ""start"": ""node node_modules/react-native/local-cli/cli.js start"",
    ""test"": ""jest""
  },
  ""dependencies"": {
    ""react"": ""16.3.1"",
    ""react-native"": ""0.55.4"",
    ""yarn-install"": ""^1.0.0""
  },
  ""devDependencies"": {
    ""babel-core"": ""^6.26.3"",
    ""babel-jest"": ""23.0.1"",
    ""babel-preset-env"": ""^1.7.0"",
    ""babel-preset-react-native"": ""^4.0.0"",
    ""chai"": ""^4.1.2"",
    ""enzyme"": ""^3.3.0"",
    ""enzyme-adapter-react-15"": ""^1.0.5"",
    ""enzyme-adapter-react-16"": ""^1.1.1"",
    ""jest"": ""^23.1.0"",
    ""mocha"": ""^5.2.0"",
    ""react-native-mock"": ""^0.3.1"",
    ""react-test-renderer"": ""16.3.1""
  },
  ""jest"": {
    ""preset"": ""react-native""
  }
}
</code></pre>

<p>Thank you..</p>
",https://stackoverflow.com/questions/51015943/react-native-unit-testing-jest,"['unit-testing', 'react-native', 'jestjs']",1456,TRUE,0,1
Unit-Testing a WooCommerce Extension,"<p>I'm new to using PHPStorm along with PHPUnit, and the wordpress-develop package.</p>

<p>My projects rely on WooCommerce a lot.</p>

<p>Is it possible to add it as a dependency to the project?</p>

<p>At the moment I get this result:
<a href=""https://i.stack.imgur.com/lpDUT.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/lpDUT.png"" alt=""enter image description here""></a></p>

<p>And have the following setup:</p>

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

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

<p>Any help appreciated.</p>
",https://stackoverflow.com/questions/52089547/unit-testing-a-woocommerce-extension,"['wordpress', 'unit-testing', 'woocommerce', 'phpunit']",767,TRUE,0,1
Unit testing code with MvxTrace,"<p>I have this code:</p>

<pre class=""lang-cs prettyprint-override""><code>    public async Task DeleteListAsync(Models.List list)
    {
        var userList = (await _userListRepository.GetAllAsync())
            .Where(ul =&gt; ul.ListId.Equals(list.Id, StringComparison.CurrentCultureIgnoreCase))
            .FirstOrDefault();

        if (userList != null)
            await _userListRepository.DeleteAsync(userList);
        else
            MvxTrace.Error(string.Format(""Unable to find UserList entry for List {0}."", list.Id));

        await _listRepository.DeleteAsync(list);
    }
</code></pre>

<p>The question I have is a s follows - how do I unit test this code with a call to MvxTrace which is part of MvvmCross framework.  I know that I can wrap a call into MvxTrace into my own interface base method and provide own implementation for unit test purposes but is there a better/different way to provide a mock implementation for MvxTrace without the effort of wrapping it?</p>
",https://stackoverflow.com/questions/48992941/unit-testing-code-with-mvxtrace,"['c#', 'unit-testing', 'xamarin', 'xamarin.android', 'mvvmcross']",102,TRUE,1,1
unit testing: static create method,"<p>I want to start writing some unit tests for a buffer class and I`m struggling a bit with the static create method. </p>

<pre><code>class MyBuffer
{
public: 
  static MyBuffer* create(int32 bufSize)
  {
     if(!bufSize)
       return nullptr; 

     char* internalBuf = (char*)malloc(bufSize);
     if(nullptr == internalBuf) return nullptr; 

     return new MyBuffer(internalBuf, bufSize);
  }

 public bool write(void* data, int32 dataSize) {...}

private:
 MyBuffer(char* buf, int32 size) : internalBuf(buf), size(bufSize) {}

 char* internalBuf = nullptr; 
 int32 bufSize = 0;
};

//just dummy code
TEST(MyBuffer bufferWithZeroSize)
{ 
   auto buf = MyBuffer::create(0);
   ASSERT_True(nullptr == buf);
}

TEST(MyBuffer writeDataToBuffer)
{
  //arrange
  auto buf = MyBuffer::create(50); 
  ASSERT_NotNull(buf); //is this call needed

  //act
  buf-&gt;write(...); 

  //assert 
}
</code></pre>

<p>Verifying the MyBuffer creation process seems to be ok. </p>

<p>In my 2nd test, is it ok to assume that the creation process of the MyBuffer was successfull? Otherwise I have to check it in the ""act"" part of the unit test. This sounds not so reasonable to me because I want to check only one thing per unit test. On the other side, I know the malloc call can fail.   </p>

<p>How do you test objects with a static create method? Are there any useful test strategies or is it recommend to refactor such objects? I mainly use the static create methods in order to avoid that the caller of the object forget to initialize the object correctly. Therefore it sounds to me a valid approach.  </p>
",https://stackoverflow.com/questions/52235035/unit-testing-static-create-method,"['c++', 'unit-testing']",56,TRUE,0,2
RSpec Unit Testing controller method,"<p>am relatively new with rspec and testing,am trying to write a test for this code</p>

<pre><code>@assessments = Assessment.where(assigned_user_id: current_user.id)
</code></pre>

<p>here is what i have tried so far,but am not sure if it's the right way,i was told controller spec is not advisable,hence i am trying to implement it using unit test.</p>

<p>spec_file</p>

<pre><code>    require 'rails_helper'

# Test suite for the assessment model
RSpec.describe Assessment, type: :model do
  let(:admin) { User.new(email: 'rockcoolsaint@example.com', password: 'password', password_confirmation: 'password', role: :admin) }
  let(:behavioral_specialist) { User.new(email: 'bs@example.com', password: 'password', password_confirmation: 'password', role: :behavioral_specialist) }
  let(:behavioral_specialist_2) { User.new(email: 'bs2@example.com', password: 'password', password_confirmation: 'password', role: :behavioral_specialist) }
  let(:bs_user_assessments) { Assessment.where(assigned_user_id: behavioral_specialist.id) }

  describe 'Validations' do
    it { should validate_presence_of(:title) }

    it 'is valid with all attributes' do
      expect(build(:assessment, user: admin, assigned_user: behavioral_specialist)).to be_valid
    end

    it 'is valid if assigned_user_id equals behavioral_specialist_id' do
      bs_user_assessments.each do |assessment|
        expect(assessment.assigned_user_id).to eq(behavioral_specialist.id)  
      end
    end

    it 'is valid if assigned_user_id does not equal behavioral_specialist_2_id' do
      bs_user_assessments.each do |assessment|
        expect(assessment.assigned_user_id).to_not eq(behavioral_specialist_2.id)  
      end
    end
  end
</code></pre>
",https://stackoverflow.com/questions/53670331/rspec-unit-testing-controller-method,"['ruby-on-rails', 'testing', 'rspec']",276,FALSE,0,0
Angular Hybrid application unit testing,"<p>How do I configure karma/test.ts/angular.json so it can pull in the *.spec.js files as well? I am using angluar-cli and do not want to use webpack in my project.</p>

<p>In my test.ts I am trying something like this:</p>

<pre><code>const tsContext = require.context('./', true, /\.spec\.ts$/);
const jsContext = require.context('../../lz-consumer-app/widgets/', true, /\.spec\.js$/);
// And load the modules.
tsContext.keys().concat(jsContext.keys()).map(tsContext);
</code></pre>
",https://stackoverflow.com/questions/52204412/angular-hybrid-application-unit-testing,"['angular', 'jasmine', 'angular-cli', 'karma-runner']",307,FALSE,0,0
tornado_json unit testing async methods,"<p>I'm trying to set up a unit test for a tornado_json web app.
I'm trying to test a post handler, but I'm failing miserably as the <code>fetch</code> method seems to return an _asyncio.Future object, which never seems to complete/have a result set. I've tried to post a summary of the code, at the moment I'm just returning ['test'] item.
I've looked at <a href=""https://github.com/tornadoweb/tornado/issues/1154"" rel=""nofollow noreferrer"">https://github.com/tornadoweb/tornado/issues/1154</a>, as well as the tornado documentation. It sounds like I need to self.stop, or self.wait() to complete the task, but I haven't worked out how to get this to work, or if that is the solution.
Any help would be greatly appreciated.</p>

<p><code>
    @schema.validate(
        input_schema={
            ""type"": ""object"",
            ""properties"": {
                ""path"": {""type"": ""string""}
            },
            ""required"": [""path""]
        },
        output_schema={
            ""type"": ""array"",
            ""items"": {
                ""properties"": {""type"": ""string""}
            }
        }
    )
    @coroutine
    def post(self):
        attributes = dict(self.body)
        path = attributes[""path""]
        response = [""test""]
        return response
</code></p>

<p><code>
    @gen_test
    def test_POST_method(self):<br>
        body = json.dumps({'path': 'bin'})
        self.http_client.fetch(self.get_url('/api/listmyfiles'),
            method=""POST"",
            body=body
        )
        response = self.wait()
        print(response.result()))
</code></p>

<p>The error I get is:
<code>asyncio.base_futures.InvalidStateError: Result is not set.</code></p>
",https://stackoverflow.com/questions/53299630/tornado-json-unit-testing-async-methods,"['python-3.x', 'tornado', 'pytest', 'pytest-asyncio']",134,TRUE,0,1
Jasmine Unit Testing on extjs,"<p>I would like to ask for some advice on how do you write jasmine unit test for extjs store? Stores that connects to the database to retrieve data. Do people write such unit test?</p>
",https://stackoverflow.com/questions/51890969/jasmine-unit-testing-on-extjs,"['jasmine', 'extjs4.2']",410,FALSE,0,1
Unit Testing for the following :,"<p>Tring to set up a unit testing for the following code, but I keep getting this:  Comparing two different types of values. Expected string but received undefined. as an error</p>

<pre><code> Test :


     import {prepadSigned} from './utils';

  describe('prepadSigned', () =&gt; {test('should prepend `00` to the input      &lt;', () =&gt; {
  const str = '-10';
  const actual = prepadSigned(str);
  const expected = '00-10';
    expect(actual).toEqual(expected);
    })
</code></pre>

<p>Code: </p>

<pre><code>function prepadSigned(hexStr) {
  const msb = hexStr[0];
  if (msb &lt; '0' || msb &gt; '7') {
    return `00${hexStr}`;
  }
  return hexStr;
} 
</code></pre>

<p>I expect a unit test to pass with some input/output. 
I keep getting the following :</p>

<pre><code>expect(received).toEqual(expected)

Expected value to equal:
  ""00-10""
Received:
  undefined
</code></pre>
",https://stackoverflow.com/questions/53935426/unit-testing-for-the-following,"['reactjs', 'unit-testing', 'jestjs']",38,FALSE,0,1
How JavaScript Unit testing works,"<p>Consider the following snippet of my javascript function -</p>

<pre><code>firstJs.prototype.SetSum=function(a,b){
    var htmlToBind=""&lt;div&gt;""+(a+b)+""&lt;/div&gt;"";
    $('#setSum').html(htmlToBind);
};
</code></pre>

<p>Here <code>setSum</code> is a elementID in DOM.I would like to understand how will this function pass the unit testing done by Jasmine or Jest as and when the unit testing would run it will not find the 'setSum' in DOM hence fail the test case.I am a rookie in test cases</p>
",https://stackoverflow.com/questions/48780313/how-javascript-unit-testing-works,"['javascript', 'jquery', 'unit-testing', 'jasmine', 'jestjs']",97,TRUE,0,2
Unit testing two C# lists,"<p>I have a method which takes in a list collection of objects. The idea is the method will check a specific field <code>CoverArt</code> in each of the objects passed into it and if the <code>CoverArt</code> property is null, an empty string, or an empty space, it will set it to a default value. If the <code>CoverArt</code> property is not null, empty string, or a white space, it just returns whatever string is in there already.</p>

<pre><code>//checks a list of stories for cover art and sets cover art to a default if it is null
   public string CheckIfCoverArtIsNullForStoryList(List&lt;Story&gt; stories)
   {
    foreach (var story in stories)
    {
        if (story.CoverArt == null || story.CoverArt == """" || story.CoverArt == "" "")
    {
    return story.CoverArt = ""default-book.png"";
   }
   return story.CoverArt;
}

            return """";
        }
</code></pre>

<p>What I'm trying to do is create a unit test that will test whether or not this method even works but I'm having difficult trying to compare two lists. What is wrong with my code?</p>

<pre><code>[TestMethod]
        [Description(""Tests list of stories for null cover art"")]
        public void TestingStoryListCoverArtMethodWithValidInput()
        {
            List&lt;Story&gt; StoryListActual = new List&lt;Story&gt;()
            {
                new Story()
                {
                    CoverArt = ""Lord of the Rings.png""
                },
                new Story()
                {
                    CoverArt = ""Johnny Appleseed.jpeg""
                },
                new Story()
                {
                    CoverArt = ""The Great Gatsby.jpg""
                },
                new Story()
                {
                    CoverArt = ""Happy Gilmore.gif""
                }
            };

            List&lt;Story&gt; CoverArtExpected = new List&lt;Story&gt;()
            {
                new Story()
                {
                    CoverArt = ""Lord of the Rings.png""
                },
                new Story()
                {
                    CoverArt = ""Johnny Appleseed.jpeg""
                },
                new Story()
                {
                    CoverArt = ""The Great Gatsby.jpg""
                },
                new Story()
                {
                    CoverArt = ""Happy Gilmore.gif""
                }
            };

            helper.CheckIfCoverArtIsNullForStoryList(StoryListActual);

            for (var i = 0; i &lt; StoryListActual.Count; i++)
            {
                for (var j = 0; j &lt; CoverArtExpected.Count; j++)
                {
                    Assert.AreEqual(StoryListActual[i].CoverArt, CoverArtExpected[j].CoverArt);
                }
            }
        }
</code></pre>

<p>My unit testing is failing with this message.</p>

<p><a href=""https://i.stack.imgur.com/OsE1E.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/OsE1E.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/52123660/unit-testing-two-c-lists,"['c#', 'unit-testing']",72,FALSE,0,0
Laravel 5.5 api unit testing,"<p>I have issue on laravel api unit testing, these are my configs and simple code, but getting ""Expected status code 201 but received 500"". But with postman everything is ok, why??? please help <a href=""https://i.stack.imgur.com/wjPba.png"" rel=""nofollow noreferrer"">config1</a> <a href=""https://i.stack.imgur.com/gw4Vz.png"" rel=""nofollow noreferrer"">config2</a> <a href=""https://i.stack.imgur.com/1q6Yx.png"" rel=""nofollow noreferrer"">test</a> <a href=""https://i.stack.imgur.com/xWjF0.png"" rel=""nofollow noreferrer"">controller</a> <a href=""https://i.stack.imgur.com/j0Y1P.png"" rel=""nofollow noreferrer"">result</a></p>

<p>There is a trait in RegisterController called RegistersUsers and in it is register() method  </p>

<p><code>Route::post('register', 'Auth\RegisterController@register');</code>  </p>

<p>it calls a register() method and the register method calls registered()</p>

<p><strong><em>config 1 - config/database.php</em></strong></p>

<pre><code>   'connections' =&gt; [

    'sqlite' =&gt; [
        'driver' =&gt; 'sqlite',
        'database' =&gt; ':memory:',
        'prefix' =&gt; '',
    ],
</code></pre>

<p><strong><em>config 2 - phpunit.xml</em></strong></p>

<pre><code>   &lt;php&gt;
    &lt;env name=""APP_ENV"" value=""testing""/&gt;
    &lt;env name=""CACHE_DRIVER"" value=""array""/&gt;
    &lt;env name=""SESSION_DRIVER"" value=""array""/&gt;
    &lt;env name=""QUEUE_DRIVER"" value=""sync""/&gt;
    &lt;env name=""DB_CONNECTION"" value=""sqlite""/&gt;
&lt;/php&gt;
</code></pre>

<p><strong><em>test</em></strong></p>

<pre><code>public function testRegisterSuccessfully()
{
    $register = [
        'name' =&gt; 'UserTest',
        'email' =&gt; 'user2@test.com',
        'password' =&gt; 'testpass',
        'password_confirmation' =&gt; 'testpass'
    ];

    $this-&gt;json('POST', 'api/register', $register)
        -&gt;assertStatus(201)
        -&gt;assertJsonStructure([
            'token',
            'user' =&gt; [
                'id',
                'name',
                'email',
                'created_at',
                'updated_at'
            ]
        ]);
 }
</code></pre>

<p><strong><em>controller method</em></strong></p>

<pre><code>public function registered(Request $request)
{
    $user = $this-&gt;guard()-&gt;user();
    $success['token'] = $user-&gt;createToken('WAI')-&gt;accessToken;
    $success['user'] = $user;
    return response()-&gt;json($success, 201);
}
</code></pre>

<p><strong><em>result</em></strong></p>

<pre><code> developer@developer-v3:/var/www/WAI$ composer test
 &gt; vendor/bin/phpunit
 PHPUnit 6.5.8 by Sebastian Bergmann and contributors.

  ..F..                                                               5 /   5 (100%)

Time: 3.78 seconds, Memory: 20.00MB

 There was 1 failure:

1) Tests\Feature\Auth\RegisterControllerTest::testRegisterSuccessfully
Expected status code 201 but received 500.
Failed asserting that false is true.

/var/www/WAI/vendor/laravel/framework/src/Illuminate/Foundation/Testing         /TestResponse.php:78
/var/www/WAI/tests/Feature/Auth/RegisterControllerTest.php:26

FAILURES!
Tests: 5, Assertions: 6, Failures: 1.
Script vendor/bin/phpunit handling the test event returned with error code   1
</code></pre>
",https://stackoverflow.com/questions/50212918/laravel-5-5-api-unit-testing,"['laravel', 'api', 'unit-testing']",1134,TRUE,-1,3
States undefined in unit testing,"<p>I'm trying a very simple shallow test for a component:</p>

<pre><code>it('renders without crashing', () =&gt; {

shallow(&lt;SampleComponent /&gt;);
});
</code></pre>

<p>In my sample component, I did a setState :</p>

<pre><code> this.setState({myCurrentState: ""InSample""});
</code></pre>

<p>Now somewhere in my return, I used that to output an element, say:</p>

<pre><code>return ( &lt;h1&gt; this.state.myCurrentState &lt;/h1&gt;)
</code></pre>

<p>When I try the above test, I get</p>

<pre><code> TypeError: Cannot read property of undefined.
</code></pre>

<p>I know that I can pass in props to shallow, but I can't seem to figure how to do it with states. Is there a better way of doing it? Sorry I'm new to React and unit testing. thanks</p>
",https://stackoverflow.com/questions/49091888/states-undefined-in-unit-testing,"['reactjs', 'enzyme']",2724,TRUE,0,2
Unit Testing Error: py.test WinError5,"<p>I am trying to do unit testing in Python (intermediate skill level). I've had this error for the past couple of months, and after many hours of searching for a solution on Google, I have not been able to fix this. The issue is that I am being denied permission to certain folders on my computer despite running conda as an admin and being the listed owner of each file.</p>

<pre><code>(base) C:\Users\danie&gt;py.test
============================= test session starts =============================
platform win32 -- Python 3.6.5, pytest-3.5.1, py-1.5.3, pluggy-0.7.1
rootdir: C:\Users\danie, inifile:
plugins: remotedata-0.2.1, openfiles-0.3.0, doctestplus-0.1.3, arraydiff-0.2
collected 0 items / 1 errors

=================================== ERRORS ====================================
______________________________ ERROR collecting  ______________________________
AppData\Local\Continuum\anaconda3\lib\site-packages\py\_error.py:66: in checked_call
    return func(*args, **kwargs)
E   PermissionError: [WinError 5] Access is denied: 'C:\\Users\\danie\\AppData\\Local\\Application Data'

During handling of the above exception, another exception occurred:
AppData\Local\Continuum\anaconda3\lib\site-packages\py\_path\common.py:377: in visit
    for x in Visitor(fil, rec, ignore, bf, sort).gen(self):
AppData\Local\Continuum\anaconda3\lib\site-packages\py\_path\common.py:429: in gen
    for p in self.gen(subdir):
AppData\Local\Continuum\anaconda3\lib\site-packages\py\_path\common.py:429: in gen
    for p in self.gen(subdir):
AppData\Local\Continuum\anaconda3\lib\site-packages\py\_path\common.py:429: in gen
    for p in self.gen(subdir):
AppData\Local\Continuum\anaconda3\lib\site-packages\py\_path\common.py:414: in gen
    entries = path.listdir()
AppData\Local\Continuum\anaconda3\lib\site-packages\py\_path\local.py:387: in listdir
    names = py.error.checked_call(os.listdir, self.strpath)
AppData\Local\Continuum\anaconda3\lib\site-packages\py\_error.py:86: in checked_call
    raise cls(""%s%r"" % (func.__name__, args))
E   py.error.EBUSY: [Resource device]: listdir('C:\\Users\\danie\\AppData\\Local\\Application Data',)
!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!
=========================== 1 error in 0.20 seconds ===========================
</code></pre>
",https://stackoverflow.com/questions/51885525/unit-testing-error-py-test-winerror5,"['python', 'unit-testing', 'pytest']",300,FALSE,0,0
Django unit testing middleware error,"<p>This is my middleware -</p>

<pre><code>class HeadersControlMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        response = self.get_response(request)

        response['Cache-Control'] = ""no-cache""
        # Code to be executed for each request/response after
        # the view is called.

        return response
</code></pre>

<p>and this is my unit test -</p>

<pre><code>class TestHeadersControlMiddleware(MyAPITestCase):

    def dummy_middleware(self):
        response = Response()
        response.status_code = 200
        response.json = {""key1"": ""value1""}

        return response

    def test_cache_control_header_is_added(self):
        self.middleware = HeadersControlMiddleware(self.dummy_middleware())
        self.request = RequestFactory()
        self.request.META = {
            ""REQUEST_METHOD"": ""POST"",
            ""HTTP_APP_VERSION"": ""1.0.0"",
            ""HTTP_USER_AGENT"": ""AUTOMATED TEST""
        }
        self.request.path = '/testURL/'
        self.request.session = {}

        response = self.middleware(self.request)

        print(str(response['Cache-Control']))
</code></pre>

<p>When running the test I'm getting the following error:</p>

<pre><code>File "".../tests/test_headers_control_middleware.py"", line 56, in test_cache_control_header_is_added
response = self.middleware(self.request)
File ""..../api/headers_control_middleware.py"", line 10, in __call__
response = self.get_response(request)
TypeError: 'Response' object is not callable
</code></pre>

<p>Any idea?</p>

<p>EDIT - 
Apparently, I returned 'Response' in 'dummy_middleware' instead of 'response' (thanks to @szymon for noticing). So I fixed that and updated the current error and question.</p>
",https://stackoverflow.com/questions/49529162/django-unit-testing-middleware-error,"['django', 'unit-testing', 'middleware']",1317,TRUE,0,1
Unit-testing secondary routing controller,"<p>Currently i'm developing a simple pizza-webshop for a school assignment. I'm experienced in Java &amp; C# but AngularJS is new to me. </p>

<p>I created a single page application with 1 main order controller (index contains an overview of the total order) and another menu controller to load the .JSON menu into a partial view. </p>

<p>The order controller is set in the index as follows;</p>

<p><strong>index.html</strong></p>

<pre><code>    &lt;html ng-app=""pizzaApp"" ng-controller=""orderCtrl""&gt;
&lt;head&gt;
    &lt;link rel=""stylesheet"" href=""CSS/style.css""/&gt;
    &lt;script src=""https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js""&gt;&lt;/script&gt;
    &lt;script src=""https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.min.js""&gt;&lt;/script&gt;
    &lt;script src=""Apps/pizzaApp.js""&gt;&lt;/script&gt;
    &lt;script src=""Controllers/menuCtrl.js""&gt;&lt;/script&gt;
    &lt;script src=""Controllers/orderCtrl.js""&gt;&lt;/script&gt;
&lt;/head&gt;
</code></pre>

<p>and the menu controller is set in the app's routing as follows;</p>

<p><strong>pizzaApp.js</strong></p>

<pre><code>var app = angular.module(""pizzaApp"", [""ngRoute""]);

    // View routing
    app.config(function ($routeProvider) {
        $routeProvider
            .when('/', {
                templateUrl : 'Views/main.html'
            })
            .when('/pizzas', {
                templateUrl: 'Views/pizzas.html',
                controller: 'menuCtrl'
            })
            .when('/pizzas/:param', {
                templateUrl: 'Views/pizzaInfo.html',
                controller: 'menuCtrl'
            })
            .when('/orders', {
                templateUrl: 'Views/orders.html',
            })
    });
</code></pre>

<p>I managed to write a working (and passing) unit-test for the order controller as follows;</p>

<p><strong>orderCtrl.spec.js</strong></p>

<pre><code>describe('Controllers', function() {
    beforeEach(module('pizzaApp'));

    var $controller;

    beforeEach(inject(function(_$controller_){
      $controller = _$controller_;
    }));

    describe('orderCtrl Test', function() {
      var $scope, controller;

      beforeEach(function() {
        $scope = {};
        controller = $controller('orderCtrl', { $scope: $scope });
      });

      it('orderCtrl.addPizza methode', function() {
         //code...
      });

      it('orderCtrl.clearList methode', function() {
         //code...
      });

    });
  });
</code></pre>

<p>However, if i try to write a simple unit test for the menu controller in the exact same way, it says the scope/controller is undefined and/or gives me back nulls resulting in the following error message;</p>

<pre><code>Expected null to equal [  ].
        at UserContext.&lt;anonymous&gt; (C:/Users/Ken/Git repositories/angular-phonecat/app/practicum/Unit_tests/menuCtrl.spec.js:88:34)
    Error: Unexpected request: GET Models/menu.json
    Expected GET ../Models/menu.json
</code></pre>

<p><strong>menuCtrl.spec.js</strong></p>

<pre><code>describe('menuCtrl Tests', function() {
    beforeEach(module('pizzaApp'));

    var $controller, $httpBackend;

    beforeEach(inject(function(_$controller_, _$httpBackend_){
        $controller = _$controller_;
        $httpBackend = _$httpBackend_;
        $httpBackend.expectGET(""../Models/menu.json"").respond([{name: 'Margaritha'}, {name: 'Shoarma'}, {name: 'Supreme'}]);

    }));

    describe('menuCtrl Tests', function() {
      var $scope, controller;

        beforeEach(function() {
            $scope = {};
            controller = $controller('menuCtrl', { $scope: $scope});
        });

        it('should create a `menu` property with 3 pizzas with `$httpBackend`', function() {
            jasmine.addCustomEqualityTester(angular.equals);

             expect($scope.Menu).toEqual([]);

             $httpBackend.flush();
             expect($scope.Menu).toEqual([{name: 'Margaritha'}, {name: 'Shoarma'}, {name: 'Supreme'}]);
           });



    });
  });
</code></pre>

<p><strong>menuCtrl.js</strong></p>

<pre><code>app.controller('menuCtrl', function ($scope, $http, $routeParams) {

    $scope.param = $routeParams.param;  //URL Parameter (.../index.html#!/pizzas/#)
    $scope.test=""123"";

    //Menu array inladen vanuit .JSON
    $http.get('Models/menu.json')
        .then(function (menu) {
            $scope.Menu = menu.data;

        });

});
</code></pre>

<p>I have read the f*cking manual, searched google for many-many hours, read all similar questions on stack and i have been trying to solve this for about 2 weeks total, all to no avail...</p>

<p>I have tried changing the unit tests, controllers, front-end, routing, dependency injections, using controller instead of scope, etc. etc. ... and i am COMPLETELY stuck! </p>
",https://stackoverflow.com/questions/53350971/unit-testing-secondary-routing-controller,"['angularjs', 'unit-testing', 'controller', 'karma-runner', 'angular-routing']",39,TRUE,0,1
Unit testing with Jest without module.exports,"<p>I have a script that holds a single <code>const</code> variable which holds all of my logic, kind-of like Moment.js.<br>
I want to test out functions that go out with this script with Jest.  </p>

<p>I can't use <code>module.exports</code> since it will not work when I publish my script.<br>
And if I can't use <code>module.exports</code> I can't use <code>require</code>.</p>

<p>But I still want to run unit tests on my script.<br>
I have tried using <code>import</code> with no luck.  </p>

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

<pre><code>import 'src/library.js';

test('Something', () =&gt; {
    expect(library.add(1,2)).toBe(3);
});
</code></pre>

<p>And this is my library:  </p>

<pre><code>const library = () =&gt; {
    return {
        add : (num1,num2) =&gt; num1 + num2,
        subtract : (num1,num2) =&gt; num1 - num2
    }
}
</code></pre>
",https://stackoverflow.com/questions/52506163/unit-testing-with-jest-without-module-exports,"['javascript', 'node.js', 'unit-testing', 'npm', 'jestjs']",2728,TRUE,8,2
"Unit Testing, overload output operator","<p>I want to make a unit test, basically i have a class Pawn and <code>&lt;&lt;</code> return the color of my pawn. The colors of my pawn are retained in a enum.</p>

<pre><code>TEST_METHOD(outputOperator)
 {
   Pawn pawn(Pawn::Color::Blue);

   std::stringstream out;
   out &lt;&lt; pawn.GetColor();
   Assert::IsTrue(Pawn::Color::Blue == out);
}
</code></pre>

<p>The problem is that my compiler said that no operator <code>==</code> matches these operands. What can I do ?
PS: This is my second unit test</p>
",https://stackoverflow.com/questions/53645652/unit-testing-overload-output-operator,"['unit-testing', 'visual-c++', 'operator-overloading', 'c++17']",226,FALSE,0,0
Not Unit Testing external code,"<p>It is said that if a class uses an <strong>external</strong> resource then that <strong>external resource</strong> call is not be tested. So, if there is <strong>class</strong> like below;</p>

<pre><code>public interface IVideo
{
string VideoName();        
}

public class Video : IVideo
{
    public string VideoName()
    {
         var obj = new VideoReader(""videoPath.avi"").GetName();

         ////some other code
    }
}
</code></pre>

<p>In order to unit test, we would create a fake class which would inherit from IVideo and implement like below,</p>

<pre><code>public string VideoName()
        {
            return """";
        }
</code></pre>

<p>My question is why don't we test <strong>actual code</strong> which calls <strong>actual Video class</strong> object?</p>
",https://stackoverflow.com/questions/51866410/not-unit-testing-external-code,"['unit-testing', 'nunit']",21,TRUE,-1,1
PHP unit testing recaptcha v2,"<p>I am implemented invisible recaptcha on my site, the users submits the form, I get a response code and then POST that to recaptchas endpoint to verify the user via cURL.</p>

<p>What I am wanting to do now is create some functional tests for so that I can test the success and error responses. Can anyone point me in the right direction of either creating fake calls/responses from recaptcha or using some kind of test service if one exists?</p>
",https://stackoverflow.com/questions/52083329/php-unit-testing-recaptcha-v2,"['php', 'unit-testing', 'phpunit', 'recaptcha', 'invisible-recaptcha']",243,FALSE,0,0
Unit testing Angular Jasmine Karma,"<p>I'm learning Unit testing and I've</p>

<pre><code>   @Input() showSearchTab: Boolean = false;
     @Input() currentTab: string = null;

     ngOnInit(): void {
        if (this.showSearchTab) {
          this.currentTab = 'search';
        }
      }
</code></pre>

<p>This is the unit test: </p>

<pre><code>describe('ngOnInit()', () =&gt; { 
        it('should set all the defaults', () =&gt; {
          specManager.component.ngOnInit();
          expect(specManager.component.currentTab).toBe('search');
        });
    });
</code></pre>

<p>I get an error expected null to be 'search'</p>
",https://stackoverflow.com/questions/53321810/unit-testing-angular-jasmine-karma,"['angular', 'jasmine', 'karma-runner']",153,TRUE,-1,2
Angular unit testing a service,"<p>I am struggling to test a simple service. I cannot find out what exactly to test.</p>

<pre><code>@Injectable()
export class MyService {
    constructor(
        private firstService: FirstService,
        private secondService: SecondService) {
    }

    deals(body: myModel): Observable&lt;any&gt; {
        let url = this.secondService.makeUrl('/api/deals');
        return this.firstService.post(url, body);
    }

}
</code></pre>

<p>myModel is like:</p>

<pre><code>export class myModel {
    meta: otherModel;
    data: any;
}  
</code></pre>

<p><code>this.secondService.makeUrl()</code> returns a <code>url</code> and <code>this.firstService.post()</code> is actually an <code>http.post</code> request. </p>

<p>The problem is I do not know how to test <code>deals</code> method. I have mocked <code>FirstService</code> and <code>SecondService</code> e.g. </p>

<pre><code>mockFirstService = jasmine.createSpyObj([""post""]);
</code></pre>

<p>everything is okay inside <code>beforeEach (TestBed.configureTestingModule etc)</code>, but I do not know what exactly to add inside </p>

<pre><code> it(...)
</code></pre>

<p>What exactly do I have to test and how?</p>
",https://stackoverflow.com/questions/53102348/angular-unit-testing-a-service,['angular'],49,TRUE,0,1
Unit testing mapstruct with &#39;uses&#39;,"<p>Is there a standard approach for unit testing mappers when using spring boot? i.e. getting dependencies etc.</p>

<p>I'm currently doing something like this:</p>

<pre><code>@SpringBootTest(classes = {VehicleMapper.class, VehicleMapperImpl.class,
  VehicleAttributesMapper.class, VehicleAttributesMapperImpl.class})
@RunWith(SpringRunner.class)
public class VehicleMapperTest {

@Autowired
private VehicleMapper vehicleMapper;
</code></pre>

<p>VehicleMapper has a <strong>uses</strong>:</p>

<p><code>@Mapper(componentModel = ""spring"", uses = VehicleAttributesMapper.class)</code></p>

<p>However when I run my unit test the <code>VehicleAttributesMapper</code> does not appear to get invoked? (the types match i.e. source/target)</p>

<p>TIA</p>
",https://stackoverflow.com/questions/52663250/unit-testing-mapstruct-with-uses,"['spring-boot', 'mapstruct']",839,TRUE,0,1
How to Unit Testing RuntimeType,"<pre><code>[Test]
// arrange 
// ...
// act
var result = (Car) service.GetCar(req);

// assert
Assert.AreEqual(result, typeof(Car));  
</code></pre>

<p>But I'm getting following error</p>

<pre><code>Expected: &lt;Models.Car&gt; (Car)    
But was:  &lt;Models.Car&gt; (RuntimeType)
</code></pre>

<p>I tried to change assert to use <code>Is.InstanceOf</code>:   </p>

<pre><code>Assert.AreEqual(result, Is.InstanceOf&lt;Car&gt;());
</code></pre>

<p>But I'm still getting error, this time </p>

<pre><code>Expected: &lt;Models.Car&gt;
But was:  &lt;&lt;instanceof Models.Car&gt;&gt;
</code></pre>
",https://stackoverflow.com/questions/52834742/how-to-unit-testing-runtimetype,"['c#', '.net', 'unit-testing']",159,TRUE,0,2
Unit testing a Threaded Application,"<p>I am having thoughts on how do I write a test case for this using mockito.</p>

<p>Example, part of my logic in my main thread is to create a thread that does 3 things.
Please see my annotated code below.</p>

<p>Now the RequestThread can be spawn many times depending on the number of inputs coming from the main program.</p>

<pre><code>public class MainThreads {
    public static void main(String[] args) {
        RequestThread rt = new RequestThread(""sample"");
        rt.start();

        //RequestThread another = new RequestThread(""sample-2"");
        //another.start();

        //RequestThread newThread = new RequestThread(""sample-3"");
        //newThread.start();
    }

    public static class RequestThread implements Runnable{
        private final String request;

        public RequestThread(String request) {
            this.request = request;
        }

        @Override
        public void run() {
            //1. Instantiate a service passing the required request parameter
            MyDataWebService service = new MyDataWebService(request);

            //2. Get the returned data
            List&lt;String&gt; dataList = service.requestData();

            //3. Write to file
            Path file = Paths.get(""/someDir/"" + request);
            Files.write(file, dataList, Charset.forName(""UTF-8""));
        }

    }
}
</code></pre>

<p>My issue is this, I could not figure out how to properly write a JUnit/Mockito test for a threaded class.
I am not that well verse on Mockito and JUnit in general so I am looking for a way to unit test
a threaded application.</p>

<p>Can somebody guide me on how can I unit test such thing?</p>
",https://stackoverflow.com/questions/51510823/unit-testing-a-threaded-application,"['java', 'junit', 'mockito']",354,TRUE,0,2
robolectric java.lang.AssertionError while unit testing,"<p>I have a login form which contains two edit texts, one to enter an emailId and another to enter a password. I have written a simple method to validate that these fields are not empty. This is my method </p>

<pre><code>public boolean validate() {

    if(edtEmail.getText().toString().trim().equalsIgnoreCase("""")){
        showErrorMessage(true);
        return false;
    }

    if(edtPassword.getText().toString().trim().equalsIgnoreCase("""")){
        showErrorMessage(false);
        return false;
    }
    return true;
}
</code></pre>

<p>I have written a unit test for this method</p>

<pre><code>@Test
public void check_validate() {
    EditText edtEmail = loginActivity.findViewById(R.id.edtEmail);
    EditText edtPassword=loginActivity.findViewById(R.id.edtPassword);
    assertTrue(loginActivity.validate());
}
</code></pre>

<p>I am getting the error as <strong>java.lang.AssertionError</strong>. All i want to check is whether the function is working correctly.</p>
",https://stackoverflow.com/questions/52090042/robolectric-java-lang-assertionerror-while-unit-testing,"['android', 'unit-testing', 'robolectric']",201,FALSE,0,0
Angular unit testing getting failed,"<p>I am trying to unit test the function <code>editDependentInfo()</code>, but I am getting error, because in that function, another function <code>populateEditDepInfo()</code> is being called and <code>populateEditDepInfo</code> have <code>this.dependentsInfo</code> property and test from <code>EditDependentInfo</code> is trying to access but not able to
Please find the below code and let me know what should I do</p>

<pre><code>let dependentsInfo: Dependents;
        class ProfileDependentsStub {
            dependentInfoChange: Subject&lt;any[]&gt; = new Subject&lt;any[]&gt;();
            dependentInfoDelete: Subject&lt;any[]&gt; = new Subject&lt;any[]&gt;();

            data = {
                body: [{states: [{name: ""Alabama"", code: ""AL""}]}, {countries: [{name: ""UNITED STATES"", code: ""USA""}]}, ['relationshipType'], {hideDBCardStatus:""no""}, {hsaenrollmentStatus: ""Enrolled""},{beneficiaryType:[""Contingent"", ""Primary""]},
                {relationshipType:[""Adopted Child""]}, {status:[""Active""]}, 
                {prefixlist: [""DEACON""]},{prefixlist: [""DEACON""]}, {addressDetails:[{addressLineOne: ""6226 3RD DRIVE""}]}, {beneficiaryList:[{id:123, firstName:""David""}]},
                {dependentsList:[{id:1234, employeeId:909}]} ]}

            getChildObject = function (href) {
                return { href: '' };
            };

            getChildLinks = function () {
                return Observable.of(ResponseData);
            };

            getLabelList = function (label) {
                return label;
            };

            addChildObjects = function (links) {
                return links;
            };

            addLabelList = function (labels) {
                return labels;
            };

            getStateCountryList = function () {
                return Observable.of(this.data);
            };

            getRelationAndStatusList = function () {
                return Observable.of(this.data);
            };

            getPrefixSuffixList = function () {
                return Observable.of(this.data);
            };

            populateEditDepInfo = function(data){
                return data;
            }

            getDependentsInfoDetails = function () {
                this.data.body['dependentsList'] = new Array('John Smith');
                return Observable.of(this.data);
            };
        }
</code></pre>

<p>test which is getting failed</p>

<pre><code>  it('should edit Dependent Info', () =&gt; {

        component.editDependentInfo(null,this.userDependentInfo)

        expect(component.isUpdateDependentInfo).toBeTruthy();
    });
</code></pre>

<p>Component which I am testing</p>

<pre><code>    export class {
       dependentsInfo: Dependents;
    editDependentInfo(event = null, userDependentInfo: Dependents) {
            this.dependentsInfo = &lt;Dependents&gt;{};
            this.clearSelectValues();
            this.isUpdateDependentInfo = true;
            this.dependentsInfo = userDependentInfo;
            this.populateEditDepInfo();
        }

        populateEditDepInfo(): void {
            this.saveDepInfo = false;
            if (this.dependentsInfo.id) {
                this.dependentId = this.dependentsInfo.id;
            }}
}
</code></pre>

<p>Sample Dependents class</p>

<pre><code>class Dependents {
  name: string;
  id: string;
  dependentType: string;
  status: string;
  ineligibleReason: String;
  depndtDebitCardStatus: string;
  showCardStatusfInfo: boolean;
  addressLineOne: string;
  addressLineTwo: string;
  addressLineThree: string;
  city: string;}
</code></pre>

<p>Error which I am getting</p>

<pre><code>TypeError: Cannot read property 'id' of undefined
    at ProfileDependentsViewComponent.populateEditDepInfo (webpack:///./src/app/profile/_profile-dependents-view/profile-dependents-view.component.ts?:207:33)
    at ProfileDependentsViewComponent.editDependentInfo (webpack:///./src/app/profile/_profile-dependents-view/profile-dependents-view.component.ts?:202:14)
    at Object.eval (webpack:///./src/app/profile/_profile-dependents-view/profile-dependents-view.component.spec.ts?:135:19)
</code></pre>
",https://stackoverflow.com/questions/50767526/angular-unit-testing-getting-failed,"['angular', 'typescript', 'angular5', 'karma-jasmine', 'angular-unit-test']",1117,TRUE,0,1
Unit Testing U-sql Scripts,"<p>I want to unit test the u-sql scripts which does not contain any user defined object and user defined functions.
Please let me know how to unit test the u-sql scripts.</p>
",https://stackoverflow.com/questions/50589800/unit-testing-u-sql-scripts,"['unit-testing', 'u-sql']",144,FALSE,0,0
Unit Testing dynamically imported React Component,"<p>I have a very simple React component that uses <a href=""https://github.com/jamiebuilds/react-loadable"" rel=""noreferrer""><code>react-loadable</code></a> to dynamically import another component. The code looks something akin to the following:</p>

<pre><code>import React from 'react';
import Loadable from 'react-loadable';
import LoaderComponent from 'path/to/LoaderComponent';


export default outerLoadableComponent = Loadable({
  loader: () =&gt; import('path/to/innerComponent'),
  loading() {
    return &lt;LoaderComponent /&gt;
  }
});
</code></pre>

<p>I am attempting to test this component by using Enzyme to <code>mount</code> <code>outerLoadableComponent</code>, which creates a wrapper around <code>outerLoadableComponent</code> where I can see that the <code>LoaderComponent</code> wrapping it has the <code>loadingState</code> set to true. However, I am stuck at the point where the inner <code>import</code> does not resolve. It seems to be a promise that would only resolve should the import actually go through, however even with some timeouts, it does not work:</p>

<pre><code>const expect = chai.expect;
chai.use(sinonChai);

it('should render the loading state, and innerComponent', (done) =&gt; {
  const wrapper = mount(
    &lt;outerLoadableComponent /&gt;
  );

  expect(wrapper.loading).to.be.true;

  setTimeout(() =&gt; {
    expect(wrapper.loading).to.be.false;
    expect(wrapper.loaded).to.exist; // loaded state returns a function
    expect(wrapper.find(innerComponent)).to.exist;
    done();
  }, 500);
});
</code></pre>

<p>My <code>babel-rc</code> has <code>dynamic-import-node</code> so running this outside of the test works all fine. But there seems to be no clear/documented way of mocking (with sinon) the results of an <code>import</code> promise. Any ideas?</p>
",https://stackoverflow.com/questions/49638887/unit-testing-dynamically-imported-react-component,"['reactjs', 'sinon', 'chai', 'enzyme', 'react-loadable']",999,FALSE,7,0
Angular unit-testing mock paramMap get,"<p>I've component which represents an item from a list and to get this item I use <code>this.route.snapshot.paramMap.get('id')</code>. How do I mock this?
I've tried</p>

<pre><code>providers: [
                {
                    provide: ActivatedRoute,
                    useValue: { snapshot: { params: convertToParamMap({ id: '1' }) } }
                }
            ]
</code></pre>

<p>But this results in</p>

<blockquote>
  <p>TypeError: Cannot read property 'get' of undefined</p>
</blockquote>
",https://stackoverflow.com/questions/53479797/angular-unit-testing-mock-parammap-get,"['angular', 'unit-testing', 'karma-runner']",6007,TRUE,6,1
Unit Testing Typescript for Compiler Errors,"<p>Is there a library or some form of built-in support in Typescript for writing unit tests to assert that some code does <em>not</em> compile? It would be be especially nice if the precise error message / code could also be tested for.</p>

<p>For example, I would like to assert that the following code:</p>

<pre><code>expect(tsErrorCode`const x=""a"";const y:number=x`).toBe(""TS2322"")
</code></pre>

<p>or</p>

<pre><code>expect(tsCompiles`const x=""a"";const y:number=x`).toBeFalsy()
</code></pre>
",https://stackoverflow.com/questions/50164317/unit-testing-typescript-for-compiler-errors,"['unit-testing', 'typescript']",255,TRUE,6,1
Jest unit Testing - No tests found,"<p>I am starting out with Jest unit testing.
I keep getting ""No tests found"" while running a jest unit test.</p>

<p><strong>Error description</strong></p>

<pre><code>yarn test
    yarn run v1.3.2
    $ jest
    No tests found
    In E:\Course\Testing JavaScript\Jest Demo
      4 files checked.
      testMatch: **/__tests__/**/*.js?(x),**/?(*.)(spec|test).js?(x) - 3 matches
      testPathIgnorePatterns: \\node_modules\\ - 4 matches
    Pattern:  - 0 matches
    error Command failed with exit code 1.
</code></pre>

<p>os : window 7 ,
node v : 8.6,
npm v : 5.4.2</p>

<pre><code>folder structure :
Demo 
    package.json
    __tests__
           sum.js
           sum.test.js
</code></pre>

<p><strong>sum.js file:</strong></p>

<pre><code>function sum(a, b) {
  return a + b;
}
module.exports = sum;
</code></pre>

<p><strong>sum.test.js</strong></p>

<pre><code>const sum = require(""./sum"");

test(""adds 1 + 2 to equal 3"", () =&gt; {
  expect(sum(1, 2)).toBe(3);
});
</code></pre>

<p><strong>package.json</strong></p>

<pre><code>{
  ""name"": ""JestDemo"",
  ""version"": ""1.0.0"",
  ""main"": ""index.js"",
  ""license"": ""MIT"",
  ""dependencies"": {
    ""jest"": ""^22.4.3""
  },
  ""scripts"": {
    ""test"": ""jest""
  }
}
</code></pre>

<p>So far, i have referred these articles 
<a href=""https://stackoverflow.com/questions/44741766/jest-no-tests-found"">Stackoverflow-Jest No Tests found
</a></p>

<p>A few more post on github too regarding the same issue but nothing helped.</p>

<p><strong>What i did so far :</strong></p>

<p>1) changed the script to point to folder containing test files:</p>

<pre><code>""scripts"": {
    ""test"": ""jest __test__""  // 
     from ""test"": ""jest""
  }
</code></pre>

<p>2) tried changing folder structure.</p>

<p>Could someone help me figure out the problem ?</p>
",https://stackoverflow.com/questions/49584364/jest-unit-testing-no-tests-found,"['javascript', 'unit-testing', 'jestjs']",16329,TRUE,6,1
Angular 6 unit testing component with DomSanitizer dependency,"<p>In a unit test to just create (instantiate) a component that has a <code>DomSanitizer</code> dependency, how does one mock / stub this dependency?</p>

<p>Because <code>DomSanitizer</code> is an <code>Abstract</code> class, I have no idea what the method signature of <code>bypassSecurityTrustHtml</code> really looks like.</p>

<p>And if it's not intended to mock / stub <code>DomSanitizer</code>, how should one proceed to inject the actual implementation iso the abstract class?</p>

<p>actual statement in the component looks like:</p>

<pre class=""lang-js prettyprint-override""><code>this.trustedString = &lt;string&gt;this.domSanitizer.bypassSecurityTrustHtml(trustedHTML);
</code></pre>

<p><code>TestBed</code> setup looks like:</p>

<pre class=""lang-js prettyprint-override""><code>beforeEach(async(() =&gt; {
  TestBed.configureTestingModule({
    imports: [
      BrowserModule,
      // other modules
    ],
    providers: [
      {
        provide: DomSanitizer,
        useValue: {
          bypassSecurityTrustHtml: () =&gt; 'safeString'
        }
      },
      // more providers
    ],
    declarations: [ TheComponent ],
    schemas: [ NO_ERRORS_SCHEMA ]
  })
    .compileComponents();
}));
</code></pre>

<p>The specific error that I'm getting in Karma in Chrome (not headless) is this:</p>

<p><code>TypeError: view.root.sanitizer.sanitize is not a function</code></p>

<blockquote>
  <p>error properties: Object({ ngDebugContext: DebugContext_({ view: Object({ def: Object({ factory: Function, nodeFlags: 16793601, rootNodeFlags: 1, nodeMatchedQueries: 0, flags: 0, nodes: [ Object({ nodeIndex: 0, parent: null, renderParent: null, bindingIndex: 0, outputIndex: 0, checkIndex: 0, flags: 1, childFlags: 16793601, directChildFlags: 16777217, childMatchedQueries: 0, matchedQueries: Object({  }), matchedQueryIds: 0, references: Object({  }), ngContentIndex: null, childCount: 5, bindings: [  ], bindingFlags: 0, outputs: [  ], element: Object({ ns: null, name: null, attrs: [  ], template: null, componentProvider: null, componentView: null, componentRendererType: null, publicProviders: null({  }), allProviders: null({  }), handleEvent: Function }), provider: null, text: null, query: null, ngContent: null }), Object({ nodeIndex: 1, parent: Object({ nodeIndex: 0, parent: null, renderParent: null, bindingIndex: 0, outputIndex: 0, checkIndex: 0, flags: 1, childFlags: 16793601, directChildFlags: 16777217 ...
      at 
      at setElementProperty (webpack:///./node_modules/@angular/core/fesm5/core.js?:8237:61)
      at checkAndUpdateElementValue (webpack:///./node_modules/@angular/core/fesm5/core.js?:8189:13)
      at checkAndUpdateElementInline (webpack:///./node_modules/@angular/core/fesm5/core.js?:8136:24)
      at checkAndUpdateNodeInline (webpack:///./node_modules/@angular/core/fesm5/core.js?:10477:20)
      at checkAndUpdateNode (webpack:///./node_modules/@angular/core/fesm5/core.js?:10443:16)
      at debugCheckAndUpdateNode (webpack:///./node_modules/@angular/core/fesm5/core.js?:11076:38)
      at debugCheckRenderNodeFn (webpack:///./node_modules/@angular/core/fesm5/core.js?:11062:13)
      at Object.eval [as updateRenderer] (ng:///DynamicTestModule/ConversationMessageComponent.ngfactory.js:84:5)
      at Object.debugUpdateRenderer [as updateRenderer] (webpack:///./node_modules/@angular/core/fesm5/core.js?:11054:21)
      at checkAndUpdateView (webpack:///./node_modules/@angular/core/fesm5/core.js?:10430:14)</p>
</blockquote>
",https://stackoverflow.com/questions/51874109/angular-6-unit-testing-component-with-domsanitizer-dependency,"['angular', 'unit-testing', 'sanitization']",16260,TRUE,20,2
C# - Unit testing Factory Design Pattern,"<p>I'm working on a project and I have to Unit Test a Factory Design pattern in C#.
Currently im stuck and I have no idea what I have too do. Can someone help me out? I want to Unit Test this code:</p>

<pre><code>public class CinemaFactory : AbstractFactory //inheritance of AbstractFactory
{
    public override Space createspace(AddItemsInProps item)
    {
        //returns new Cinema
        return new Cinema(item.AreaType, item.Position, item.Dimension); 
    }
}
</code></pre>

<p>I also made a Unit test project and created this:</p>

<pre><code>    [TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        //Arrange
        Game1.Design_Patterns.CinemaFactory cinemaFactory = new Game1.Design_Patterns.CinemaFactory();

        //Act

        //Assert

    }
}
</code></pre>

<p>Cinema:</p>

<pre><code>public class Cinema : Space //inheritance of Space class
{

    //Named arguments free you from the need to remember or to look up the order of parameters in the parameter lists of called methods. 
    public Cinema(string areaType, string position, string dimension) : base(areaType, position, dimension)
    {
        //The sprite  of the Cinema
        this.Img = ""cinema"";
    }
    public void StartMovie()
    {

    }
}
</code></pre>

<p>This is de class AddItemsInProps:</p>

<pre><code>public class AddItemsInProps
{
    //Get: The get { } implementation must include a return statement. It can access any member on the class.
    //Set: The set { } implementation receives the implicit argument ""value."" This is the value to which the property is assigned.

        public string Classification { get; set; }
        public string AreaType { get; set; }
        public string Position { get; set; }
        public string Dimension { get; set; }
        public int Capacity { get; set; }
        public int ID { get; set; }
    }
}
</code></pre>

<p>This is de class Space:</p>

<pre><code> public abstract class Space
{
    public string AreaType { get; set; }
    public Point Position { get; set; }
    public Point Dimension { get; set; }
    public int ID { get; set; }
    public string Img { get; set; }
    public int Afstand { get; set; }
    public Space Vorige { get; set; }
    public Dictionary&lt;Space, int&gt; Neighbours = new Dictionary&lt;Space, int&gt;();
</code></pre>

<p>This is de class AbstractFactory:</p>

<pre><code>    public abstract class AbstractFactory
{
    //Creating Object
    public abstract Space createspace(AddItemsInProps item);
}
</code></pre>
",https://stackoverflow.com/questions/52839852/c-unit-testing-factory-design-pattern,"['c#', 'unit-testing', 'tdd']",8419,TRUE,5,2
Chutzpah and Jasmine typescript unit testing,"<p>I am trying to get Chutzpah and Jasmine working together in visual studio, my end goal is to get unit tests running with TeamCity integration.</p>

<p>On save, all of the typescript code generates a single <code>.js</code> file.  This also causes Chutzpah to run my tests, so far so good.</p>

<p>My issue is Chutzpah reports 0 passed, 0 failed and 0 errors.  The Jasmine html file that is generated lists out all of my tests correctly but Chutzpa doesn't seem to receive any information back from Jasmine.</p>

<p>Highlights of a trace log:</p>

<pre><code>Trying to build test context for c:\.....\test.ts
Building test context for c:\.....\test.ts
...framework dependencies / other ok looking things... (~15 lines)
Finished building test context for c:\.....\test.ts
Warning: 0 : Message:Chutzpah determined generated .js files are missing but the compile 
mode is External so Chutzpah can't compile them. Test results may be wrong.
</code></pre>

<p>Then it starts Phantom js and logs loading / receiving resources.  My test.ts file is not one of the recources listed but the site-wide <code>.js</code> is (I checked the site-wide file and my tests are being appended to it).</p>

<pre><code>Finished test run for c:\......\test.ts in Discovery mode
Cleaning up test context for c:\......\test.ts
Chutzpah run finished with 0 passed, 0 failed and 0 errors
Chutzpah.json file cache cleared
End Test Adapter Discover Tests
</code></pre>

<p><strong>chutzpah.json</strong></p>

<pre><code>{
  ""Framework"": ""jasmine"",  
  ""EnableTestFileBatching"": true,
  ""Compile"": {
    ""Mode"": ""External"",
    ""Extensions"": [ "".ts"" ],
    ""ExtensionsWithNoOutput"": [ "".d.ts"" ],
    ""Paths"": [
      {
        ""OutputPath"": ""../SiteWide.js"",
        ""SourcePath"": ""Views""
      }
    ]
  },
  ""References"": [
    {
      ""Path"": ""../knockout-3.4.2.js"",
      ""IsTestFrameworkFile"": true
    }
  ],
  ""Tests"": [
    {
      ""Includes"": [ ""*.ts"" ],
      ""Path"": ""../Tests/Views""
    }
  ],
  ""EnableTracing"": true,
  ""TraceFilePath"": ""./trace.log""
}
</code></pre>

<p><strong>tests.ts</strong></p>

<pre><code>describe('configuring unit tests for typescript!', () =&gt; {
    it('this should pass', () =&gt; {
        expect(1).toBe(1);
    });

    it('this should fail', () =&gt; {
        expect(1).toBe(0);
    });
});
</code></pre>

<p>There are a few things I'm suspicious of (the missing .js files line from the trace - but that might just be caused by my single js file compilation step?)</p>

<p>Maybe I'm missing references to jasmine in my chutzpah.json?</p>

<p>I'm at a loss for why the Jasmine tests work, but Chutzpah doesn't report back.</p>
",https://stackoverflow.com/questions/49524099/chutzpah-and-jasmine-typescript-unit-testing,"['unit-testing', 'typescript', 'jasmine', 'chutzpah']",793,TRUE,4,1
Unit Testing Azure Functions with HttpRequestMessage,"<p>I'm running into a few issues when trying to unit test HTTP Trigger Azure Functions in Visual Studio. I've created a GitHub repo (<a href=""https://github.com/ericdboyd/TestingAzureFunctions"" rel=""nofollow noreferrer"">https://github.com/ericdboyd/TestingAzureFunctions</a>) with an example solution that contains both an Azure Function project and a Unit Test project that demonstrates the issues.</p>

<p>First, when I bring in Microsoft.AspNet.WebApi.Core it creates a conflict between System.Web.Http and Microsoft.AspNetCore.Mvc.WebApiCompatShim when trying to use IContentNegotiator. The only way around that was to alias WebApiCompatShim in the csproj file for the test project using the following:</p>

<pre><code>&lt;Target Name=""ChangeAliasesOfStrongNameAssemblies"" BeforeTargets=""FindReferenceAssembliesForReferences;ResolveReferences""&gt;
&lt;ItemGroup&gt;
  &lt;ReferencePath Condition=""'%(FileName)' == 'Microsoft.AspNetCore.Mvc.WebApiCompatShim'""&gt;
    &lt;Aliases&gt;webapicompatshim&lt;/Aliases&gt;
  &lt;/ReferencePath&gt;
&lt;/ItemGroup&gt;
</code></pre>

<p></p>

<p>Once I got past that error, I run into this issue which I haven't been able to get past. Using the HttpRequestMessage.CreateResponse extension method to return a response in the Azure Function, I get ""No service for type 'System.Net.Http.Formatting.IContentNegotiator' has been registered."" when I try to test it. I have tried to build a HttpRequestMessage that I think should work with that extension method using the following code which can also be found in the GitHub repo, but it fails, and I have worked on trying to get past this for several hours now.</p>

<pre><code>IServiceCollection services = new ServiceCollection();
services.AddOptions();
services.AddSingleton(typeof(IContentNegotiator), typeof(DefaultContentNegotiator));
IServiceProvider serviceProvider = services.BuildServiceProvider();

var httpContext = new DefaultHttpContext {RequestServices = serviceProvider};

var httpConfiguration = new HttpConfiguration();

HttpRequestMessage request = new HttpRequestMessage
{
    Method = HttpMethod.Post,
    RequestUri = new Uri(url),
    Content = new StringContent(content, Encoding.UTF8, ""application/json""),
    Properties =
    {
        { HttpPropertyKeys.HttpConfigurationKey, httpConfiguration },
        { nameof(HttpContext), httpContext} 
    }
};
</code></pre>

<p>If I don't use that CreateResponse extension method, and just create HttpResponseMessage objects, it works fine.</p>

<p>Just to set some additional context, I know this is not the best way to unit test the code being executed by the Azure Function. I'm unit testing that code much more granularly. But I want to be able to unit test the Azure Function that is performing the mapping between the http request and response to that logic. </p>

<p>There are two Azure Functions and two unit tests in the GitHub repo, one set with the extension method, one without to demonstrate the issue. But everything else is the same.</p>
",https://stackoverflow.com/questions/49498176/unit-testing-azure-functions-with-httprequestmessage,"['unit-testing', 'azure', 'azure-functions', 'asp.net-core-webapi']",1892,TRUE,4,2
unit testing flask app with login_required,"<p>I have the following test case for my flask app setup </p>

<pre><code>class AboutViewTest(BaseTestCase):
    def setUp(self):
        self.url = url_for('pages_app.about',_external=True)
        self.url_login_redirect = url_for('accounts_app.login')

    def test_render(self):
        # without login
        resp = self.client.get(self.url)
        self.assertRedirects(resp, self.url_login_redirect)

        # after login
        with self.app.test_client() as c:
            login_successful = self.login(username='user1', password=""123456"", client=c)
            self.assertTrue(login_successful)
            resp = c.get(self.url)
            self.assertStatus(resp, 200) # this fails
</code></pre>

<p>To test a view with @login_required </p>

<pre><code>@pages_app.route('/about/')
@login_required
def about():
    return render_template('pages/about.html')


def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if g.user is None:
            return redirect(url_for('accounts_app.login', next=request.url))
        return f(*args, **kwargs)
    return decorated_function
</code></pre>

<p>The second test case fails (login required) as it gets redirected to login <code>302 != 200</code></p>

<p>How can I test this view with to pass both the cases(with and without login)? Wht are the best practices to do this? </p>
",https://stackoverflow.com/questions/50328918/unit-testing-flask-app-with-login-required,"['python', 'unit-testing', 'flask', 'nose']",1461,TRUE,4,1
Testing scrollintoview while unit testing angular,"<p>When unit testing a scrollintoview() method in Angular 2+, I receive an error -> <em>""Failed: Cannot read property 'scrollIntoView' of undefined"" in Angular 2+</em></p>

<p>Here is my scrollintoview code:</p>

<pre><code> document.getElementsByClassName('class')[0].scrollIntoView();
</code></pre>

<p>Any ideas on how to resolve this trough an execute script?</p>
",https://stackoverflow.com/questions/48722982/testing-scrollintoview-while-unit-testing-angular,"['angular', 'testing', 'scroll', 'scrollview', 'karma-runner']",3805,TRUE,4,2
Firebase Functions TypeScript unit testing devDependencies,"<p>Following the guideline here: <a href=""https://firebase.google.com/docs/functions/unit-testing"" rel=""nofollow noreferrer"">https://firebase.google.com/docs/functions/unit-testing</a>
I'm trying to write unit tests to my TS functions.
here's 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"": ""functions"",
  ""scripts"": {
    ""lint"": ""tslint --project tsconfig.json"",
    ""build"": ""tsc"",
    ""serve"": ""npm run build &amp;&amp; firebase serve --only functions"",
    ""shell"": ""npm run build &amp;&amp; firebase functions:shell"",
    ""start"": ""npm run shell"",
    ""deploy"": ""firebase deploy --only functions"",
    ""logs"": ""firebase functions:log"",
    ""test"": ""mocha --reporter spec""
  },
  ""main"": ""lib/index.js"",
  ""dependencies"": {
    ""@types/algoliasearch"": ""^3.27.0"",
    ""@types/axios"": ""^0.14.0"",
    ""@types/nodemailer"": ""^4.6.0"",
    ""@types/stripe"": ""^5.0.11"",
    ""algoliasearch"": ""^3.27.1"",
    ""axios"": ""^0.18.0"",
    ""firebase-admin"": ""~5.12.0"",
    ""firebase-functions"": ""^1.0.3"",
    ""nodemailer"": ""^4.6.4"",
    ""stripe"": ""^5.8.0"",
    ""webpack"": ""^4.7.0""
  },
  ""devDependencies"": {
    ""@types/node"": ""^9.6.6"",
    ""firebase-functions-test"": ""^0.1.2"",
    ""mocha"": ""^5.2.0"",
    ""ts-loader"": ""^4.2.0"",
    ""tslint"": ""^5.8.0"",
    ""typescript"": ""^2.8.3"",
    ""webpack-cli"": ""^2.1.2"",
    ""webpack-node-externals"": ""^1.7.2""
  },
  ""private"": true
}</code></pre>
</div>
</div>
</p>

<p>and I have 1 problem and 1 question.</p>

<p><strong>problem:</strong>
I can't import the firebase-functions-test
in my index.test.ts file.
it is looking for it in dependencies only and not in devDependencies...
(adding it inside dependencies solve it).</p>

<p><strong>question:</strong>
Can I move all the @types to devDependencies?</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/50677994/firebase-functions-typescript-unit-testing-devdependencies,"['unit-testing', 'typescript', 'firebase', 'dependencies', 'google-cloud-functions']",1054,TRUE,4,2
Unit testing Excel addin using VSTO,"<p>I've been trying to test my addin without success, and even after looking at various sources like <a href=""https://blogs.msdn.microsoft.com/varsha/2010/08/17/writing-automated-test-cases-for-vsto-application/"" rel=""nofollow noreferrer"">MSDN</a> and <a href=""https://stackoverflow.com/questions/45121396/vsto-unit-testing-office-addin-in-c-sharp-net-via-requestcomaddinautomationserv"">StackOverflow</a></p>

<p>I can't seem to be able to do it.
Here's my current code (I trimmed to only have the relevant parts)</p>

<h2>AssemblyInfo.cs</h2>

<pre><code>[assembly: ComVisible(true)]
[assembly: InternalsVisibleTo(""MyAddInTest"")]
</code></pre>

<h2>ThisAddIn.cs</h2>

<pre><code>private AddinHelper _comAddinObject;
protected override object RequestComAddInAutomationService()
{
    return _comAddinObject ?? (_comAddinObject = new AddinHelper());
}
</code></pre>

<h2>AddinHelper.cs</h2>

<pre><code>[ComVisible(true)]
[Guid(""B523844E-1A41-4118-A0F0-FDFA7BCD77C9"")]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface IAddinHelper
{
    string GetString();
}

[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[Guid(""A523844E-1A41-4118-A0F0-FDFA7BCD77C9"")]
[ComSourceInterfaces(typeof(IAddinHelper))]
public class AddinHelper : StandardOleMarshalObject, IAddinHelper
{
    public string GetString()
    {
        return Globals.ThisAddIn.Application.ActiveWorkbook.Name;
    }
}
</code></pre>

<h2>ThisAddInTest.cs</h2>

<pre><code>Application = new Application();
Workbook = Application.Workbooks.Add();
COMAddIns comAddins = Application.COMAddIns;
COMAddIn comAddin = comAddins.Item(""MyAddIn"");
IAddinHelper comObject = (IAddinHelper) comAddin.Object;
</code></pre>

<p>The main project references the .NET Assembly version of <code>Microsoft.Office.Interop.Excel</code> with Embed Interop Types set to true.
My test project references my VSTO project, and the COM (ActiveX) version of the Interop.</p>

<p>The exception I get is:</p>

<blockquote>
  <p>Unable to cast COM object of type 'System.__ComObject' to interface type 'MyAddIn.IAddinHelper'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{B523844E-1A41-4118-A0F0-FDFA7BCD77C9}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).</p>
</blockquote>

<p>I currently use Office 2013 (so Office 15.0) and the references are all pointing to that version, .NET 4.5.3 and Visual Stuio Community 2017. The SO link that I provided seems to be the exact same issue, however I still have the exception when running my tests unlike there.</p>
",https://stackoverflow.com/questions/50743180/unit-testing-excel-addin-using-vsto,"['c#', 'excel', 'testing', 'vsto', 'office-interop']",388,FALSE,3,0
Connection refused on C# unit testing,"<p>When I do a simple unit testing in C#, 
it's throwing  ""System.AggregateException: One or more errors occurred. ---> System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it <strong>127.0.0.1:52747</strong>""</p>

<p>Unit test Cs file:</p>

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

<p>CS file for the get method:</p>

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

<p>When I run test method , it's keep on refusing</p>
",https://stackoverflow.com/questions/50962783/connection-refused-on-c-unit-testing,"['c#', 'unit-testing', 'asp.net-web-api']",1480,FALSE,3,0
C# Unit Testing - Assertions on JSON,"<p>I am just playing around with some Json and Fluentassertions, I am able to make a call to an API successfully, get the results, deserialize them but for some reason when i get to do an assertion on the response its losing the data and it empty. I have debugged, can see the data flowing through and then losing it during assertion.</p>

<p>Any help appreciated. </p>

<pre><code>{
    [TestClass]
    public class UnitTest1
    {
        HttpClient client = new HttpClient();

         [TestMethod]
        public void ActorNotInSeason6Episode1()
        {
            try
            {
                //test = extent.CreateTest(""Test 1"");
                HttpResponseMessage respone = client.GetAsync(""https://api.themoviedb.org/3/tv/1399/season/6/episode/1/credits?api_key="").Result;
                Assert.IsTrue(respone.IsSuccessStatusCode.Equals(true));
                string ResponseMessage = respone.Content.ReadAsStringAsync().Result;
                Actors actors = JsonConvert.DeserializeObject&lt;Actors&gt;(ResponseMessage);
                //var a = Actors.cast[""cast""];
                //var names = a.Children[];
                //var a = actors.cast.Children();


           actors.cast.Should().Contain(""Emilia Clarke"", ""Test"");

            }
            catch(AssertFailedException)
            {
                Assert.Fail();

            }
        }

    }
}



    class Actors
    {
        public JArray cast  { get; set; }
        public JArray guest_stars { get; set; }

    }
}
</code></pre>

<p>JSON</p>

<pre><code>{[
  {
    ""character"": ""Daenerys Targaryen"",
    ""credit_id"": ""5256c8af19c2956ff60479f6"",
    ""gender"": 1,
    ""id"": 1223786,
    ""name"": ""Emilia Clarke"",
    ""order"": 0,
    ""profile_path"": ""/lRSqMNNhPL4Ib1hAJxmDFBXHAMU.jpg""
  }
]}
</code></pre>
",https://stackoverflow.com/questions/53450568/c-unit-testing-assertions-on-json,"['c#', 'unit-testing', 'nunit', 'assertion', 'fluent-assertions']",8050,TRUE,3,2
Vue and Jest unit testing components,"<p>I'm pretty new in <strong>Vue js</strong>, and I'm starting with unit testing with <strong>Jest</strong>. I don't have any idea where and how to start. I have this piece of Vue code that i would like to test using Jest. Any tips or idea I'll be so thankful.
I read that I should use <strong>shallowMount</strong> from <strong>Vue test-utils</strong> to avoid troubles during the component testing</p>

<pre><code>&lt;template &gt;
  &lt;div class=""wrapper""&gt;
    &lt;div class=""user""&gt;
      &lt;span&gt;{{ user.substr(0, 4) }}&lt;/span&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/template&gt;
&lt;script&gt;
export default {
  props: {
    user: {
      type: String,
      required: true
    }
  }
}
&lt;/script&gt;
</code></pre>

<p>At the moment I have something like this, but I don't know how to conitnue</p>

<pre><code>import { shallowMount } from '@vue/test-utils'
import User from '../User.vue'


describe('User', () =&gt; {
  it('Should substract four letters', () =&gt; {
    const wrapper = shallowMount(User, {
      props: {
        ''
      }
    })
  })
})
</code></pre>
",https://stackoverflow.com/questions/51520835/vue-and-jest-unit-testing-components,"['javascript', 'unit-testing', 'vue.js', 'vuejs2', 'jestjs']",1620,TRUE,3,1
flask - unit testing session with nose,"<p>I am trying to test the following code with nose. The app.py file is as below:</p>

<pre><code>from flask import Flask, session, redirect, url_for, request

app = Flask(__name__)

@app.route('/')
def index():
    session['key'] = 'value'
    print('&gt;&gt;&gt;&gt; session:', session)
    return redirect(url_for(""game""))
</code></pre>

<p>The test file is below:</p>

<pre><code>from nose.tools import *
from flask import session
from app import app

app.config['TESTING'] = True
web = app.test_client()

def test_index():

    with app.test_request_context('/'):
        print('&gt;&gt;&gt;&gt;test session:', session)
        assert_equal(session.get('key'), 'value')
</code></pre>

<p>When I run the test file, I get an assertion error <code>None != 'value'</code>
and the print statement in the test file prints an empty session object. Moreover, the print statement in the app.py file does not print anything. Does this mean that the index function isn't running?</p>

<p>Why is this happening? According to the flask documentation (<a href=""http://flask.pocoo.org/docs/1.0/testing/#other-testing-tricks"" rel=""nofollow noreferrer"">http://flask.pocoo.org/docs/1.0/testing/#other-testing-tricks</a>),
I should have access to the session contents through test_request_context().</p>

<p>Also, if I write the test_index function like this instead, the test works (and both print statements in the app.py and test files are executed):</p>

<pre><code>def test_index():

    with app.test_client() as c:
        rv = c.get('/')
        print('&gt;&gt;&gt;&gt;test session:', session)
        assert_equal(session.get('key'), 'value')
</code></pre>

<p>What is the difference between using Flask.test_client() and Flask.test_request_context in a 'with' statement? As I understand it, the point in both is to keep the request context around for longer.</p>
",https://stackoverflow.com/questions/50866804/flask-unit-testing-session-with-nose,"['python', 'python-3.x', 'flask', 'nose']",1173,TRUE,3,1
NullPointerException from Toast while Unit Testing,"<p>I am testing a function of my Signup class, however every time I run it a NullPointerException occurs inside the first if statement it enters at:</p>

<pre><code>pass.show()
</code></pre>

<p>I suspect it is has something to do with not testing the app with an emulator. How can I prevent errors of creating a Toast when I am testing this? </p>

<p><strong>Function in Signup Class:</strong></p>

<pre><code>public boolean checkInput(String username, String email, String password, String confirmpassword) {
    if (!email.contains(""@"") || !email.contains("".com"")) {
        Toast pass = Toast.makeText(Signup.this, ""Email must be valid!"", Toast.LENGTH_SHORT);
        pass.show();
        return false;
    }
    if (!password.equals(confirmpassword)) {
        Toast pass = Toast.makeText(Signup.this, ""Passwords don't match!"", Toast.LENGTH_SHORT);
        pass.show();
        return false;
    }
    if (!(password.length() &gt;= 6)) {
        Toast pass = Toast.makeText(Signup.this, ""Password must be at least 6 characters"", Toast.LENGTH_SHORT);
        pass.show();
        return false;
    }
    else {
        return true;
    }
}
</code></pre>

<p><strong>Test method:</strong></p>

<pre><code>    @Test
    public void testInvalidEmail() {

    String testUser = ""testUser"";
    String testEmail = ""testEmail.com""; //invalid
    String testPass = ""testPass"";
    String testConfirmPass = ""testPass"";

    assertFalse(signupClass.checkInput(testUser,testEmail,testPass,testConfirmPass));
}
</code></pre>
",https://stackoverflow.com/questions/52266797/nullpointerexception-from-toast-while-unit-testing,"['android', 'junit', 'android-toast']",1343,TRUE,3,3
Crashing Visual Studio Live Unit Testing,"<p>I´m a new user in <strong>stackoverflow</strong> and this is my problem:</p>

<p>As part of my work, we recently installed VS 2017 Enterprise Edition. Everything was fine untill few weeks ago the <strong><em>Live Unit Testing</em></strong> module stop working.</p>

<p>Does enyone was able to resolve this kind of problems?</p>

<p>This is the output console:</p>

<p><code>
[17:26:23.170 Info] Live Unit Testing started.
[17:26:23.229 Error] - FatalError - System.ArgumentNullException: Value cannot be null.
Parameter name: key
   at System.Collections.Generic.Dictionary'2.Insert(TKey key, TValue value, Boolean add)
   at Microsoft.CodeAnalysis.LiveUnitTesting.AugmentedProjectDependencyGraph.AddDependencies(ProjectGraphNode projectNode)
   at Microsoft.CodeAnalysis.LiveUnitTesting.AugmentedProjectDependencyGraph.EnsureDirectDependencies()
   at Microsoft.CodeAnalysis.LiveUnitTesting.AugmentedProjectDependencyGraph.GetBuildOrder(Solution solution, CancellationToken cancellationToken)
   at Microsoft.CodeAnalysis.LiveUnitTesting.BuildManagement.BuildManagerState.&lt;BuildAsync&gt;d__35.MoveNext()
[17:26:24.099 Info] Live Unit Testing stopped.
</code></p>

<p><a href=""https://i.stack.imgur.com/8nrMU.png"" rel=""nofollow noreferrer"">Output Console Image</a></p>

<p><strong>Thanks for yor time!</strong></p>
",https://stackoverflow.com/questions/51391235/crashing-visual-studio-live-unit-testing,"['c#', 'visual-studio-2017', 'live-unit-tests']",204,FALSE,2,1
Angular 6 with Jest unit testing,"<p>I cloned a starter project using Angular 6 (<a href=""https://github.com/KrunalLathiya/Angular6CRUDTutorial"" rel=""nofollow noreferrer"">https://github.com/KrunalLathiya/Angular6CRUDTutorial</a>). I removed Karma and installed Jest instead. The site loads fine, but the unit test fails with this error:</p>

<pre><code>Illegal state: Could not load the summary for directive AppComponent.
  at syntaxError (../../../../../execroot/angular/packages/compiler/src/util.ts:100:17)
  at CompileMetadataResolver.Object.&lt;anonymous&gt;.CompileMetadataResolver.getDirectiveSummary (../../../../../execroot/angular/packages/compiler/src/metadata_resolver.ts:426:11)...
</code></pre>

<p>app.component.ts:</p>

<pre><code>import { Component } from '@angular/core';
import { SlimLoadingBarService } from 'ng2-slim-loading-bar';
import { 
  NavigationCancel,
  Event,
  NavigationEnd,
  NavigationError,
  NavigationStart,
  Router } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'app';
  constructor(private _loadingBar: SlimLoadingBarService, private _router: Router) {
    this._router.events.subscribe((event: Event) =&gt; {
      this.navigationInterceptor(event);
    });
  }
  private navigationInterceptor(event: Event): void {
    if (event instanceof NavigationStart) {
      this._loadingBar.start();
    }
    if (event instanceof NavigationEnd) {
      this._loadingBar.complete();
    }
    if (event instanceof NavigationCancel) {
      this._loadingBar.stop();
    }
    if (event instanceof NavigationError) {
      this._loadingBar.stop();
    }
  }
}
</code></pre>

<p>app.component.test.ts:</p>

<pre><code>import { AppModule } from ""./app.module"";
import { TestBed, ComponentFixture, async } from '@angular/core/testing';
import { APP_BASE_HREF } from '@angular/common';
import { Router } from '@angular/router';
import { AppComponent } from './app.component';

describe('AppComponent', () =&gt; {
  beforeEach(() =&gt; {
    class loading = { return { events: {} } };
    class router = {};
    TestBed.configureTestingModule({
      // imports: [AppModule], // didn't help
      declarations: [
        AppComponent
      ],
      providers: [
        AppComponent,
        // { provide: APP_BASE_HREF, useValue: '/' }, // didn't help
        { provide: SlimLoadingBarService, useClass: loading },
        { provide: Router, useClass: router }
      ],
    }).compileComponents();
  });

  it('should create the app', () =&gt; {
    const fixture = TestBed.createComponent(AppComponent);
  });
});
</code></pre>

<p>Do I need something specific for Jest and Angular to work together? Thanks!</p>
",https://stackoverflow.com/questions/51660463/angular-6-with-jest-unit-testing,"['angular', 'jestjs', 'jest-preset-angular']",738,FALSE,2,0
Unit testing directive HostListener not working,"<p>I am attempting to unit test some functionality that does work on the front-end flawlessly but the unit test doesn't seem to be taking hold.</p>

<p>Below is my current unit test, it is not finished completely I am just trying to get the bare bones test to work before moving on to more complicated checks. </p>

<pre class=""lang-js prettyprint-override""><code>@Component({
  template : '&lt;input appInputFilter filterType=""alphanumericOnly"" type=""text"" minlength=""2""&gt;'
})
class TestComponent {

}

describe('InputFilterDirective', () =&gt; {

  let comp: TestComponent;
  let fixture: ComponentFixture&lt;TestComponent&gt;;
  let de: DebugElement;
 // const el: HTMLElement;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      declarations : [InputFilterDirective, TestComponent]
    });

    fixture = TestBed.createComponent(TestComponent);

    comp = fixture.componentInstance;

    de = fixture.debugElement.query(By.directive(InputFilterDirective));
  });

  it('should create instance of inputFilter', () =&gt; {
    expect(comp).toBeTruthy();
    expect(de).toBeDefined();
  });

  it('should only allow onlyNumbers', async(() =&gt; {

    fixture.detectChanges();


    const keyEvent = new KeyboardEvent('keydown', {'code': 'KeyQ'});
    const input = de.nativeElement as HTMLInputElement;
    input.dispatchEvent(keyEvent);
    expect(input.value).toEqual('q');


    expect(true).toBeTruthy();
  }));
});
</code></pre>

<p>And here is my full directive:</p>

<pre class=""lang-js prettyprint-override""><code> import { Directive, ElementRef, HostListener, Input  } from '@angular/core';

@Directive({
  selector: '[appInputFilter]',

})
export class InputFilterDirective {

  private el : any;
  private specialKeys : Array&lt;string&gt; = ['Backspace', 'Tab', 'End', 'Home'];

  @Input() public filterType : any;

  constructor(el: ElementRef) {
    this.el = el;
   }

   @HostListener('keydown', ['$event'])
   onKeyDown(event: KeyboardEvent) {

    if (this.specialKeys.indexOf(event.key) !== -1) {
      return;
    }

    switch (this.filterType) {
      case 'onlyNumber':
        this.appFilter(event, new RegExp(/\D/g));
      break;
      case 'alphanumericOnly':
        this.appFilter(event, new RegExp(/\W/g));
      break;
      case 'alphabeticAndSpecial':
        this.appFilter(event, new RegExp(/[^a-zA-Z'-]/));
      break;
      case 'ipAddress':
        this.appFilter(event, new RegExp(/[^0-9.]/g));
      break;
    }
   };

  appFilter(event: KeyboardEvent, regex: RegExp) {
    const current: string = this.el.nativeElement.value;
    const next: string = current.concat(event.key);

    if (next &amp;&amp; String(next).match(regex)) {
      event.preventDefault();
    }
  };
}
</code></pre>

<p>Additional notes:</p>

<ul>
<li>I have attempted many different KeyEvents such as type key: '1' and such like that. </li>
<li>I have run the unit test as async and non async.</li>
<li>I have followed many different stack overflow instructions on how other people have attempted to unit test HostListeners and unfortunately this is simply not working for me and I have no idea why.</li>
</ul>

<p>And help is very much appreciated, like I said this is a bare bones test, you will notice in the test component that I am using the filter to filter for alphanumeric (which you can check out in the directive code)</p>

<p>Also I am <strong>NOT</strong> opposed to listening for ""preventDefault"" to prove this test so if the issue is how I am detecting change then please let me know and I do not mind adjusting. </p>
",https://stackoverflow.com/questions/48426754/unit-testing-directive-hostlistener-not-working,"['angular', 'unit-testing', 'typescript', 'angular2-forms', 'angular2-directives']",4094,FALSE,3,1
Hubot Unit Testing Not Receiving Response,"<p>I'm trying to set up a simple unit test for my hubot code and I am not receiving responses back.  I have simplified this down to:</p>

<p>test.coffee:</p>

<pre><code>Helper = require('hubot-test-helper')
chai = require 'chai'
expect = chai.expect
helper = new Helper('../hubot-scripts/something.coffee')

describe 'PING', -&gt;
    beforeEach -&gt;
        @room = helper.createRoom()
    afterEach -&gt;
        @room.destroy

    it 'should PONG', -&gt;
        @room.user.say 'alice', '@hubot PING'
        expect(@room.messages).to.eql [
            ['alice', '@hubot PING'],
            ['hubot', 'PONG']
        ]
</code></pre>

<p>and something.coffee:</p>

<pre><code>module.exports = (robot) -&gt;
    robot.response /PING$/i, (msg) -&gt;
        msg.send 'PONG'
</code></pre>

<p>When I run my tests, I get an assertion error of:</p>

<pre><code>  AssertionError: expected [ [ 'alice', '@hubot PING' ] ] to deeply equal [ Array(2) ]
  + expected - actual

     [
       ""alice""
       ""@hubot PING""
     ]
  +  [
  +    ""hubot""
  +    ""PONG""
  +  ]
   ]
</code></pre>

<p>Meaning I am not getting a response back at all.  I have tried changing @hubot to hubot (which shouldn't matter).  I also verified that it is finding my something.coffee, as when I changed that path to an incorrect one I received an error about that.</p>

<p>I am following the example at bottom of <a href=""https://hubot.github.com/docs/scripting/"" rel=""nofollow noreferrer"">https://hubot.github.com/docs/scripting/</a> </p>

<p>Thanks for the help!</p>
",https://stackoverflow.com/questions/48447909/hubot-unit-testing-not-receiving-response,"['coffeescript', 'mocha.js', 'chai', 'hubot']",266,FALSE,3,2
Unit Testing Django Model Save Function,"<p>I'm creating tests to check that a custom calibration model save function updates an asset record (foreign key) if it is the latest calibration record for the asset.  The save function performs exactly as expected in live dev &amp; production server and even in the django shell, but appears to fail during testing...</p>

<p>models.py</p>

<pre><code>class Asset(models.Model):
    ...
    requires_calibration = models.BooleanField()
    passed_calibration = models.BooleanField(default=False)
    calibration_date_prev = models.DateField(null=True, blank=True)
    calibration_date_next = models.DateField(null=True, blank=True)


class CalibrationRecord(models.Model):
    calibration_record_id = models.AutoField(primary_key=True)
    asset = models.ForeignKey(
                              ""myapp.Asset"",
                              on_delete=models.CASCADE,
                              limit_choices_to={""requires_calibration"": True}
                              )
    calibration_date = models.DateField(default=timezone.now)
    calibration_date_next = models.DateField(null=True, blank=True)
    calibration_outcome = models.CharField(max_length=10, default=""Pass"")

    def save(self, *args, **kwargs):

        super(CalibrationRecord, self).save(*args, **kwargs)

        # Check if this is the latest calibration record for any asset, if so update asset.calibration_dates and status
        latest_asset_calibration = CalibrationRecord.objects.filter(asset=self.asset.pk).order_by(
            ""-calibration_date"", ""-calibration_record_id"")[0]

        if self.pk == latest_asset_calibration.pk:

            Asset.objects.filter(pk=self.asset.pk).update(calibration_date_prev=self.calibration_date)

            if self.calibration_date_next:
                Asset.objects.filter(pk=self.asset.pk).update(calibration_date_next=self.calibration_date_next)
            else:
                Asset.objects.filter(pk=self.asset.pk).update(calibration_date_next=None)

            if self.calibration_outcome == ""Pass"":
                Asset.objects.filter(pk=self.asset.pk).update(passed_calibration=True)
            else:
                Asset.objects.filter(pk=self.asset.pk).update(passed_calibration=False)
</code></pre>

<p>tests_models.py example failing test</p>

<pre><code>class CalibrationRecordTests(TestCase):
    def test_calibration_record_updates_asset_cal_date_prev(self):
        """"""
        All calibration records should update related Asset record's ""calibration_date_prev"" to calibration_date
        """"""
        asset1 = Asset.objects.create(asset_description=""Test Asset 2"", requires_calibration=True)
        self.assertIsNone(asset1.calibration_date_prev)
        cal = CalibrationRecord.objects.create(asset=asset1, calibration_description=""Test Calibration 2"", calibration_date=timezone.now())
        self.assertEqual(cal.calibration_date, asset1.calibration_date_prev)
</code></pre>

<p>Error log</p>

<pre><code>======================================================================
FAIL: test_calibration_record_updates_asset_cal_date_prev (assetregister.tests_models.CalibrationRecordTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File ""C:\[path]\app\tests_models.py"", line 159, in test_calibration_record_updates_asset_cal_date_prev
self.assertEqual(cal.calibration_date, asset1.calibration_date_prev)
AssertionError: datetime.datetime(2018, 2, 26, 12, 26, 34, 457513, tzinfo=&lt;UTC&gt;) != None
======================================================================
</code></pre>

<p>All of my tests relating to this custom calibration record save function appear to fail because the related asset record isn't updated when it should be.</p>

<p>Any ideas why this would work during dev and production but not during testing?</p>

<p>Even though the .create() method should automatically do a .save() after, I even tried doing a manual .save() after creating the calibration record, but it still seems to fail.</p>
",https://stackoverflow.com/questions/48989171/unit-testing-django-model-save-function,"['django', 'django-models', 'python-unittest', 'django-testing', 'django-unittest']",4808,TRUE,3,2
How to mock ActivatedRouteSnapshot when unit testing a Resolver,"<p>I want to write a unit test for my resolver, which needs to take <code>ActivatedRouteSnapshot</code> in its constructor like so:</p>

<pre><code>export class MyResolver {
  constructor () {
    // ...
  }

  resolve (private route: ActivatedRouteSnapshot) {
    callFoo(route.params.val);
  }
};
</code></pre>

<p>But in my unit test, what's the best way to provide an activated route snapshot with mock data? When I try to create an object with just the properties I need, I get an error that it cannot be cast to ActivatedRouteSnapshot:</p>

<pre><code>it('should call foo', inject([MyResolver], async (myResolver: MyResolver) =&gt; {
  const mockRoute = {
    params: {
      val: '1234'
    };
  };

  sinon.spy(callFoo);
  myResolver.resolve(mockRoute); // This is the line that errors
  expect(callFoo.calledWith('1234')).to.be.true;
}));
</code></pre>

<p><strong>Error:</strong></p>

<pre><code>Type '{ params: { val: string; }; }' cannot be converted to type 'ActivatedRouteSnapshot'.
</code></pre>

<p>How can I provide a mock ActivatedRouteSnapshot to pass to my resolver?</p>
",https://stackoverflow.com/questions/48389002/how-to-mock-activatedroutesnapshot-when-unit-testing-a-resolver,"['angular', 'unit-testing', 'angular-router']",19465,TRUE,23,6
Unit Testing fromEvent observable with withLatestFrom,"<p>I have the following observables:</p>

<pre><code>  public ngAfterViewInit(): void {
    fromEvent(this.showFeaturesButton.nativeElement, 'click').pipe(
      takeUntil(this.ngUnsubscribe),
      withLatestFrom(this.store.pipe(select(fromClientStorage.getSubscription)))
    ).subscribe(([_event, subscription]) =&gt; {
      this.featureModal.open(FeatureListComponent, {
        data: {
          features: subscription.features
        },
      });
    });
  }
</code></pre>

<p>I am trying to test using:</p>

<pre><code>   it('should call modal when feature button is clicked', () =&gt; {
      const subscription: Subscription = ClientMock.getClient().subscription;
      spyOn(instance['store'], 'pipe').and.returnValue(hot('-a', {a: subscription.features}));
      spyOn(instance.featureModal, 'open');
      instance.ngAfterViewInit();
      instance.showFeaturesButton.nativeElement.click();
      expect(instance.featureModal.open).toHaveBeenCalledWith(FeatureListComponent, {
        data: {
          features: subscription.features
        }
      });
    });
</code></pre>

<p>However I am never hitting the subscribe which opens the modal. If I remove <code>withLatestFrom</code> like this:</p>

<pre><code>  public ngAfterViewInit(): void {
    fromEvent(this.showFeaturesButton.nativeElement, 'click').pipe(
      takeUntil(this.ngUnsubscribe)
    ).subscribe(res) =&gt; {
      this.featureModal.open(FeatureListComponent, {
        data: {
          features: res
        },
      });
    });
  }
</code></pre>

<p>Then subscribe is hit, I am just wondering what I am missing with <code>withLatestFrom</code></p>
",https://stackoverflow.com/questions/52623803/unit-testing-fromevent-observable-with-withlatestfrom,"['angular', 'unit-testing', 'observable', 'ngrx']",1760,TRUE,2,1
Unit testing entry file in React,"<p>I am writing unit tests for an entry (aka root or index) file in React. </p>

<p>No documentation seems to have been written about unit tests for entry files in React. </p>

<p>Is unit testing entry files in React necessary? Is it possible?</p>
",https://stackoverflow.com/questions/50800335/unit-testing-entry-file-in-react,"['reactjs', 'unit-testing', 'jestjs', 'entry-point']",573,TRUE,2,2
Unit testing with RxJava2 and MutableLiveData,"<p>I am trying to unit test some Android/Kotlin code that uses RxJava2. The code looks roughly as follows:</p>

<pre><code>val temperature = MutableLiveData&lt;Double&gt;()

fun save(): Single&lt;Result&lt;ClassifyResponse&gt;&gt; {
    val temp = temperature.value
    ...
    return repository.classify(request)
        .flatMap { response-&gt;
                val result: Result&lt;ClassifyResponse&gt; = Result.Success(response)
                Single.just(result)
        }.onErrorReturn {
                Result.Error(it)
        }
}
</code></pre>

<p>However, I am getting the following exception:</p>

<pre><code>java.lang.RuntimeException: Method getMainLooper in android.os.Looper not mocked. See http://g.co/androidstudio/not-mocked for details.
</code></pre>

<p>every time I run my unit test. I read a lot of <a href=""https://android.jlelse.eu/complete-example-of-testing-mvp-architecture-with-kotlin-and-rxjava-part-2-ca150c688ab1"" rel=""nofollow noreferrer"">tutorials</a> and <a href=""https://stackoverflow.com/questions/43356314/android-rxjava-2-junit-test-getmainlooper-in-android-os-looper-not-mocked-runt"">SO answers</a> but even after using the RxJavaPlugins, I still can't seem to be able to mock the main thread scheduler and the same exception prevails.</p>

<p>Could someone take a look at my unit test class and suggest what am I missing here?</p>

<pre><code>class MyViewModelTest() {

    private val repository = mock(MyRepository::class.java)

    private val immediateScheduler = object : Scheduler() {
        override fun createWorker(): Worker {
            return ExecutorScheduler.ExecutorWorker(Executor { it.run() })
        }
    }

    @Before
    fun setUp() {
        RxJavaPlugins.setInitIoSchedulerHandler { immediateScheduler }
        RxJavaPlugins.setComputationSchedulerHandler { immediateScheduler }
        RxAndroidPlugins.setInitMainThreadSchedulerHandler { immediateScheduler }
        RxAndroidPlugins.setInitMainThreadSchedulerHandler { immediateScheduler }
    }

    @Test
    fun test() {
        // given temperature view model
        val viewModel = MyViewModel(repository)
        ...

        val classifyResponse = ClassifyResponse(...)
        `when`(repository.classify(any(ClassifyRequest::class.java))).then { Single.just(classifyResponse) }

        // when sending request
        val result = viewModel.save()

        // then verify result
        val expected = Result.success(classifyResponse)

        assertEquals(expected, result)
    }
}
</code></pre>

<p>EDIT: I noticed that it is failing due to using <code>MutableLiveData</code>. When I try to access <code>temperature.value</code>, it complains about the MainLooper thread.</p>
",https://stackoverflow.com/questions/50703029/unit-testing-with-rxjava2-and-mutablelivedata,"['android', 'unit-testing', 'junit', 'kotlin', 'rx-java2']",621,TRUE,2,1
Mocha unit testing a mongoose model,"<p>I'm trying to do a simple test of my mongoose model with mocha and chai</p>

<pre><code>// Mock user
  var testUser = new User({
    companyID: ""1"",
    username: ""mockUser"",
    password: ""password"",
    email: ""a@valid.email"",
  });

// Create new user
it('Should add a new user with a hashed password to DB' , (done) =&gt; {
  User.addUser(testUser, (err, user) =&gt; {
    if(err) console.log(err);
    else {
      assert.typeOf(user, 'Object');
      assert.equal(user.username, ""mockUser"");
      expect(user.password).to.not.equal(""password"");
    }
    done();
  });
});
</code></pre>

<p>Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure ""done()"" is called; if returning a Promise, ensure it resolves</p>

<p>I assume mocha changed since this has been working with previous projects.
What am i missing here ?</p>

<p>the model method: </p>

<pre><code>module.exports.addUser = function(newUser, callback) {
  bcrypt.genSalt(10, (err, salt) =&gt; {
    bcrypt.hash(newUser.password, salt, (err, hash) =&gt; {
      if (err) throw err;
      newUser.password = hash;
      newUser.save(callback);
    });
  });
}
</code></pre>
",https://stackoverflow.com/questions/53593508/mocha-unit-testing-a-mongoose-model,"['node.js', 'unit-testing', 'mongoose', 'mocha.js', 'chai']",811,TRUE,2,2
Angular 5 Local Storage Unit Testing,"<p>I am getting an error '<strong>SyntaxError: Unexpected token u in JSON at position 0</strong>'  in Jasmin Karma Angular testing. I recoginzed that this error is due to local storage JSON parsing. Also I am getting '<strong>ERROR in src/app/projects/project-details/project-details.component.spec.ts(77,40): error TS2304: Cannot find name 'm'.</strong>' in the console. </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.RowSelected = JSON.parse(localStorage['ProjectArray']);</code></pre>
</div>
</div>
</p>

<p>I tried  changing my component code to the below, JSON U Token seems to gone but a new error seems to throw like 'Typerror: cannot read property 'projectId' as null'. Can someone help me in mocking local storage for my app. 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>this.RowSelected = JSON.parse(localStorage['ProjectArray'] || null);</code></pre>
</div>
</div>
</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 { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { ProjectDetailsComponent } from './project-details.component';
import { FormsModule } from '@angular/forms';
import { BsDatepickerModule } from 'ngx-bootstrap';
import { ProjectSearchService } from '../../core/project-services/project-search.service';
import { StoreDataService } from '../../core/project-services/store-data.service';
import { RouterTestingModule } from '@angular/router/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { HttpClient, HttpHeaders } from '@angular/common/http';

describe('ProjectDetailsComponent', () =&gt; {
  let component: ProjectDetailsComponent;
  let fixture: ComponentFixture&lt;ProjectDetailsComponent&gt;;

  
  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [ FormsModule, BsDatepickerModule, HttpClientTestingModule, RouterTestingModule.withRoutes([]) ],
      schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
      declarations: [ ProjectDetailsComponent ],
      providers: [StoreDataService, ProjectSearchService]
    })
    .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(ProjectDetailsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    function storageMock() {
    var storage = {};
      return {
      setItem: function(key, value) {
        storage[key] = value || '';
      },
      getItem: function(key) {
        return key in storage ? storage[key] : null;
      },
      removeItem: function(key) {
        delete storage[key];
      },
      get length() {
        return Object.keys(storage).length;
      },
      key: function(i) {
        var keys = Object.keys(storage);
        return keys[i] || null;
      }
    };
  }
    let mockConfig = JSON.stringify({
            projectId: ""015104072"",
            csj: ""015104072"",
            ccsj: ""015104072"",
            controlSection: ""015104"",
            projectType: ""Construction"",
            projectSubtype: ""Roadway"",
            district: ""Austin"",
            county: ""Williamson"",
            assignedTo: null,
            projectStatus: ""Active"",
            projectStage: ""Ready to Let"",
            projectClassification: ""Intersection &amp; Operational Imprv"",
            letScheduleFiscalYear: ""2018"",
            dateCreated: ""2018-07-20"",
            highway: ""US 183""
  });
  //Set storage
 let m =  storageMock();
 m.setItem('ProjectArray', mockConfig);
  
    Object.defineProperty(window, 'localStorage', { value: m });
  });

  it('should create', () =&gt; {
    component.RowSelected = JSON.parse(m.getItem('ProjectArray'));
  });
});</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/51467905/angular-5-local-storage-unit-testing,"['javascript', 'angular', 'local-storage', 'karma-jasmine']",2873,FALSE,2,0
unit testing of many simple *ngIf,"<p>I have simply component</p>

<pre><code>@Component({
    selector: 'app-certificate-panel',
    templateUrl: './certificate.component.html'
})
export class CertificateComponent {
    @Input()
    public certificate: Certificate;
}
</code></pre>

<p>with template</p>

<pre><code>&lt;h3 translate&gt;General&lt;/h3&gt;
&lt;x-form-row label=""{{'Version' | translate}}""&gt;
    {{ certificate.version }}
&lt;/x-form-row&gt;
&lt;x-form-row label=""{{'Serial Number' | translate}}""&gt;
    {{ certificate.serialNumber }}
&lt;/x-form-row&gt;
&lt;h3 translate&gt;Issued From&lt;/h3&gt;
&lt;x-form-row label=""{{'Common Name (CN)' | translate}}"" *ngIf=""certificate.issuedFrom.commonName""&gt;
    {{ certificate.issuedFrom.commonName }}
&lt;/x-form-row&gt;
&lt;x-form-row label=""{{'Organization Unit (OU)' | translate}}"" *ngIf=""certificate.issuedFrom.organizationUnit""&gt;
    {{ certificate.issuedFrom.organizationUnit }}
&lt;/x-form-row&gt;
</code></pre>

<p>There are more properties shown. There are several <code>*ngIf</code> in this template.</p>

<p>Now I want to write unit tests. Should I test each <code>*ngIf</code>? Isn't it testing the framework functionality?</p>
",https://stackoverflow.com/questions/50136035/unit-testing-of-many-simple-ngif,"['angular', 'unit-testing', 'typescript', 'angular-test']",1483,TRUE,2,1
Error while doing Angular Unit Testing,"<p>I am facing an error while doing Angular unit testing. I am trying to test create component 
Please see error below file and let me know why I am facing that, 
I also import the services related with the providers and imports for the module.</p>

<p>the below error is shown by Karma while unit testing. I think I am missing something</p>

<pre><code>TypeError: Cannot read property 'userName' of undefined
at Object.eval [as updateRenderer] (ng:///DynamicTestModule/ProfilePersonalInformationComponent.ngfactory.js:72:38)
at Object.debugUpdateRenderer [as updateRenderer] (webpack:///./node_modules/@angular/core/esm5/core.js?:14909:21)
at checkAndUpdateView (webpack:///./node_modules/@angular/core/esm5/core.js?:14023:14)
at callViewAction (webpack:///./node_modules/@angular/core/esm5/core.js?:14369:21)
at execEmbeddedViewsAction (webpack:///./node_modules/@angular/core/esm5/core.js?:14327:17)
at checkAndUpdateView (webpack:///./node_modules/@angular/core/esm5/core.js?:14019:5)
at callViewAction (webpack:///./node_modules/@angular/core/esm5/core.js?:14369:21)
at execEmbeddedViewsAction (webpack:///./node_modules/@angular/core/esm5/core.js?:14327:17)
at checkAndUpdateView (webpack:///./node_modules/@angular/core/esm5/core.js?:14019:5)
at callViewAction (webpack:///./node_modules/@angular/core/esm5/core.js?:14369:21)
</code></pre>

<p>To solve above error, I created PerosnalInfoStub class but it didnt work.</p>

<p>component.spec.ts file</p>

<pre><code>describe('ProfilePersonalInformationComponent', () =&gt; {
  let component: ProfilePersonalInformationComponent;
  let fixture: ComponentFixture&lt;ProfilePersonalInformationComponent&gt;;
  let personalInfo : PersonalInfo;

  class PersonalInfoStub{
      personalInfo: Subject&lt;any[]&gt; = new Subject&lt;any[]&gt;();



  }

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({

        imports: [FormsModule, SharedModule, HttpModule, BrowserModule],
      declarations: [ ProfilePersonalInformationComponent ],
      providers: [
        {
           provide: PersonalInfo, useClass: PersonalInfo
        },

        {
            provide: NotificationService, useClass: NotificationService
        },

        {
            provide: LoginService, useClass: LoginService
        },
        {
            provide: ConfigService, useClass: ConfigService
        }

    ],


    })
    .compileComponents();
  }));

  beforeEach(() =&gt; {

    fixture = TestBed.createComponent(ProfilePersonalInformationComponent);
    component = fixture.componentInstance;

    fixture.detectChanges();
  });

  it('should create', () =&gt; {

    expect(component).toBeTruthy();
  });
</code></pre>

<p>personal-info.ts</p>

<pre><code>export class PersonalInfo {
  userName: string;
}
</code></pre>

<p>class file of component</p>

<pre><code>ProfilePersonalInformationComponent implements OnInit {




  @Input() personalInfo: PersonalInfo;
  @Input() loadingData;
  savingData: boolean;

  passwordHelpTextArray: string[];
  passwordHelpText: string;
  formErrors: any = {
    username: {
      error: '',
      errorMessage: ''
    },
    currentPassword: {
      error: '',
      errorMessage: ''
    },
    newPassword: {
      error: '',
      errorMessage: ''
    },
    verifyNewPassword: {
      error: '',
      errorMessage: ''
    }
  };

  updatedUsername: string = '';
  existingPassword: string = '';
  newPassword: string = '';
  reEnterNewPassword: string = '';

  constructor(private personalInfoService: PersonalInformationService,
    private notificationService: NotificationService) { }

  ngOnInit(): void {
    this.populateInfo();
  }

  populateInfo() {
    setTimeout(() =&gt; {
      if (this.loadingData === false) {
        this.updatedUsername = this.personalInfo.userName;
      } else {
        this.populateInfo();
      }

    }, 500);
  }
</code></pre>

<p>Html code for User Name</p>

<pre><code> &lt;div class=""col-sm-2""&gt;
        &lt;h3&gt;Username&lt;/h3&gt;
        &lt;p&gt;{{personalInfo.userName}}&lt;/p&gt;
      &lt;/div&gt;
      &lt;div class=""col-sm-2""&gt;
        &lt;h3&gt;Password&lt;/h3&gt;
        &lt;p&gt;********&lt;/p&gt;
      &lt;/div&gt;
</code></pre>
",https://stackoverflow.com/questions/50728302/error-while-doing-angular-unit-testing,"['angular', 'unit-testing', 'typescript', 'angular5', 'karma-jasmine']",1173,TRUE,2,1
Aurelia unit testing access component&#39;s viewModel,"<p>I am unit testing one of my components in an Aurelia project. I'd like to access my component's viewModel in my unit test but haven't had any luck so far.</p>

<p>I followed the example available at <a href=""https://aurelia.io/docs/testing/components#manually-handling-lifecycle"" rel=""nofollow noreferrer"">https://aurelia.io/docs/testing/components#manually-handling-lifecycle</a> but I keep getting <code>component.viewModel</code> is <code>undefined</code>.</p>

<p>Here is the unit test:</p>

<pre><code>describe.only('some basic tests', function() {
    let component, user;

    before(() =&gt; {
        user = new User({ id: 100, first_name: ""Bob"", last_name: ""Schmoe"", email: 'joe@schmoe.com'});
        user.save();
    });

    beforeEach( () =&gt; {
        component = StageComponent
            .withResources('modules/users/user')
            .inView('&lt;user&gt;&lt;/user&gt;')
            .boundTo( user );
    });

    it('check for ', () =&gt; {
        return component.create(bootstrap)
            .then(() =&gt; {
                expect(2).to.equal(2);
                return component.viewModel.activate({user: user});
            });

    });

    it('can manually handle lifecycle', () =&gt; {

        return component.manuallyHandleLifecycle().create(bootstrap)
            .then(() =&gt; component.bind({user: user}))
            .then(() =&gt; component.attached())
            .then(() =&gt; component.unbind() )
            .then(() =&gt; {
                expect(component.viewModel.name).toBe(null);
                return Promise.resolve(true);
        });
    });

    afterEach( () =&gt; {
        component.dispose();
    });
});
</code></pre>

<p>Here is the error I get:</p>

<pre><code>1) my aurelia tests
       can manually handle lifecycle:
     TypeError: Cannot read property 'name' of undefined
</code></pre>

<p><a href=""https://github.com/aurelia/testing/blob/0635bade27d270c93cd7e4fe3d8ee1e8051569b0/dist/native-modules/component-tester.js#L54"" rel=""nofollow noreferrer"">Here</a> is the the line that defines the <code>viewModel</code> on the <code>component</code> object but only if <code>aurelia.root.controllers.length</code> is set. I am not sure how to set controllers in my aurelia code or if I need to do so at all.</p>

<p>I guess my question is:
How do I get access to a component's viewModel in my unit tests?</p>
",https://stackoverflow.com/questions/52975104/aurelia-unit-testing-access-components-viewmodel,"['unit-testing', 'aurelia']",966,TRUE,2,2
(How to Think like a Computer Scientist - 6.3 Unit Testing) Unit Testing using test vs unittest,"<p>The sample code in the book uses the test module shown here:</p>

<pre><code>def square(x):
    '''raise x to the second power'''
    return x * x

import test
print('testing square function')
test.testEqual(square(10), 100)
</code></pre>

<p>However, when I write out the script and use IDLE to run it I get the following error:</p>

<pre><code>testing square function
Traceback (most recent call last):
  File ""/Users/ivan/Documents/scripts/Untitled.py"", line 7, in &lt;module&gt;
    test.testEqual(square(10), 100)
AttributeError: module 'test' has no attribute 'testEqual'
</code></pre>

<p>Checking the Global Module Index > test module shows that the preferred method is to use the unittest module. Here is the given example:</p>

<pre><code>import unittest

class TestStringMethods(unittest.TestCase):

    def test_upper(self):
        self.assertEqual('foo'.upper(), 'FOO')

    def test_isupper(self):
        self.assertTrue('FOO'.isupper())
        self.assertFalse('Foo'.isupper())

    def test_split(self):
        s = 'hello world'
        self.assertEqual(s.split(), ['hello', 'world'])
        # check that s.split fails when the separator is not a string
        with self.assertRaises(TypeError):
            s.split(2)

if __name__ == '__main__':
    unittest.main()
</code></pre>

<p>The problem is that we have not learned anything past import unittest as seen in this example.</p>

<p>Is there a way to use the unittest module as given in the first script in this question?</p>
",https://stackoverflow.com/questions/48154619/how-to-think-like-a-computer-scientist-6-3-unit-testing-unit-testing-using-t,"['python', 'unit-testing']",522,TRUE,0,1
Unit testing support for Corda.v2 Contract?,"<p>I'm using Corda V2 (in Java) and have a Contract in desperate need of a unit test.  But quickly going down a rabbit hole of trying to reverse engineer the creation of a <code>net.corda.core.transactions.LedgerTransaction</code>.  Is there any framework support for testing <code>MyContract</code> method <code>verify()</code>?</p>

<pre><code>public class MyContract implements Contract {
// This is used to identify our contract when building a transaction.
public static final String MY_CONTRACT_ID = ""com.exchange.data.address.MyContract"";

// Our Create command.
public static class Create implements CommandData {
}

@Override
public void verify(LedgerTransaction tx) {
    final CommandWithParties&lt;MyContract.Create&gt; command = requireSingleCommand(tx.getCommands(), MyContract.Create.class);

    requireThat(check -&gt; {
        // Constraints on the shape of the transaction.
        check.using(""No inputs should be consumed when exchanging data."", tx.getInputs().isEmpty());
        check.using(""There should be one output state of type MyState."", tx.getOutputs().size() == 1);

        final MyState out = tx.outputsOfType(MyState.class).get(0);
        final Party sender = out.getSender();
        final Party receiver = out.getReceiver();
        check.using(""The sender and the receiver cannot be the same entity."", !sender.getName().equals(receiver.getName()));

        // Constraints on the signers.
        final List&lt;PublicKey&gt; signers = command.getSigners();
        check.using(""There must be two signers."", signers.size() == 2);
        check.using(""The sender and receiver must be signers."", signers.containsAll(
                ImmutableList.of(sender.getOwningKey(), receiver.getOwningKey())));

        return null;
    });
}
</code></pre>
",https://stackoverflow.com/questions/49302682/unit-testing-support-for-corda-v2-contract,"['java', 'unit-testing', 'corda']",91,TRUE,1,1
Mock requests in TYPO3 unit testing,"<p>Is it possible to mock client (POST or GET) requests in unit testing using the TYPO3 testing framework with phpunit? I'm looking for something like the static::createClient() of Symfony.</p>

<p>UPDATE: Looking at <a href=""https://stackoverflow.com/questions/1935541/phpunit-test-mvc-controller-with-post-variable"">PHPUnit - test MVC controller with $_POST variable</a> I found the simple solution of just adding to the $_POST array the expected content. Question can be closed.</p>
",https://stackoverflow.com/questions/50628004/mock-requests-in-typo3-unit-testing,"['unit-testing', 'phpunit', 'typo3']",157,FALSE,1,0
Unit testing REST endpoints in Django,"<p>I am pretty new to Django and web development in general. I decided to learn by creating a simple web app for posting and displaying college reviews. I have a number of GET and POST endpoints that I want to test.</p>

<p>In the past, I have developed APIs where endpoints returned JSON objects that I could assert on when doing my API endpoint testing. However, in this case, my Django app returns HTML.</p>

<p>The first issue I encountered was that my HTML sometimes contains dynamic values that I cannot assert on. For example, the <code>csrf_token</code> which is located in my forms. Here is part of the HTML file for the university details page:</p>

<pre><code>...
&lt;form action=""{% url 'university_add_review' university.id %}"" method=""post""&gt;
    {% csrf_token %}
    &lt;p&gt;Date:&lt;/p&gt;&lt;input type=""date"" name=""date"" id=""date""/&gt;
    &lt;p&gt;Summary:&lt;/p&gt;&lt;textarea name=""summary"" id=""summary""&gt;Enter your summary here.&lt;/textarea&gt;
    &lt;input type=""submit"" value=""Submit""/&gt;
&lt;/form&gt;
...
</code></pre>

<p>In my unit tests, I want to check that a <code>GET</code> request to that page is getting the correct contents:</p>

<pre><code>def test_get_university_details(self):
    response = Client().get('/%s/overview/' % self.university.id)

    self.assertEqual(response.content, expected)
</code></pre>

<p>Where <code>expected</code> is the expected HTML. However, that fails because the <code>csrf_token</code> is different in every <code>GET</code> request so I can't have an expected value for it. As a result this test fails:</p>

<pre><code>Traceback (most recent call last):
  File "".../tests.py"", line 47, in test_get_university_details
    self.assertEqual(response.content, expected)
AssertionError: b'\n\[384 chars]ue=\'wrG24VMcdpYYOMECnibQrElP1km9YU0WeOMedGJ2C[488 chars]orm&gt;' != b'\n\[384 chars]ue=\'QWCWACcNQwbfOx9M3iLFt77nSIKhUMiK5i1I4a5mD[530 chars]on&gt; '
</code></pre>

<p>So my two questions are:</p>

<ol>
<li>What is a solution for this? Could I ignore certain parts of the HTML?</li>
<li>Is testing the contents of the HTML a good practice when testing Django applications? Should I instead be testing in a different way?</li>
</ol>
",https://stackoverflow.com/questions/53364546/unit-testing-rest-endpoints-in-django,"['python', 'django', 'testing']",779,TRUE,1,1
Unit testing Rx binding with UITextView,"<p>I have a ControlProperty binding like this in my UIViewController:</p>

<pre><code>textView.rx.text.orEmpty.asObservable()
    .bind(to: viewModel.descriptions)
    .disposed(by: disposeBag)
</code></pre>

<p>, where <code>viewModel.descriptions</code> is of type <code>BehaviorRelay&lt;String&gt;</code>.</p>

<p>In a TDD approach, I would like to write an (initially failing) test (as the initial step of the red-green-refactor cycle) to see that this binding exists. I tried with a test code like this:</p>

<pre><code>sut.textView.insertText(""DESC"")
sut.textView.delegate?.textViewDidChange?(sut.textView)

expect(mockViewModel.lastDescriptions).to(equal(""DESC""))
</code></pre>

<p>, where <code>sut</code> is my ViewController and <code>mockViewModel</code> contains code to subscribe to the <code>descriptions</code> <code>BehaviorRelay</code>:</p>

<pre><code>class MockViewModel: MyViewModelProtocol {
    var descriptions = BehaviorRelay&lt;String&gt;(value: """")
    var lastDescriptions: String?
    private var disposeBag = DisposeBag()

    init() {            
        descriptions.asObservable()
            .skip(1)
            .subscribe(onNext: { [weak self] (title: String) in
                self?.lastDescriptions = title
            })
            .disposed(by: disposeBag)
    }
}
</code></pre>

<p>However, I cannot push the new value to the <code>textView</code> so that the <code>descriptions</code> <code>BehaviorRelay</code> gets it.</p>

<p>How can I achieve <code>descriptions.asObservable()</code> to fire when entering a value in the <code>textView</code>? If it were a <code>UITextField</code> then I would do:</p>

<pre><code>textField.text = ""DESC""
textField.sendActions((for: .editingChanged))
</code></pre>

<p>Thanks in advance for any help.</p>
",https://stackoverflow.com/questions/52621483/unit-testing-rx-binding-with-uitextview,"['ios', 'unit-testing', 'uitextview', 'rx-swift', 'rx-cocoa']",500,FALSE,1,0
Unit testing serial port in java,"<p>I have a program that is communicating with a hardware serial port sensor.
I use jssc as a connection abstraction library.</p>

<p>I would like to crate a virtual serial port test class I can use to test my real production code without a hardware sensor.</p>

<p>How do I mock/fake/virtualise a serial port in unit tests?
Can it be done in java?</p>
",https://stackoverflow.com/questions/50276198/unit-testing-serial-port-in-java,"['java', 'junit', 'serial-port', 'jssc']",667,FALSE,1,1
Unit-testing a custom CLion plugin,"<p>I am currently developing a plugin for CLion, and wanted to know if there is any way of using Intellijs testing framework for plugins.</p>

<p>I am talking about classes like <code>LightPlatformCodeInsightFixtureTestCase</code> and <code>LightCodeInsightFixtureTestCase</code> which I don't seem to find, if I use CLion as Intellij Platform Plugin SDK. Using CLion as plugin SDK is crucial, as I'm working with classes like <code>CMakeProfile</code> and <code>CidrLauncher</code>.</p>

<p>Some additional information: I am using <em>CLion CL-181.5281.33 (java version ""1.1.0_60"")</em>. The package <code>com.intellij.testFramework</code> does not seem to include the <code>fixtures</code> package.</p>

<p>If I switch to <em>IntelliJ IDEA Community Edition IC-181.5281.24 (java version ""1.8.0_60"")</em> as my project SDK I can import the classes and my project builds.</p>

<p>Am I missing something or can I simply not use the intellij test framework for my clion plugin?</p>
",https://stackoverflow.com/questions/51169380/unit-testing-a-custom-clion-plugin,"['unit-testing', 'testing', 'clion', 'intellij-plugin']",112,FALSE,1,1
Unit testing in typescript with mocha,"<p>I'm starting with unit testings and I'd like to unit test my routes with sinon and mocha</p>

<p>My controller looks like this :</p>

<pre><code>import { NextFunction, Request, Response, Router } from 'express';


export default class Sample {

  constructor(a: string) {
    console.error('constructor',a);
  }

  public getAll(req: Request, res: Response, next: NextFunction) {
    res.json('OK');
  }
}
</code></pre>

<p>This is what I did so far to test it :</p>

<pre><code>import { expect } from 'chai';
import 'mocha';
import * as sinon from 'sinon';  

import Sample from './../controllers/Sample';
import { Response, Request, NextFunction } from 'express';

describe('Hello function', () =&gt; {

  it('should return hello world', async () =&gt; {
    const sample = new Sample('sample');

    const req: Partial&lt;Request&gt; = {};
    const res: Partial&lt;Response&gt; = {
      json: sinon.stub(),
    };
    const next: Partial&lt;NextFunction&gt; = {};

    await sample.getAll(&lt;Request&gt;req, &lt;Response&gt;res, &lt;NextFunction&gt; next);
    const expectedResult = 'OK';

    sinon.assert.calledWith(
      res.render as sinon.SinonStub, 
      'OK');      

  });

});
</code></pre>

<p>However I got the following error :</p>

<pre><code>constructor sample
    1) should return hello world


  0 passing (39ms)
  1 failing

  1) Hello function
       should return hello world:
     AssertError: fake is not a spy
      at Object.fail (node_modules/sinon/lib/sinon/assert.js:96:21)
</code></pre>

<p>What am I doing wrong ?</p>
",https://stackoverflow.com/questions/49779648/unit-testing-in-typescript-with-mocha,"['typescript', 'mocha.js', 'sinon']",660,TRUE,1,1
Unit Testing RxJava doOnSubscribe and doFinally,"<p>How do I create a unit test that a certain side effect is done on <code>doOnScubscribe</code> and <code>doFinally</code> of an rxjava chain?</p>
<p>For Example:</p>
<pre class=""lang-java prettyprint-override""><code>Observable.requestSomeValueFromWeb()
            .doOnSubscribe(() -&gt; showLoading = true)
            .doFinally(() -&gt; showLoading = false)
            .subscribe(result -&gt; doSomething(result), error -&gt; doErrorHandling(error));
</code></pre>
<p>How do I test in the scenario above that the <code>showLoading</code> was set to true on subscribe and false when the observable was disposed?</p>
<pre class=""lang-java prettyprint-override""><code>TestSubscriber&lt;WebServiceResponse&gt; loginRequestSubscriber = new TestSubscriber&lt;&gt;();

clientLoginViewModel.requestLogin().subscribe(loginRequestSubscriber);

// check that showLoading was true when webservice was called
assertEquals(true, showLoading);

// check that showLoading was false when webservice was finished
assertEquals(false, showLoading);

loginRequestSubscriber.assertSubscribed();
</code></pre>
",https://stackoverflow.com/questions/48980897/unit-testing-rxjava-doonsubscribe-and-dofinally,"['unit-testing', 'testing', 'rx-java2']",1838,TRUE,1,1
spring boot unit testing using testng,"<p>How to write a POST method test case if the return type of a particular create method in the service layer is <code>ResponseEntity&lt;Object&gt;</code>?</p>

<p>This is my <code>createOffer</code> method:</p>

<pre><code>public ResponseEntity&lt;Object&gt; createOffer(Offer offer) {
    Offer uoffer = offerRepository.save(offer);


    URI location = ServletUriComponentsBuilder.fromCurrentRequest().path(""/{jobTitle}"").
                    buildAndExpand(uoffer.getJobTitle()).toUri();

    return ResponseEntity.created(location).build();

}
</code></pre>

<p>and this is its corresponding test class method:</p>

<pre><code>@Test
public void testCreateOffer() {
    Offer offer = new Offer(""SE"",new Date(),5);
    Mockito.when( offerRepository.save(offer)).thenReturn( offer);
    assertThat(offerServiceImpl.createOffer(offer)).isEqualTo(offer);
}
</code></pre>

<p>Here I am getting an error while running this test case which is no current servlet request attributes and exception is:</p>

<blockquote>
  <p>java.lang.IllegalStateException</p>
</blockquote>

<p>Why is it coming </p>
",https://stackoverflow.com/questions/52903080/spring-boot-unit-testing-using-testng,"['spring-boot', 'testng']",2579,TRUE,1,3
Laradock unit testing database errors PDOException,"<p>So I'm trying to write unit tests for a Laravel application like this:</p>

<pre><code>protected function setUp()
{
    parent::setUp();
    $this-&gt;disableMiddlewareForAllTests();
    $this-&gt;withoutExceptionHandling();
}

public function test_login_badRequest()
{
    $response = $this-&gt;call('post', '/login');
    $response-&gt;assertOk();
    $response-&gt;assertJson(['status' =&gt; 400]);
}
</code></pre>

<p>The above works fine, and gives this output:</p>

<pre><code>Test 'Tests\Unit\LoginTest::test_login_badRequest' started
Test 'Tests\Unit\LoginTest::test_login_badRequest' ended
Time: 69 ms, Memory: 12.00MB
OK (1 test, 2 assertions)
</code></pre>

<p>But the next test is another story:</p>

<pre><code>public function test_login_goodRequest()
{
    $response = $this-&gt;call('post', '/login', [
        'email' =&gt; 'email@email.com',
        'password' =&gt; 'P4ssw0rd'
    ]);

    $response-&gt;assertOk();
    $response-&gt;assertJson(['status' =&gt; 200]);
}
</code></pre>

<p>As soon as the test hits this line of code in the application:</p>

<pre><code>/* Retrieve User associated with posted email address */
$user = $this-&gt;userModel
    -&gt;where('email', $request-&gt;post('email'))
    -&gt;get();
die('here');// &lt;-- Happens in browser, does not happen in tests.
</code></pre>

<p>This is the error:</p>

<pre><code>1) Tests\Unit\LoginTest::test_login_goodRequest
PDOException: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known
/var/www/html/projects/laravel-template/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php:68 ...
</code></pre>

<p>I've been banging my head against this one for a few days, any ideas what's going on here, and how to get that die to print in the tests?
Cheers.</p>

<p>-- Laradock, Docker, nginx, mysql,
PHP 7.2.4-1+ubuntu16.04.1+deb.sury.org+1 (cli) (built: Apr  5 2018 08:53:57) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.2.4-1+ubuntu16.04.1+deb.sury.org+1, Copyright (c) 1999-2018, by Zend Technologies</p>

<p>EDITED:</p>

<p>.env:</p>

<pre><code>APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:Z+p6uA3G2DyCCFBXOPgrWwls1U6z/vi8Zi2r4eKHxEY=
APP_DEBUG=true
DEBUGBAR_ENABLED=true
APP_URL=http://localhost

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=sample_database
DB_USERNAME=root
DB_PASSWORD=root

BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
SESSION_LIFETIME=120
QUEUE_DRIVER=sync

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=
MAIL_PASSWORD=
MAIL_ENCRYPTION=tls

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1

MIX_PUSHER_APP_KEY=""${PUSHER_APP_KEY}""
MIX_PUSHER_APP_CLUSTER=""${PUSHER_APP_CLUSTER}""
</code></pre>
",https://stackoverflow.com/questions/52455914/laradock-unit-testing-database-errors-pdoexception,"['php', 'mysql', 'unit-testing', 'docker', 'laradock']",821,TRUE,1,1
Unit testing angularjs $watch in Jasmine,"<p>I'm pretty new to <code>AngularJS</code> and even newer to unit tests in <code>Jasmine</code>. I have to write a test for:</p>

<pre><code>$scope.$watch(
function () {
    return alertService.getAlert();
},
function (newVal, oldVal)
{
    if (typeof newVal !== 'undefined') {
        $scope.alert = alertService.getAlert();
    }
});
</code></pre>

<p><code>getAlert</code> returns things like:</p>

<pre><code>[ Object({ type: 'typeOfAlert', message: 'alertMessage' }) ].
</code></pre>

<p>Now, I've learned (in some cases even understood) things about digest, timeouts, mocking services etc. but I only know how to handle variable-fired watches and I'm not sure what to do with:</p>

<pre><code>alertService.getAlert();
</code></pre>

<p>Could anyone give me a hand?</p>
",https://stackoverflow.com/questions/52146316/unit-testing-angularjs-watch-in-jasmine,"['angularjs', 'jasmine', 'karma-jasmine', 'watch']",1119,TRUE,1,1
Unit Testing WCF Service using Moq,"<p>I have been teaching myself how to unit test various parts of my application. I am trying to do a unit test of my UserService. I seem to be getting the following error:
<a href=""https://i.stack.imgur.com/VRN4n.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/VRN4n.png"" alt=""User Service Error""></a></p>

<p>I am not sure what the error means. Could someone explain what is going on? I know the service itself works already I tested it separately. I have never created unit tests before so if someone could please give me a detailed explanation as to why this is happening?</p>

<p>Thanks in advance!</p>

<p><strong>User Service Test</strong></p>

<pre><code>public class UserServiceTest
{
    public readonly IUserService MockUserService;


    public List&lt;UserDTO&gt; userDTOList = new List&lt;UserDTO&gt;
    {
        new UserDTO(new User{UserId = 1, FirstName = ""Eric""}),
        new UserDTO(new User{UserId = 1, FirstName = ""Dave""}),
        new UserDTO(new User{UserId = 1, FirstName = ""Jim""})

    };

    public UserServiceTest()
    {
        Mock&lt;IUserService&gt; mockUserService = new Mock&lt;IUserService&gt;();

        mockUserService.Setup(mr =&gt; mr.GetAllUsers()).Returns(userDTOList);
        this.MockUserService = mockUserService.Object;

    }

    [TestMethod]
    public void TestServiceGetUsers()
    {
        List&lt;UserDTO&gt; testUserList = this.MockUserService.GetAllUsers();

        Assert.IsNotNull(testUserList);
        Assert.AreEqual(userDTOList, testUserList);
    }
}
</code></pre>

<p><strong>WCF Interface</strong></p>

<pre><code> [ServiceContract]
public interface IUserService
{
    [OperationContract]
    List&lt;UserDTO&gt; GetAllUsers();

}

[DataContract]

public class UserDTO
{
    public UserDTO(User user)
    {
        this.FirstName = user.FirstName;
        this.LastName = user.LastName;
        this.NumberOfItemsSold = user.NumberOfItemsSold;
        this.UserId = user.UserId;
        this.UserName = user.UserName;

    }

    [DataMember]
    public int UserId { get; set; }

    [DataMember]
    public string FirstName { get; set; }

    [DataMember]
    public string LastName { get; set; }

    [DataMember]
    public string UserName { get; set; }

    [DataMember]
    public int NumberOfItemsSold { get; set; }
}
</code></pre>

<p><strong>WCF Interface implementation</strong></p>

<pre><code>public class UserService : IUserService
{
    public List&lt;UserDTO&gt; GetAllUsers()
    {
        using (UnitOfWork work = new UnitOfWork(new ProductContext()))
        {

            return work.Users.GetAll().Select(a =&gt; new UserDTO(a)).ToList();
        }
    }
}
</code></pre>

<p><strong>Edit after suggestion from Mel Gerats</strong></p>

<p>Okay so I figured I would place the updated code for my unit test that actually tests the service now. Here it is! Thanks again for the help.</p>

<pre><code>[TestClass]
public class UserServiceTest
{

    public List&lt;UserDTO&gt; userDTOList = new List&lt;UserDTO&gt;
    {
        new UserDTO(new User{UserId = 1, FirstName = ""Eric""}),
        new UserDTO(new User{UserId = 2, FirstName = ""Dave""}),
        new UserDTO(new User{UserId = 3, FirstName = ""Jim""})

    };

    public IEnumerable&lt;User&gt; users = new List&lt;User&gt;
    {
        new User{UserId = 1, FirstName = ""Eric""},
        new User{UserId = 2, FirstName = ""Dave""},
        new User{UserId = 3, FirstName = ""Jim""}
    };

    [TestMethod]
    public void TestServiceGetUsers()
    {
        //Setup
        var unitOfWorkMock = new Mock&lt;IUnitOfWork&gt;();
        unitOfWorkMock.Setup(m =&gt; m.Users.GetAll()).Returns(users);

        var serviceUnderTest = new UserService(unitOfWorkMock.Object);



        var result = serviceUnderTest.GetAllUsers();

        Assert.IsNotNull(result);

        Assert.AreEqual(userDTOList.Count, result.Count);
        Assert.AreEqual(userDTOList[0].FirstName, result[0].FirstName);
        Assert.AreEqual(userDTOList[1].FirstName, result[1].FirstName);
    }
}
</code></pre>

<p>For some reason I could not directly test if the two lists were equal. I think it is because the Capacity of the lists were different on my lists. So I opted for testing each position in the list.</p>
",https://stackoverflow.com/questions/51774832/unit-testing-wcf-service-using-moq,"['c#', 'unit-testing', 'wcf', 'moq']",1600,TRUE,1,1
Getting Started Unit Testing Xamarin iOS,"<p>My question is about UI testing for Xamarion.iOS and Xamarion.Android.</p>

<p>I have an app for Android and iOS built using Xamarin.Android and Xamarin.iOS with a PCL.  These were not made using Xamarin.Forms.<br>
I've been trying to start UI unit testing the apps and I've read over NUnit, NUnitLite, and Xamarin.UITest and looking through guides on how to get the testing started but have been unsuccessful at starting my app's UI.</p>

<p>When I build a project with Xamarin.UITest, the Platform class does not exist and when attempting to do an Android test while pointing the app to the apk file, it wasn't successful.</p>

<p>I have created test projects for NUnit 3 platform-specific testing following this guide: <a href=""http://www.alteridem.net/2015/12/21/testing-xamarin-projects-using-nunit-3/"" rel=""nofollow noreferrer"">http://www.alteridem.net/2015/12/21/testing-xamarin-projects-using-nunit-3/</a> I can run the app, get to the page showing the tests passed/failed, but after that, I've been unable to wire up the UI.</p>

<p>I have not found any documentation on how to do UI testing in either Android or iOS. I've been over the MS's docs like on <a href=""https://learn.microsoft.com/en-us/xamarin/ios/deploy-test/touch.unit?tabs=vswin"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/xamarin/ios/deploy-test/touch.unit?tabs=vswin</a> </p>

<p>Can anyone shed some light on how I can start a simple UI test?  Preferably with NUnit 3.</p>
",https://stackoverflow.com/questions/52376184/getting-started-unit-testing-xamarin-ios,"['ios', 'unit-testing', 'xamarin']",473,TRUE,1,1
"Angular unit testing, for Observable errors","<p>I am trying to errors in code coverage for service calls.
I am following two approaches but doing some mistake.</p>

<p>below is my method for which I am writing test cases</p>

<pre><code>setPrefixSuffixDetails(): void {
    this.prefixSuffixDetailSubscription = this.profileBeneficiaryService.getPrefixSuffixDetails()
      .subscribe(data =&gt; {
        if (data.body.prefixlist.length &gt; 0) {
          this.prefixConfig.options = data.body.prefixlist;
        }
        if (data.body.suffixlist.length &gt; 0) {
          this.suffixConfig.options = data.body.suffixlist;
        }
      }, error =&gt; {
        this.loadingData = false;
        this.notificationService.addNotications(error);
      });
  }
</code></pre>

<p>For testing, I am creating providers, below are my providers</p>

<pre><code> { provide: ProfileBeneficiaryService, useClass: ProfileServiceStub},
{provide: ProfileBeneficiaryService, useClass: ProfileBenficiaryErrorStub},
</code></pre>

<p>one is for success call and other is for error call.</p>

<pre><code>beforeEach(async(() =&gt; {

        TestBed.configureTestingModule({ .............

    class ProfileBenficiaryErrorStub {
            getPrefixSuffixDetails = function () {
                return Observable.throw(Error('Test error'));
            }}

     class ProfileServiceStub {
      getPrefixSuffixDetails = function () {
                return Observable.of(this.data);
            }
            }
</code></pre>

<p>But the issue is when I use two providers it only covers for error, If I dont include the provider for error, it covering for success</p>

<p>Please let me know where I am doing mistake using providers.</p>

<p>Also, I was trying to use spyOn way and facing error</p>

<pre><code> it('should check for the getPrefixSuffixDetails error call ', () =&gt; {
 spyOn(ProfileBeneficiaryService,'getPrefixSuffixDetails').and.returnValue(Observable.throw('error'));});
</code></pre>
",https://stackoverflow.com/questions/51294749/angular-unit-testing-for-observable-errors,"['angular', 'jasmine', 'karma-jasmine', 'angular-unit-test']",8778,TRUE,1,1
Unit Testing - faking out Dapper QueryMultipleAsync,"<p>I am using the Dapper QueryMultipleAsync to split the result of a SQL query into a number of different objects.  </p>

<p>However I am having trouble finding a way to unit test the method that this call is in. I have been using Fake it Easy to fake out elements for the unnit tests. As part of the tests I wanted to fake the QueryMultipleAsync to check other calls are made, however which ever way and at whatever level I try this I seam to get errors. </p>

<p>Does anyone have any experience trying to fake out this dapper element? If so how did you do it? </p>
",https://stackoverflow.com/questions/48298521/unit-testing-faking-out-dapper-querymultipleasync,"['dapper', 'fakeiteasy']",960,TRUE,1,1
AngularJS + Karma + Jasmine Controller Unit testing :,"<p>I have the following unit test code in which first test is passing, but the second one is failing and I am not able to figure it out.</p>

<p>Unit test code</p>

<pre><code>describe('List controller', function () {

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

    var $controller, $rootScope, $scope, $state;

    beforeEach(inject(function (_$controller_, _$rootScope_) {
        $controller = _$controller_;
        $rootScope = _$rootScope_;
        $scope = $rootScope.$new();
    }));

    describe('Parameter Group List', function() {
        it('should exists', function () {
            $controller = $controller('baseController', {'$scope': $scope});
            expect($scope.prepareSidebarMenu).toBeDefined();
        });
        it('should exists', function () {
            $state = {};
            $scope.header = {};
            $state.current = {};
            var parameterGroups = '';
            $scope.header.title = '';
            $controller = $controller('listController', {'$scope': $scope, 'parameterGroups': parameterGroups });
            expect($scope.truncateCharacters).toBeDefined();
        });
    });
});
</code></pre>

<p>and I am trying to test following controllers.</p>

<p>Base controller</p>

<pre><code>(function () {
    'use strict';

    angular.module('PpmApp')
        .controller('baseController', ['$scope', '$injector', baseController]);

    function baseController($scope, $injector) {

        var $state = $injector.get('$state');

        $scope.header = {
            title: ""Plan Parameter Manager""
        };
        $scope.sidebarMenuInfo = {
            name: $state.current.name,
            parameterGroupId: null,
            hideSidebar: true
        };
        $scope.prepareSidebarMenu = function (sidebarMenuInfo) {
            angular.extend($scope.sidebarMenuInfo, sidebarMenuInfo);
        };
    }
})();
</code></pre>

<p>List controller</p>

<pre><code>(function () {
    'use strict';

    angular.module('PpmApp')
        .controller('listController', ['$scope', '$injector', 'parameterGroups', listController]);

    function listController($scope, $injector, parameterGroups) {
        var $state = $injector.get('$state');
        var apiService = $injector.get('apiService');
        var utilService = $injector.get('utilService');
        var constantsProvider = $injector.get('constantsProvider');

        $scope.header.title = ""Parameter Manager Overview"";
        $scope.prepareSidebarMenu({
            name: $state.current.name,
            hideSidebar: true
        });

        var titleMaxLength = 47;
        var descriptionMaxLength = 270;

        $scope.parameterGroups = parameterGroups;
        $scope.createPopupInfo = {};
        $scope.createPopupInfo.validationErrors = {};
        $scope.createPopupInfo.validationErrors.isError = false;
        $scope.createPopupInfo.years = utilService.populateYearsForParameterGroup();
        $scope.createPopupInfo.months = constantsProvider.months;

        $scope.truncateCharacters = function (text, type) {
            if (type == 'title' &amp;&amp; text.length &gt; titleMaxLength) {
                return text.substring(0, titleMaxLength) + '...';
            } else if (type == 'description' &amp;&amp; text.length &gt; descriptionMaxLength) {
                return text.substring(0, descriptionMaxLength) + '...';
            }
            return text;
        };
 }
})();
</code></pre>

<p>My Unit test result is </p>

<pre><code>$ karma start
07 02 2018 12:41:00.734:WARN [karma]: No captured browser, open http://localhost                                                                                                                                  :9876/
07 02 2018 12:41:00.746:INFO [karma]: Karma v0.13.22 server started at http://lo                                                                                                                                  calhost:9876/
07 02 2018 12:41:00.751:INFO [launcher]: Starting browser Chrome
07 02 2018 12:41:02.946:INFO [Chrome 63.0.3239 (Windows 7 0.0.0)]: Connected on                                                                                                                                   socket doxoZRvKoJYdYozhAAAA with id 67949004

  parameterGroupListController
    Parameter Group List
      √should exists
      ×should exists
        TypeError: $scope.prepareSidebarMenu is not a function
            at new parameterGroupListController (C:/ZS/JIM-PPM/PlanManagerWeb/Ji                                                                                                                                  mPPM/app/controllers/parameter-group-list.js:14:16)
            at Object.instantiate (C:/ZS/JIM-PPM/PlanManagerWeb/JimPPM/resources                                                                                                                                  /angular.js:5112:14)
            at $controller (C:/ZS/JIM-PPM/PlanManagerWeb/JimPPM/resources/angula                                                                                                                                  r.js:11083:28)
            at C:/ZS/JIM-PPM/PlanManagerWeb/JimPPM/node_modules/angular-mocks/an                                                                                                                                  gular-mocks.js:2314:14
            at UserContext.&lt;anonymous&gt; (C:/ZS/JIM-PPM/PlanManagerWeb/JimPPM/test                                                                                                                                  s/parameter-group.spec.js:24:27)


Chrome 63.0.3239 (Windows 7 0.0.0): Executed 2 of 2 (1 FAILED) (0.038 secs / 0 s                                                                                                                                  ecs)
TOTAL: 1 FAILED, 1 SUCCESS


1) should exists
     parameterGroupListController Parameter Group List
     TypeError: $scope.prepareSidebarMenu is not a function
    at new parameterGroupListController (C:/ZS/JIM-PPM/PlanManagerWeb/JimPPM/app                                                                                                                                  /controllers/parameter-group-list.js:14:16)
    at Object.instantiate (C:/ZS/JIM-PPM/PlanManagerWeb/JimPPM/resources/angular                                                                                                                                  .js:5112:14)
    at $controller (C:/ZS/JIM-PPM/PlanManagerWeb/JimPPM/resources/angular.js:110                                                                                                                                  83:28)
    at C:/ZS/JIM-PPM/PlanManagerWeb/JimPPM/node_modules/angular-mocks/angular-mo                                                                                                                                  cks.js:2314:14
    at UserContext.&lt;anonymous&gt; (C:/ZS/JIM-PPM/PlanManagerWeb/JimPPM/tests/parame                                                                                                                                  ter-group.spec.js:24:27)
</code></pre>
",https://stackoverflow.com/questions/48658250/angularjs-karma-jasmine-controller-unit-testing,"['angularjs', 'jasmine', 'karma-runner']",254,TRUE,1,1
Mocking and unit testing implementation dependencies,"<p>I am trying to wrap my head around the practice of unit testing. I have read that unit tests should not be dependent on the implementations.</p>

<p>The way I understand this is, for example, if we have a function <code>int addTwoNumbers (int a, int b)</code> we should be testing whether, for example addition return correct results (i.e. <code>addTwoNumbers (2, 2) == 4)</code>) and we should not care whether, for example, <code>addTwoNumbers</code> calls <code>operator +</code> just once - it might as well use bit manipulation for this.</p>

<p>It seemed reasonable for me and - in my opinion - offers a decent decoupling between the tests and the code. </p>

<p>Enter the mocking frameworks. As far I can tell from reading their documentation, their functionality amounts to</p>

<p>(a) generating objects that implement placeholder functionality of some interfaces of base classes (stubbing) and</p>

<p>(b) checking whether that functionality was called according to expectations set forth by the tester. </p>

<p>I have no problems with (a) - I understand that we sometimes need to hard-code some functionality of external dependencies for the testing. I do not understand though, why should we check whether the tested code called mock's functionality in a way expected by the tester.</p>

<p>Shouldn't we be interested only in what a tested method returns or how it modifies its out arguments and not really care about its implementation details? Does the verification functionality of the mocking frameworks not introduce tight coupling between tested and testing code?</p>
",https://stackoverflow.com/questions/51455947/mocking-and-unit-testing-implementation-dependencies,"['unit-testing', 'mocking']",44,TRUE,1,1
unit testing auto mapper using moq,"<p>I have a service method which gets data from the repository and using automapper I am mapping it to the dto.</p>

<pre><code>public CustResponse GetCustomer(string id)
{
var repo = _myRepo.GetData(id);
var response = AutoMapper.Mapper.Map&lt;CustResponse&gt;(repo.custObj)
                           .Map(repo.addrObj);
return response;
}
</code></pre>

<p>I have created .map extension method in order to map multiple objects in class to a single dto.</p>

<pre><code>public static TDestination Map&lt;TSource, TDestination&gt;(this TDestination destination, TSource source)
{
    return Mapper.Map(source, destination);
}
</code></pre>

<p>Automapper configuration:</p>

<pre><code>m.CreateMap&lt;CUSTOBJ,CustResponse&gt;().ForMember(/*Some Properties*/);
m.CreateMap&lt;ADDROBJ,CustResponse&gt;().ForMember(/*Some Properties*/);
</code></pre>

<p>Now, I would like to write a unit test case for my <code>GetCustomer</code> method. I am not able to do so because my method depends on <code>Mapper.Map</code>.</p>

<p>Is there anyway I can move <code>var response = AutoMapper.Mapper.Map&lt;CustResponse&gt;(repo.custObj).Map(repo.addrObj);</code> to some interface and use the interface object to invoke the action.</p>

<p>In this way, I would be able to <code>mock</code> auto mapper interface.</p>

<p>Unit Testing code:</p>

<pre><code>var repStub = new Mock&lt;ICustomerRepository&gt;();
var expected = new CustResponse();            
var mockMapper = new Mock&lt;Mapper.Map&gt;(); //Not working
var customer = new CustomerService(repStub.Object);
customer.GetCustomer(""data"");
</code></pre>

<p><strong>Edit:</strong> I am not asking if I should do automapper unit testing or not. My questions my current service method does not allow me to create <code>moq</code> objects of <code>Mapper</code>. How can I create <code>IMapper</code> interface with my implementation?</p>
",https://stackoverflow.com/questions/52998763/unit-testing-auto-mapper-using-moq,"['c#', 'unit-testing', 'automapper', 'moq']",1233,FALSE,1,0
How is unit testing testing anything?,"<p>I don't understand how I'm testing anything with unit testing. </p>

<p>Suppose I am testing that my repository class can retrieve values from the database correctly. The proper way to do this would be to actually call the real database and retrieve and check those values. </p>

<p>But the idea behind unit testing is that it should be done in isolation, and connecting to a running database is not isolation. So what is usually done is to <em>mock</em> or <em>stub</em> the database. </p>

<p>But why would testing on a fake database with hardcoded data and hardcoded return values even test anything? It seems tautological and a waste of time. </p>

<p>Or am I not understanding how to unit test properly?</p>

<p>Does one even unit test database calls?</p>
",https://stackoverflow.com/questions/51308467/how-is-unit-testing-testing-anything,"['unit-testing', 'testing', 'tdd']",121,TRUE,1,3
Spring Unit testing rest controller error,"<p>This is my UserController, get() method which returns all UserDto's.</p>

<pre><code>@GetMapping(""/"")
public List&lt;UserDto&gt; get() {
    return userService.getUsers().stream().map((User user) -&gt; toUserDto(user)).collect(Collectors.toList());
}
</code></pre>

<p>And, <a href=""https://pastebin.com/6TtGF1Kc"" rel=""nofollow noreferrer"">this</a> is my UserControllerTest testing this get() method which fails. Could you tell me what I'm doing wrong? I'm making first steps with testing.</p>

<p>This is the console log:</p>

<pre><code>java.lang.NullPointerException
at pl.rmitula.restfullshop.controller.UserControllerTest.getAll(UserControllerTest.java:43)
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.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:389)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:115)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:167)
at org.junit.jupiter.engine.execution.ThrowableCollector.execute(ThrowableCollector.java:40)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:163)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:110)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.lambda$execute$3(HierarchicalTestExecutor.java:83)
at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:77)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.lambda$null$2(HierarchicalTestExecutor.java:92)
at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)
at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175)
at java.util.Iterator.forEachRemaining(Iterator.java:116)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.lambda$execute$3(HierarchicalTestExecutor.java:92)
at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:77)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.lambda$null$2(HierarchicalTestExecutor.java:92)
at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)
at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175)
at java.util.Iterator.forEachRemaining(Iterator.java:116)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.lambda$execute$3(HierarchicalTestExecutor.java:92)
at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:77)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:51)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:43)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:170)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:154)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:90)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:62)
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>
",https://stackoverflow.com/questions/48902923/spring-unit-testing-rest-controller-error,"['spring-boot', 'junit', 'mockito', 'spring-test']",576,TRUE,1,1
Exception during unit testing xml deserialization,"<p>I am using simplefreamwork xml serialization to deserialize some xml files in my android app. In app it works like a charm but when I put my code to unit test class it throws exception during deserialization.</p>

<pre><code>@Test
public void parseDefaultSettings() {
    String xml = ""&lt;there is xml&gt;"";
    PConfig pConfig = null;
    try {
        pConfig = parsePConfig(xml);
    } catch (Exception e) {
        Assert.fail(""parsing exception"");
    }
    assertTrue(pConfig.getSetups() != null);
}

private PConfig parsePConfig(String xml) throws Exception 
{
    org.simpleframework.xml.Serializer serializer = new Persister();
    return serializer.read(PConfig.class, xml);
}
</code></pre>

<p>This code works great in my app but it's throwing exception in unit tests:</p>

<pre><code>java.lang.AssertionError: e: java.lang.reflect.InvocationTargetException
    at org.junit.Assert.fail(Assert.java:88)
    at p_configuration.PConfigTest.parseSettings(PConfigTest.java:32)
    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.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)
    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.AppMainV2.main(AppMainV2.java:131)
</code></pre>
",https://stackoverflow.com/questions/51397283/exception-during-unit-testing-xml-deserialization,"['java', 'android', 'xml', 'unit-testing', 'simple-framework']",171,FALSE,1,0
Using global variables in unit testing,"<p>I'm unit testing a function, e.g. one that checks if the number you've given equals a global const variable. (Simplified situation)</p>

<pre><code>def the_special_number = 7

def is_the_special_number(number):
    if (number == the_special_number):
        return True
    else:
        return False
</code></pre>

<p>When I'm testing this function, I'd write a test like:</p>

<pre><code>import unittest

def test_is_special_number_true(self):
    self.assertTrue(is_the_special_number(the_special_number))
</code></pre>

<p>But is this actually a valid unit test, since in the function and the unit test I'm using the same global const? 
Or does the assertTrue need to be replaced with the following:</p>

<pre><code>self.assertTrue(is_the_special_number(7))
</code></pre>
",https://stackoverflow.com/questions/50170064/using-global-variables-in-unit-testing,"['python', 'unit-testing']",390,TRUE,1,1
Unit testing interceptor with custom header,"<p>I've been trying to run a test unit in an interceptor for Angular 6, however after much trial and error I keep getting the following error:</p>

<blockquote>
  <p>Error: Expected one matching request for criteria ""Match by function: "", found none.</p>
</blockquote>

<p>I'm kinda new to NG6 and unit testing on it, and couldn't find anything in the documentation</p>

<p>This is what I got:</p>

<p><strong>Token Service (It's mocked since it has no connection with the backend)</strong></p>

<pre><code>export class TokenService {

token: EventEmitter&lt;any&gt; = new EventEmitter();

findTokenData(): Observable&lt;any&gt; {

    return Observable.create((observer: Observer&lt;object&gt;) =&gt; {
        observer.next({ headerName: x-fake, token: fake' });
        observer.complete();
    });
  }
}
</code></pre>

<p><strong>Rest interceptor</strong></p>

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

constructor(public tokenService: TokenService) { }

intercept(req: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {

    console.log('request intercepted...');

    let authReq: HttpRequest&lt;any&gt;;
    const customHeadersMethods = ['POST', 'PUT', 'DELETE', 'PATCH'];

    // If the requested method is different GET or HEAD request the CSRF token from the service and add it to the headers
    if (customHeadersMethods.indexOf(req.method) !== -1) {
        this.tokenService.findTokenData().subscribe(res =&gt; {
            authReq = req.clone({
                headers: req.headers.set(res.headerName, res.token),
            });
        });

    } else {
        authReq = req.clone();
    }

    // send the newly created request
    return next.handle(authReq);
  }
}
</code></pre>

<p><strong>rest interceptor spec</strong></p>

<pre><code>describe('RestInterceptor', () =&gt; {
const mockTokenService = {
  headerName: 'x-fake',
  token: 'fake'
};

 beforeEach(() =&gt; {
   TestBed.configureTestingModule({
    imports: [HttpClientTestingModule],
    providers: [
    {
      provide: TokenService,
      useValue: mockTokenService
    },
    {
      provide: HTTP_INTERCEPTORS,
      useClass: RestInterceptor,
      multi: true
    }]
   });
  });

  afterEach(inject([HttpTestingController], (httpMock: HttpTestingController) =&gt; {
    httpMock.verify();
}));

  it('Should add a custom header', inject([HttpClient, HttpTestingController], (http: HttpClient, httpMock: HttpTestingController) =&gt; {

http.post('/data', {}).subscribe(
  response =&gt; {
    expect(response).toBeTruthy();
  }
);

const req = httpMock.expectOne(r =&gt;
  r.headers.has(`${mockTokenService.headerName}`) &amp;&amp; 
  r.headers.get(`${mockTokenService.headerName}`) === `${mockTokenService.token}`);

expect(req.request.method).toEqual('POST');   

httpMock.verify();
}));
});
</code></pre>

<p>Can anyone help me understand what am I missing?</p>
",https://stackoverflow.com/questions/52822760/unit-testing-interceptor-with-custom-header,"['javascript', 'angular', 'unit-testing', 'jasmine', 'angular-http-interceptors']",3362,TRUE,1,1
PowerShell pscmdlet unit testing with C#,"<p>Need some help understanding how to unit test a PowerShell module I'm creating.</p>

<p>I'm using the PowerShellStandard.Library package to create some cmdlets. My commands are deriving from pscmdlet and not cmdlet since I do need to manipulate the SessionState variables.</p>

<p>I've created a new unit testing project and I've searched some tutorials (e.g. <a href=""https://www.hanselman.com/blog/TestingPowerShellScriptsWithNUnit.aspx"" rel=""nofollow noreferrer"">https://www.hanselman.com/blog/TestingPowerShellScriptsWithNUnit.aspx</a>) where I found that I do need to use the Runspace class in order to execute the pscmdlet. Problem is that the below command, always returns a null runspace:</p>

<pre><code>Runspace runspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault2());
</code></pre>

<p>Anyone have been experimenting with these lately and have any idea?</p>
",https://stackoverflow.com/questions/50861437/powershell-pscmdlet-unit-testing-with-c,"['unit-testing', 'powershell', 'powershell-cmdlet', 'powershell-core']",1644,TRUE,1,2
Unit testing asynchronous functions in swift,"<p>I'm writing unit tests for various components of a UI. However, I'm running into trouble when writing tests for buttons that trigger asynchronous functions. My problem is that I'm using the <code>UIButton.sendActions(for controlEvents: UIControlEvents)</code> to trigger the pressing of the button, which then calls an asynchronous function.</p>

<p>Say I have a test:</p>

<pre><code>func testLoginToMainScene() {
     loadView()
     let queue = DispatchQueue(label: ""LoginButtonPressed"")

     queue.sync {
          view.loginButton.sendActions(for: .touchUpInside)
     }

     XCTAssertTrue(router.navigateToMainSceneCalled)
}
</code></pre>

<p>That tests the following bit of code in a <code>LoginViewController</code> class:</p>

<pre><code>@IBAction func loginButtonPressed(_ sender: AnyObject) {
     hideKeyboard()
     performLogin(email: emailTextField.text, password: passwordTextField.text)
}
</code></pre>

<p>And a function that handles the login by calling a method of a redux worker:</p>

<pre><code>private func performLogin(email: String, password: String) {
     let result = myReduxWorker.getStore().dispatch(newLoginAction(email: email, password: password)

     if let promise = result as? Promise&lt;[String: Any]&gt; {
          promise.done { json -&gt; Void in
               //Login was successful!
               router.navigateToMainScene()
          }
     }
</code></pre>

<p>Currently, the test fails because the <code>XCTAssertTrue</code> test runs before the <code>performLogin</code> function completes, and thus before <code>navigateToMainScene</code> is called. I tried using a <code>DispatchQueue</code>, but as soon as the <code>.touchUpInside</code> action is sent to the button, the block of code inside the <code>.sync</code> finishes, and the test function continues and runs the <code>XCTAssertTrue</code> test.</p>

<p>What is the best way to ensure that the <code>performLogin</code> function has finished running before executing the test case?</p>
",https://stackoverflow.com/questions/50765560/unit-testing-asynchronous-functions-in-swift,"['swift', 'unit-testing', 'asynchronous', 'uibutton']",316,TRUE,1,1
Unit testing with I/O dependencies,"<p>I would like to test the following class but I/O and sealed class dependencies are making it quite hard.</p>

<pre><code>public class ImageDrawingCombiner
{
    /// &lt;summary&gt;
    ///     Save image to a specified location in path
    /// &lt;/summary&gt;
    /// &lt;param name=""path""&gt;Location to save the image&lt;/param&gt;
    /// &lt;param name=""surface""&gt;The image as canvas&lt;/param&gt;
    public void CombineDrawingsIntoImage(Uri path, Canvas surface)
    {
        Size size = new Size(surface.ActualWidth, surface.ActualHeight);

        // Create a render bitmap and push the surface to it
        RenderTargetBitmap renderBitmap = new RenderTargetBitmap(
            (int)size.Width, (int)size.Height, 96d, 96d, PixelFormats.Pbgra32);
        renderBitmap.Render(surface);

        SaveBitmapAsPngImage(path, renderBitmap);
    }

    // SaveBitmapAsPngImage(path, renderBitmap);
    private void SaveBitmapAsPngImage(Uri path, RenderTargetBitmap renderBitmap)
    {
        // Create a file stream for saving image
        using (FileStream outStream = new FileStream(path.LocalPath, FileMode.OpenOrCreate))
        {
            // Use png encoder for our data
            PngBitmapEncoder encoder = new PngBitmapEncoder();
            // push the rendered bitmap to it
            encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
            // save the data to the stream
            encoder.Save(outStream);
        }
    }
}
</code></pre>

<p>Refactored the SaveBitmapAsPngImage method a bit:</p>

<pre><code>// SaveBitmapAsPngImage(path, renderBitmap, new PngBitmapEncoder());
    public void SaveBitmapAsPngImage(Uri path, BitmapSource renderBitmap, BitmapEncoder pngBitmapEncoder)
    {
        // Create a file stream for saving image
        using (FileStream outStream = new FileStream(path.LocalPath, FileMode.OpenOrCreate))
        {
            // Use png encoder for our data
            // push the rendered bitmap to it
            pngBitmapEncoder.Frames.Add(BitmapFrame.Create(renderBitmap));
            // save the data to the stream
            pngBitmapEncoder.Save(outStream);

}
</code></pre>

<p>Made it public to be testable (code smell?). It is still using FileStream. Some would suggest to replace it with MemoryStream and/or Factory pattern but in the end it has be to saved to the image file somewhere.</p>

<p>Even if I replace all the I/O based calls with wrappers or interfaces (SystemInterface):
 - Where should the instances be initialised? At the composite root? That is a lot to bubble up...
 - How would I avoid the ""up to 3 constructor parameter"" rule with DI?
 - It all sounds a lot of work for this simple function</p>

<p>The test(s) should make sure the image file is produces.</p>

<p>EDIT:
Tried to run the @Nkosi Moq test but it needed a repair. Replaced:</p>

<pre><code>var renderBitmap = new Canvas();
</code></pre>

<p>with:</p>

<pre><code>Size renderSize = new Size(100, 50);
var renderBitmap = new RenderTargetBitmap(
    (int)renderSize.Width, (int)renderSize.Height, 96d, 96d, PixelFormats.Pbgra32);
</code></pre>

<p>Test result:</p>

<blockquote>
  <p>BitmapServiceTest.BitmapService_Should_SaveBitmapAsPngImage threw
  exception:  System.IO.IOException: Cannot read from the stream. --->
  System.Runtime.InteropServices.COMException: Exception from HRESULT:
  0x88982F72
      at System.Windows.Media.Imaging.BitmapEncoder.Save(Stream stream)</p>
</blockquote>

<p>Seems like the encoder is not happy with the mocked Moq stream. Should the PngBitmapEncoder dependency also by method injected (and mocked in tests)?</p>
",https://stackoverflow.com/questions/49923188/unit-testing-with-i-o-dependencies,"['c#', 'wpf', 'nunit', 'rhino-mocks']",872,TRUE,1,1
"Spring WebFlux, unit testing Mono and Flux","<p>Interested in reactive programming, I played a bit with the <a href=""https://spring.io/guides/gs/reactive-rest-service/"" rel=""noreferrer"">Building a Reactive RESTful Web Service</a> guide. And wanted to move forwrad and add some unit tests.</p>

<p>I tried to test my handler (<code>RouterFunction</code>) with plain Junit/Mockito test. But, because it is reactive, the handler returns a <code>Mono&lt;ServerResponse&gt;</code>. So I had to <code>block()</code> it to test the <code>ServerResponse</code> status but was not able to extract his body to test it. While searching the web for a solution, it seems that all the samples are using the <code>WebTestClient</code>.</p>

<p><strong>My question is:</strong></p>

<p>Given that all samples are using <code>WebTestClient</code> to test a reactive REST service and that it is not easier to (unit) test the body of a <code>ServerResponse</code>. Is it a good practice to unit test a <code>RouterFunction</code> or is it better to always do broader tests with the <code>WebTestClient</code> ?</p>

<p>Thanks a lot.</p>
",https://stackoverflow.com/questions/51830411/spring-webflux-unit-testing-mono-and-flux,"['java', 'unit-testing', 'spring-boot', 'reactive-programming', 'spring-webflux']",15190,TRUE,8,2
SignalR dotnet core MVC Unit testing,"<p>and sorry for the confusing title!
so, i am developing a ""lobby"" where users come in, and other users can see when somebody logs in to the lobby. there can be many lobbies, but only when a user log in to the same lobby, they will show up. the solution and deployment works fine, my problem is (as the title suggests) testing this whole mess!
For this, i figured i need to test 2 things:
1. i need to test that signalR HUB side calls correctly when clients connects etc. so testing the server side part of SignalR
2. i need to test that my javascript, thats under the folder wwwroot/js (asp.net core mvc) for this i figure i need to use mocha. my problem here is that the js files is under a c# .net core project, and i dont know how to test it then.</p>

<p>However, after tirelessly searching forums and docs everywhere on the net, i came up with no solutions for none of the problems! i hope somebody can help, maybe hint some ideas of how i go about doing this.</p>

<p>i will post my relevant code here:</p>

<hr>

<h2>Lobby.cshtml</h2>

<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>@using Domain.Interfaces
@using Domain.Models
@using GUI_Index.Session
@using Microsoft.AspNetCore.Http
@model GUI_Index.ViewModels.LobbyViewModel
@{
    ViewData[""Title""] = ""Tilslut Lobby"";
}
&lt;meta http-equiv=""X-UA-Compatible"" content=""IE=edge"" /&gt;
&lt;body&gt;
&lt;div class=""container""&gt;

    &lt;button id=""ForLadLobby"" type=""button"" class=""btn btn-post"" onclick=""location.href = '@Url.Action(""ForladLobby"", ""Lobby"", Model)'""&gt;Ud af lobby&lt;/button&gt;

    &lt;div class=""form-group left-Align ingamebox""&gt;
        
        &lt;table id=""UsersInLobby""&gt;
            &lt;th&gt;Users in Lobby: &lt;/th&gt;

            @{
                foreach (var usernames in Model.Usernames)
                {
                    &lt;tr id=""@usernames""&gt;
                        &lt;td&gt;
                            @usernames
                        &lt;/td&gt;
                    &lt;/tr&gt;
                }
            }
            
        &lt;/table&gt;
    &lt;/div&gt;

    &lt;div class=""form-group right-Align ingamebox""&gt;
        Message...&lt;input type=""text"" id=""messageInput"" /&gt;
        &lt;input type=""button"" class=""btn btn-primary"" id=""sendButton"" value=""Send Message"" /&gt;
    &lt;/div&gt;

    @{
        string user = SessionExtension.GetObjectFromJson&lt;User&gt;(Context.Request.HttpContext.Session, ""user"").Username;
    }

    &lt;form method=""post"" formaction=""@Url.Action(""Lobby"", ""Lobby"")""&gt;
        &lt;table&gt;
            &lt;tr&gt;
                &lt;div class=""top-Align""&gt;
                    &lt;div id=""center-Text""&gt;

                        Hello: &lt;label id=""LobbyUser""&gt;@user&lt;/label&gt;  &lt;br/&gt;
                        Welcome to: &lt;label id=""LobbyId""&gt;@Model.Id&lt;/label&gt;

                    &lt;/div&gt;
                        
                    &lt;ul id=""Messages""&gt;&lt;/ul&gt;

                &lt;/div&gt;

            &lt;/tr&gt;

            &lt;tr&gt;
                &lt;div class=""absolute-center is-responsive""&gt;
                    &lt;div class=""form-group""&gt;
                        &lt;input type=""hidden"" class=""form-control"" name=""Id""&gt;
                    &lt;/div&gt;
                    &lt;div class=""btn-group-vertical""&gt;
                        
                        @{
                            if (Model.Admin == user)
                            {
                                &lt;button type=""submit"" class=""btn btn-primary""&gt;Start spil&lt;/button&gt;
                                &lt;div class=""divider""&gt;&lt;/div&gt;
                                &lt;br /&gt;
                            }
                        }

                    &lt;/div&gt;
                &lt;/div&gt;
            &lt;/tr&gt;
        &lt;/table&gt;

    &lt;/form&gt;

&lt;/div&gt;

&lt;/body&gt;

&lt;script src='@Url.Content(""~/lib/signalr.js"")'&gt;&lt;/script&gt;
&lt;script src='@Url.Content(""~/js/Lobby.js"")'&gt;&lt;/script&gt;</code></pre>
</div>
</div>
</p>

<hr>

<h2>Lobbyhub.cs</h2>

<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>using System;
using System.Threading.Tasks;
using Domain.Models;
using GUI_Index.Session;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.SignalR;

// https://learn.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api

namespace GUI_Index.Hubs
{
    public class LobbyHub : Hub
    {
        
        //private HttpContext context = new DefaultHttpContext();
        
        /// &lt;summary&gt;
        /// Called by SignalR on connection to page
        /// &lt;/summary&gt;
        /// &lt;returns&gt;&lt;/returns&gt;
        public override async Task OnConnectedAsync()
        {
           await this.Clients.Caller.SendAsync(""Connect"");
        }


        /// &lt;summary&gt;
        /// called by Lobby.js
        /// &lt;/summary&gt;
        /// &lt;param name=""username""&gt;The username of the user in the lobby&lt;/param&gt;
        /// &lt;param name=""Lobbyname""&gt;The lobbyname of the lobby where user is&lt;/param&gt;
        /// &lt;returns&gt;&lt;/returns&gt;
        public async Task OnConnectedUserAsync(string username, string Lobbyname)
        {
            //add user to group
            await Groups.AddAsync(Context.ConnectionId, Lobbyname);
            
            //send to others in the group
            await this.Clients.OthersInGroup(Lobbyname).SendAsync(""onConnectedUser"", username);

            //old
            //await this.Clients.Others.SendAsync(""OnConnectedUser"", username);
        }

        /// &lt;summary&gt;
        /// Called by Lobby.js
        /// &lt;/summary&gt;
        /// &lt;param name=""user""&gt; the user in the lobby that sends&lt;/param&gt;
        /// &lt;param name=""LobbyName""&gt; the lobby that the user is in&lt;/param&gt;
        /// &lt;param name=""message""&gt; the message the user wishes to send&lt;/param&gt;
        /// &lt;returns&gt;&lt;/returns&gt;
        public async Task SendMessageAsync(string user,string LobbyName, string message)
        {
            await this.Clients.Group(LobbyName).SendAsync(""ReceiveMessage"", user, message);

            //old
            //await this.Clients.All.SendAsync(""ReceiveMessage"", user, message);

        }

        public async Task UserLeftAsync(string username, string lobbyname)
        {
            await this.Groups.RemoveAsync(Context.ConnectionId, lobbyname);

            await this.Clients.OthersInGroup(lobbyname).SendAsync(""OnDisconnectedUser"", username);
        }

        /*
        public override async Task OnDisconnectedAsync(Exception exception)
        {
            await this.Clients.All.SendAsync(""Disconnect"");
        }

        public async Task OnDisconnectedUserAsync(string username)
        {
            await this.Clients.Others.SendAsync(""OnDisconnectedUser"", username);
        }

        */

    }
}</code></pre>
</div>
</div>
</p>

<hr>

<h2>Lobby.js</h2>

<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 connection = new signalR.HubConnection(""/Hubs/LobbyHub"", { logger: signalR.LogLevel.Information });

/////////////////////////////////////Enter Lobby///////////////////////////////////////////

connection.on(""Connect"", () =&gt; {

    //get the username
    var Username = document.getElementById(""LobbyUser"").textContent;
        //get the lobbyName
        var Lobbyname = document.getElementById(""LobbyId"").textContent;
        //send to hub
        connection.invoke(""OnConnectedUserAsync"", Username, Lobbyname);
    //}

});



connection.on(""OnConnectedUser"",
    (user) =&gt; {


        if (!document.getElementById(user)) {
            var li = document.createElement(""li"");
            li.textContent = ""User: "" + user + "" Signed On!"";
            document.getElementById(""Messages"").appendChild(li);

            //update table
            const table = document.getElementById(""UsersInLobby"");
            const newrow = table.insertRow(table.rows.length);
            //set the id of the row
            newrow.id = user;
            const newcell = newrow.insertCell(0);
            //add user to table
            const newText = document.createTextNode(user);
            newcell.appendChild(newText);
        }

    }); 

///////////////////////////////////////Messages///////////////////////////////////////////////

document.getElementById(""sendButton"").addEventListener(""click"", event =&gt; {
    //get the username
    const user = document.getElementById(""LobbyUser"").textContent;
    //get the message 
    const message = document.getElementById(""messageInput"").value;
    //get the lobbyname
    const lobby = document.getElementById(""LobbyId"").textContent;
    //send it to hub
        connection.invoke(""SendMessageAsync"", user,lobby, message).catch(err =&gt; console.error);
    event.preventDefault();
});

connection.on(""ReceiveMessage"", (user, message) =&gt; {
    //write the complete message
    const Message = user + "" says "" + message;
    //create list element
    const li = document.createElement(""li"");
    //add to list element
    li.textContent = Message;
    //append to chat
    document.getElementById(""Messages"").appendChild(li);
});

///////////////////////////leave Lobby////////////////////////////////////

//Setup click event
document.getElementById(""ForLadLobby"").addEventListener(""click"", event =&gt; {
    //get the username
    const user = document.getElementById(""LobbyUser"").textContent;
    //get the lobbyname
    const lobby = document.getElementById(""LobbyId"").textContent;
    //send it to hub
    connection.invoke(""UserLeftAsync"", user, lobby).catch(err =&gt; console.error);
    event.preventDefault();
});

//user left
connection.on(""OnDisconnectedUser"",
    (user) =&gt; {
        //create element to hold information
        const li = document.createElement(""li"");
        //tell others that user left
        li.textContent = ""User: "" + user + "" Signed Off!"";
        //add to chat
        document.getElementById(""Messages"").appendChild(li);

        //update table of online users
        var row = document.getElementById(user);
        //get the table and delete the row!
        row.parentNode.removeChild(row);
        //old
        //row.deleteCell(0);


    });

connection.start().catch(err =&gt; console.error);</code></pre>
</div>
</div>
</p>

<p>I hope you can help me!</p>
",https://stackoverflow.com/questions/50240510/signalr-dotnet-core-mvc-unit-testing,"['javascript', '.net-core', 'signalr', 'signalr-hub', 'signalr.client']",416,FALSE,1,0
Unit Testing Google&#39;s Go API Client,"<p>I am currently writing a workflow in Go that uses Google's <a href=""https://github.com/google/google-api-go-client"" rel=""nofollow noreferrer"">API go client</a>.  I'm relatively new to Go and am having trouble unit testing the client's services. Here is an example method that enables an API in a Google Cloud Project. </p>

<pre><code>func (gcloudService *GCloudService) EnableApi(projectId string, apiId string) error {
  service, err := servicemanagement.New(gcloudService.Client)
  if err != nil {
      return err
  }

  requestBody := &amp;servicemanagement.EnableServiceRequest{
      ConsumerId: consumerId(projectId),
  }

  _, err = service.Services.Enable(apiId, requestBody).Do()
  if err != nil {
      return err
  }

  return nil
}
</code></pre>

<p><code>GCloudService</code> is a simple struct that holds a Client.</p>

<pre><code>type GCloudService struct {
   Client *http.Client
}
</code></pre>

<p>This is my attempt at testing this method.</p>

<pre><code>var (
  mux    *http.ServeMux
  client *http.Client
  server *httptest.Server
)

func setup() {
  // test server
  mux = http.NewServeMux()
  server = httptest.NewServer(mux)

  // client configured to use test server
  client = server.Client()
}

func teardown() {
  server.Close()
}

func TestGCloudService_EnableApi(t *testing.T) {
  setup()
  defer teardown()

  projectName := ""test""
  apiId := ""api""

  testGcloudService := &amp;GCloudService{
     Client: client,
  }

  path := fmt.Sprintf(""/v1/services/{%s}:enable"", apiId)

  mux.HandleFunc(path,
    func(w http.ResponseWriter, r *http.Request) {
        // test things...
    })

  err := testGcloudService.EnableApi(projectName, apiId)
  if err != nil {
      t.Errorf(""EnableApi returned error: %v"", err)
  }
}
</code></pre>

<p>However, when I run this test it still hits the real Google endpoint instead of my localhost server because EnableApi uses the servicemanagement service which is configured with the API's base URL. How do I refactor this to call my server instead of the API? I am hoping to avoid mocking the entire servicemanagement service if possible.</p>
",https://stackoverflow.com/questions/50693560/unit-testing-googles-go-api-client,"['unit-testing', 'go', 'google-api', 'client', 'google-api-client']",1369,TRUE,1,2
Unit testing wpf (Disable message boxes),"<p>I am writing unit tests for my code. And using 'Microsoft.VisualStudio.TestTools'.
I do not want to popup a message  while running 'Unit Test' for functions which contains message boxes. I am able to do this by using following code,</p>

<pre><code> public static class UnitTestDetector
{
    static UnitTestDetector()
    {
        string testAssemblyName = ""Microsoft.VisualStudio.QualityTools.UnitTestFramework"";
        UnitTestDetector.IsInUnitTest = AppDomain.CurrentDomain.GetAssemblies()
            .Any(a =&gt; a.FullName.StartsWith(testAssemblyName));
    }

    public static bool IsInUnitTest { get; private set; }
}
</code></pre>

<p>But for this solution I have to use 'IsInUnitTest' in actual function to disable message boxes. Is there any other solution? </p>
",https://stackoverflow.com/questions/49789228/unit-testing-wpf-disable-message-boxes,"['c#', 'wpf', 'unit-testing']",1054,TRUE,1,1
Unit testing ionic services with jest,"<p>I'm building an ionic app and would like to add unit tests for a couple of services. I'm trying to get jest working with typescript but it doesn't seem to play well.</p>

<p>I'm getting this error:</p>

<pre><code>/myuser/project/node_modules/@ionic/storage/dist/index.js:1
({""Object.&lt;anonymous&gt;"":function(module,exports,require,__dirname,__filename,global,jest){import { NgModule } from '@angular/core';
                                                                                         ^^^^^^

SyntaxError: Unexpected token import
</code></pre>

<p>Now I have read that you have to add the babel-plugin-transform-es2015-modules-commonjs and use that in the test env of babel. However I am using babel 7 and this plugin is not available for babel 7. Is there a different solution?</p>

<p>I will also provide my package.json and .babelrc below.
<a href=""https://gist.github.com/blackwolf12333/cc67e0b08ea37c957a03fb305d9dd2ba"" rel=""nofollow noreferrer"">gist</a></p>
",https://stackoverflow.com/questions/49489107/unit-testing-ionic-services-with-jest,"['ionic-framework', 'jestjs', 'babel-jest']",1194,TRUE,1,1
C++ Template template for unit testing,"<p>I'm experimenting with using C++'s template template features to reduce code duplication in a small unit test segment in my code, to no success. I've seen <a href=""https://stackoverflow.com/questions/10871100/pass-a-function-as-an-explicit-template-parameter"">these</a> <a href=""https://stackoverflow.com/questions/1174169/function-passed-as-template-argument"">answers</a> to similar questions, but still can't figure out what my compiler is telling me.</p>

<p>I deal with some classes that do numerical processing at different precisions, and so I thought that I could generalize the duplicate code to a templated function, so it could be easily called by the class tests, as in:</p>

<pre><code>template&lt;typename T, size_t S&gt;
void CompareArrays(
    std::array&lt;T, S&gt; const &amp;input,
    std::array&lt;T, S&gt; const &amp;output) {...}

template &lt;typename T&gt;
void SomeClassTest::SomeClassIdentity() const {
    SomeClass&lt;T&gt; scZero;
    std::array&lt;T, 1&gt; const input = { 1 };
    auto output = scZero.Process(input);
    CompareArrays(input, output); // does the actual printing
}
</code></pre>

<p>And then, test a lot of operations similar to <code>SomeClassTest::SomeClassIdentity</code> with a template template function:</p>

<pre><code>template&lt;template &lt;typename&gt; typename F&gt;
void CheckAgainstNumericTypes() {
    std::cerr &lt;&lt; ""Testing with char..."";
    F&lt;char&gt;();
    std::cerr &lt;&lt; ""Testing with short..."";
    F&lt;short&gt;();
    std::cerr &lt;&lt; ""Testing with int..."";
    F&lt;int&gt;();
    std::cerr &lt;&lt; ""Testing with float..."";
    F&lt;float&gt;();
    std::cerr &lt;&lt; ""Testing with double..."";
    F&lt;double&gt;();
}
</code></pre>

<p>The problem is, every time I try to invoke <code>CheckAgainstNumericTypes</code>, the compiler will refuse with the error message ""Invalid Template Argument for 'F', type expected"", as in the example below:</p>

<pre><code>void SomeClassTest::Test() const {
    std::cerr &lt;&lt; ""Some Class Tests #1 - base/identity case"" &lt;&lt; std::endl;
    CheckAgainstNumericTypes&lt;SomeClassIdentity&gt;();
    ...
</code></pre>

<p>I tried making <code>CheckAgainstNumericTypes</code> a member function of <code>SomeClass</code>, prepending the template argument with <code>SomeClass::</code>, adding <code>()</code> to the end of it, and even replacing the inner <code>typedef</code> by <code>void(*F)(void)</code>; all to no avail.</p>

<p>I have two questions, then:</p>

<ul>
<li>How can I transform my member function into a type so it is accepted by the template?</li>
<li>Is there any other way of accomplishing the same desired syntactic result in <code>SomeClassTest::Tests()</code> <em>without using</em> template templates?</li>
</ul>
",https://stackoverflow.com/questions/52958372/c-template-template-for-unit-testing,"['c++', 'templates', 'c++17', 'template-templates']",1466,TRUE,1,1
Unit testing in scala for httpUtils,"<pre><code>def getDetails(userId: String, organization: String, url: String, model: String) = {
    httpUtils.get(userId, organization, url + ""/models/"" + model + ""/modelsets"").map {
      resp =&gt;
        resp.status match {
          case Status.OK =&gt; parse(resp.body).extract[List[DatabaseDetails]]
          case _         =&gt; handleError(resp.status) //
        }
    }
  }
</code></pre>

<p>Can anybody help me in writing its unit test?</p>
",https://stackoverflow.com/questions/50906538/unit-testing-in-scala-for-httputils,"['scala', 'unit-testing', 'testing']",41,FALSE,1,0
Moq unit testing access local variable,"<p>I am trying to create an INTEGRATION Test using Moq for some code that involves a REST request.  </p>

<p>In regular usage, the code would go out and create a Report record and have other impacts in a 3rd party system.
With the Moq test, the <em>Execute</em> call from the RestSharp IRestClient can be substituted for a dummy method that does nothing.  For a successful INTEGRATION test, there are 2 requirements: (a) REQUEST xml looks correct (b) RESPONSE json is returned.  I'd like to be able to execute most of the code involved in the integration and inspect a local variable from the system under test in the xUnit code assertions.  However, I can't seem to access the local variable using Moq, unless I add some code artifacts around testing. </p>

<p>I have created two projects to illustrate.  Hope you can point me in the right direction.  Perhaps the code needs to be restructured or a new Mock object for the CommandHandler needs to be created?</p>

<p>Thanks!</p>

<p><strong>TEST PROJECT</strong></p>

<pre><code>using Mocking;  // System Under Test
using Moq;
using Newtonsoft.Json.Linq;
using RestSharp;
using System.Net;
using System.Threading;
using Xunit;

namespace MockingTest
{
    public class UnitTest1
    {
        [Fact]
        public async void SubmitReport_WithPerson_CanProcessSubmitSuccessfully()
        {
            // ----------------------------------------------------------------------------------
            // Arrange
            // ----------------------------------------------------------------------------------
            Person person = new Person();
            person.Name = ""Test"";
            string testRequestXML = GetTestRequestXML(person);
            string testResponseXML = ""OK"";

            // Construct the Mock Rest Client.  This should allow most of the submission process to be run - 
            // but the actual Execute to call CMS will not be done - instead the Mock framework will return 
            // an arbitrary response as defined below.
            var mockRestClient = new Mock&lt;IRestClient&gt;();
            RestResponse testRestResponse = GetTestRestResponse(System.Net.HttpStatusCode.OK, string.Empty, ResponseStatus.Completed, testResponseXML);
            mockRestClient.Setup(rc =&gt; rc.Execute(It.IsAny&lt;IRestRequest&gt;()))
                                       .Returns(testRestResponse);

            // ----------------------------------------------------------------------------------
            // Act
            // ----------------------------------------------------------------------------------
            Command command = new Command(person);
            CancellationToken cancellationToken = new CancellationToken();
            CommandHandler commandHandler = new CommandHandler(mockRestClient.Object);  // CommandHandler is the ""System Under Test""

            string result = await commandHandler.Handle(command, cancellationToken);

            JToken responseToken = JToken.Parse(result);
            string responseXML = responseToken.SelectToken(""response"").ToString();
            string requestXML = responseToken.SelectToken(""request"").ToString();  // Normally this would not be available.

            // ----------------------------------------------------------------------------------
            // Assert
            // ----------------------------------------------------------------------------------
            Assert.Equal(requestXML, testRequestXML);                       // Handed back in JSON - normally this would not be the case.
            Assert.Equal(commandHandler.ReportXMLRequest, testRequestXML);  // Handed back in Property - normally this would not be the case.
        }

        private RestResponse GetTestRestResponse(HttpStatusCode httpStatusCode, string httpErrorMessage, ResponseStatus httpResponseStatus, string responseXML)
        {
            RestResponse testRestResponse = new RestResponse();
            testRestResponse.StatusCode = httpStatusCode;
            testRestResponse.ErrorMessage = httpErrorMessage;
            testRestResponse.ResponseStatus = httpResponseStatus;
            testRestResponse.Content = responseXML;
            return testRestResponse;
        }

        private string GetTestRequestXML(Person person)
        {
            // Sample XML.
            string xml = string.Empty;
            xml = xml + ""&lt;xml&gt;"";
            xml = xml + ""&lt;report&gt;"";
            xml = xml + ""&lt;status&gt;"" + ""Initialized"" + ""&lt;/status&gt;"";
            xml = xml + ""&lt;person&gt;"" + person.Name + ""&lt;/person&gt;"";
            xml = xml + ""&lt;/report&gt;"";
            return xml;
        }
    }
}
</code></pre>

<p><strong>SYSTEM UNDER TEST</strong></p>

<pre><code>using Newtonsoft.Json.Linq;
using RestSharp;
using System;
using System.Threading;
using System.Threading.Tasks;

// System Under Test
namespace Mocking
{
    public class Person
    {
        public string Name { get; set; }
    }

    public class ReportStatus
    {
        public string Status { get; private set; }

        public ReportStatus ()
        {
            this.Status = ""Initialized"";
        }
    }

    public class Report
    {
        public Person Person { get; private set; }

        public ReportStatus ReportStatus { get; private set; }

        public Report (Person person)
        {
            Person = person;
            ReportStatus = new ReportStatus();
        }
    }

    public class Command
    {
        public Person Person { get; private set; }

        public Command (Person person)
        {
            this.Person = person;
        }
    }
    public class CommandHandler
    {
        public string ReportXMLRequest { get; private set; }  //  Property to permit validation. 
        private readonly IRestClient RestClient;

        //// Using DI to inject infrastructure persistence Repositories - this is the normal call.
        //public CommandHandler(IMediator mediator, IReportRepository reportRepository, IIdentityService identityService)
        //{
        //    ReportXMLRequest = string.Empty;
        //    RestClient = new RestClient();
        //}

        // MOQ Addition - Overload constructor for Moq Testing.
        public CommandHandler(IRestClient restClient)
        {
            ReportXMLRequest = string.Empty;
            RestClient = restClient;
        }

        public async Task&lt;string&gt; Handle(Command command, CancellationToken cancellationToken)
        {
            Report report = new Report(command.Person);
            string reportResult = Submit(report);
            return reportResult;
        }

        private string Submit(Report report)
        {
            string responseXML = string.Empty;
            string localVariableForRequestXML = GetRequestXML(report);

            // MOQ Addition - Set Property to be able to inspect it from the integration test.
            this.ReportXMLRequest = localVariableForRequestXML;

            IRestClient client = RestClient;
            string baseType = client.GetType().BaseType.FullName;

            client.BaseUrl = new Uri(""http://SampleRestURI"");
            RestRequest request = new RestRequest(Method.POST);
            request.AddParameter(""application/xml"", localVariableForRequestXML, ParameterType.RequestBody);

            // Normally, this REST request would go out and create a Report record and have other impacts in a 3rd party system.
            // With Moq, the Execute call from the RestSharp IRestClient can be substituted for a dummy method.
            // For a successful INTEGRATION test, there are 2 requirements:
            //     (a) REQUEST xml looks correct (b) RESPONSE json is returned.
            **IRestResponse response = client.Execute(request);**
            responseXML = response.Content;

            // MOQ Addition - Do something... e.g. return JSON response with extra information.
            JObject json = null;
            if (baseType.ToLowerInvariant().Contains(""moq""))
            {
                json = new JObject(
                    new JProperty(""response"", responseXML),
                    new JProperty(""request"", localVariableForRequestXML)
                    );
            }
            else
            {
                json = new JObject(new JProperty(""response"", responseXML));
            }

            string jsonResponse = json.ToString();
            return jsonResponse;
        }

        private string GetRequestXML(Report report)
        {
            // Sample XML - normally this would be quite complex based on Person and other objects.
            string xml = string.Empty;
            xml = xml + ""&lt;xml&gt;"";
            xml = xml + ""&lt;report&gt;"";
            xml = xml + ""&lt;status&gt;"" + report.ReportStatus.Status + ""&lt;/status&gt;"";
            xml = xml + ""&lt;person&gt;"" + report.Person.Name + ""&lt;/person&gt;"";
            xml = xml + ""&lt;/report&gt;"";
            return xml;
        }
    }

}
</code></pre>
",https://stackoverflow.com/questions/49727309/moq-unit-testing-access-local-variable,"['c#', 'scope', 'integration-testing', 'moq']",2761,TRUE,1,1
Unit testing with data from file,"<p>I'm trying to create a Lemmatizer. To test this lemmatizer I've obtained a csv with almost 75000 lemmatizations.</p>

<p>To test I've created a unit test that reads the file and checks if each line results in the correct lemma. The problem with this method is that it fails on the first error, which is of course as it should. But this doesn't give me an idea of the total progress of the lemmatizer. Is this the only one failing or is this just the first of thousands. </p>

<p>I could create a test that just counts the correct ones and checks if this number is equal to the number tested. But then I don't have a good clue about the failures. </p>

<p>The best thing that comes to my mind is to create a unit test per word + lemma. The downside of this is a) the work and b) makes it less easy to add a new word/lemma combo to test in respect to just adding it to the csv.</p>

<p>So my question is: Does anyone have a better option than the one above? Having a good track of ""progress"" but still see individual fails/success tests.</p>
",https://stackoverflow.com/questions/51790608/unit-testing-with-data-from-file,"['c#', 'unit-testing']",146,TRUE,1,1
Unit Testing Class That Wraps HttpClient,"<p>I am in the process of writing unit tests for a new project we've created and one of the issues I've come across is how to properly unit test something that effectively wraps HttpClient. In this case, I have written a RestfulService class that exposes basic methods for calling a REST service from C#. </p>

<p>Here is the simple interface that the class implements:</p>

<pre><code>public interface IRestfulService
{
    Task&lt;T&gt; Get&lt;T&gt;(string url, IDictionary&lt;string, string&gt; parameters, IDictionary&lt;string, string&gt; headers = null);

    Task&lt;T&gt; Post&lt;T&gt;(string url, IDictionary&lt;string, string&gt; parameters, object bodyObject, IDictionary&lt;string, string&gt; headers = null);

    Task&lt;string&gt; Put(string url, IDictionary&lt;string, string&gt; parameters, object bodyObject, IDictionary&lt;string, string&gt; headers = null);

    Task&lt;string&gt; Delete(string url, object bodyObject, IDictionary&lt;string, string&gt; headers = null);

    Task&lt;FileResponse?&gt; Download(string url, IDictionary&lt;string, string&gt; urlParams = null, IDictionary&lt;string, string&gt; headers = null);
}
</code></pre>

<p>and here's is a trimmed down version of the implementation for example purposes:</p>

<pre><code>public class RestfulService : IRestfulService
    {
        private HttpClient httpClient = null;
        private NetworkCredential credentials = null;
        /* boiler plate code for config and what have you */
        private string Host =&gt; ""http://localhost"";
        private NetworkCredential Credentials =&gt; new NetworkCredential(""sampleUser"", ""samplePassword"");
        private string AuthHeader
        {
            get
            {
                if (this.Credentials != null)
                {
                    return string.Format(""Basic {0}"", Convert.ToBase64String(Encoding.GetEncoding(""ISO-8859-1"").GetBytes(this.Credentials.UserName + "":"" + this.Credentials.Password)));
                }
                else
                {
                    return string.Empty;
                }
            }
        }

        private HttpClient Client =&gt; this.httpClient = this.httpClient ?? new HttpClient();
        public async Task&lt;T&gt; Get&lt;T&gt;(string url, IDictionary&lt;string, string&gt; parameters, IDictionary&lt;string, string&gt; headers = null)
        {
            var result = await this.DoRequest(url, HttpMethod.Get, parameters, null, headers);
            if (typeof (T) == typeof (string))
            {
                return (T)(object)result;
            }
            else
            {
                return Newtonsoft.Json.JsonConvert.DeserializeObject&lt;T&gt;(result);
            }
        }

        private async Task&lt;string&gt; DoRequest(string url, HttpMethod method, IDictionary&lt;string, string&gt; urlParams = null, object bodyObject = null, IDictionary&lt;string, string&gt; headers = null)
        {
            string fullRequestUrl = string.Empty;
            HttpResponseMessage response = null;
            if (headers == null)
            {
                headers = new Dictionary&lt;string, string&gt;();
            }

            if (this.Credentials != null)
            {
                headers.Add(""Authorization"", this.AuthHeader);
            }

            headers.Add(""Accept"", ""application/json"");
            fullRequestUrl = string.Format(""{0}{1}{2}"", this.Host.ToString(), url, urlParams?.ToQueryString());
            using (var request = new HttpRequestMessage(method, fullRequestUrl))
            {
                request.AddHeaders(headers);
                if (bodyObject != null)
                {
                    request.Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(bodyObject), System.Text.Encoding.UTF8, ""application/json"");
                }

                response = await this.Client.SendAsync(request).ConfigureAwait(false);
            }

            var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
            if (!response.IsSuccessStatusCode)
            {
                var errDesc = response.ReasonPhrase;
                if (!string.IsNullOrEmpty(content))
                {
                    errDesc += "" - "" + content;
                }

                throw new HttpRequestException(string.Format(""RestfulService: Error sending request to web service URL {0}. Reason: {1}"", fullRequestUrl, errDesc));
            }

            return content;
        }
    }
</code></pre>

<p>As you can see from the implementation it's a pretty thin wrapper that handles things like adding the auth headers (pulled from config) and some other small basic things. </p>

<p>My question: How can I mock the call to <code>Client.SendAsync</code> to return predetermined responses to verify deserialization is happening properly and that the auth headers are added? Would it make more sense to move the adding of the auth headers out of <code>DoRequest</code> and Mock the implementation of <code>DoRequest</code> before running my test?</p>
",https://stackoverflow.com/questions/53382348/unit-testing-class-that-wraps-httpclient,"['c#', 'unit-testing', 'xunit']",1177,TRUE,1,1
Unit testing and mocking domain objects,"<p>I have a domain class, which looks like this:</p>

<pre><code>public class Employee
{
    public Guid EmployeeId { get; private set; }
    public string Name { get; private set; }
    public string Surname { get; private set; }
    ...
    // other properties

    public ICollection&lt;Language&gt; Languages { get; private set; }
        = new List&lt;Language&gt;();

    public ICollection&lt;Skill&gt; Skills { get; private set; }
        = new List&lt;Skill&gt;();

    public void AddLanguage(Language language)
    {
        if (language == null)
            return;

        Languages.Add(language);
    }

    public void DeleteLanguage(Guid languageId)
    {
        var languageToDelete = Languages
            .SingleOrDefault(x =&gt; x.LanguageId == languageId);

        if(languageToDelete == null)
            throw new ArgumentException(""Language entry doesn't exist."");

        Languages.Remove(languageToDelete);
    }
}
</code></pre>

<p>I would like to test given methods but I'm stuck.</p>

<p>I have:</p>

<pre><code>    [Fact]
    public void AddLanguage_AfterCallWithValidObject_LanguagesCollectionContainsAddedObject()
    {
        var language = new Mock&lt;Language&gt;();
        var employee = new Employee(""Name"", ""Surname"", ...);

        employee.AddLanguage(language.Object);

        Assert.Contains(employee.EmployeeLanguages, x =&gt; x.Language.Equals(language.Object));
    }

    [Fact]
    public void DeleteLanguage_WhenLanguageWithGivenIdDoesntExist_ThrowArgumentException()
    {
        var languageToDelete = new Language(""English"");

        var employee = new Mock&lt;Employee&gt;();
        employee.Setup(x =&gt; x.Languages).Returns(new List&lt;Languages&gt;
        {
            new Language(""Spanish""),
            new Language(""German"")
        });

        employee.Object.DeleteLanguage(languageToDelete);

        // Asserts here
    }
</code></pre>

<p>In the first test I would like also assert that <strong>Languages.Add(skill)</strong> method was called but I have no idea how to do it.</p>

<ol>
<li>Is it an elegant way to do it? I thought about mocking <strong>Add</strong> method but I'm not sure if it is a good idea.</li>
</ol>

<p>In the second test I cannot simply mock <strong>Employee</strong> object as it is not an interface.
I thought about exposing <strong>Employee</strong> but I read I should not do that just for testing purpose. </p>

<ol start=""2"">
<li>How should I mock <strong>Languages</strong> property without exposing <strong>Employee</strong> as interface? Is it possible? Is it any good practice to do this kind of things?</li>
<li>Is my general concept for test these methods is okay? (I'm new in unit testing)</li>
</ol>
",https://stackoverflow.com/questions/52614135/unit-testing-and-mocking-domain-objects,"['c#', 'unit-testing']",2972,TRUE,0,2
Angular 6 Unit Testing Dependant Promises,"<p>I am new to Angular and I am currently writing unit tests for my application. I am really puzzled and can't seem to get any furthur with writing Unit Tests for my current task.
My component makes use of the following method: </p>

<pre><code>async updateLevelModes(level: Level) {
    const updateModes: Promise&lt;any&gt;[] = [];
    for(let mode of level.Modes) {
      const updateMode = this.modeService.updateMode(mode);
      updateModes.push(updateMode);
    }
    await Promise.all(updateModes);
    const update = await this.LevelService.updateLevel(level);
    level.Id = update._id;
  }
</code></pre>

<p>It makes use of two services, the modeService and the levelService.</p>

<p>My LevelService.ts looks like this</p>

<pre><code>async updateLevel(level: Level): Promise&lt;void&gt; {
    const formdata = new FormData();
    formdata.append('Name', level.Name);
    formdata.append('Description', level.Description);
    formdata.append('ImageFile', level.ImageFile);

    const resultLevel = await this.http.put&lt;IStep&gt;(this.postStepsUrl+'/'+step.Id, formdata)
      .pipe(catchError(this.errorHandler))
      .toPromise&lt;IStep&gt;();
    this.HandleStepResult(Level, resultLevel);
  }
</code></pre>

<p>How should I write a test for such a complicated method ? Kindly help</p>
",https://stackoverflow.com/questions/53376060/angular-6-unit-testing-dependant-promises,"['angular', 'typescript', 'http', 'testing', 'jasmine']",391,FALSE,0,1
Css Style unit testing in jasmine,"<p>how to unit test  css of a node in enzyme</p>

<p>.toHaveStyle() is not working for me</p>

<p>any other enzyme matcher to test the css?</p>

<p><a href=""https://github.com/FormidableLabs/enzyme-matchers"" rel=""nofollow noreferrer"">this</a> is not working</p>
",https://stackoverflow.com/questions/50098082/css-style-unit-testing-in-jasmine,"['reactjs', 'jasmine', 'karma-jasmine', 'enzyme', 'jasmine2.0']",775,TRUE,0,1
Unit testing for iOS in swift,"<p>I am planning to use MVC or VIPER architecture to use.
How do I make the unit testing?
How should the unit testing be done for different design patterns?
Should all the methods be tested or only non-private methods?</p>
",https://stackoverflow.com/questions/49939389/unit-testing-for-ios-in-swift,"['ios', 'objective-c', 'swift', 'xcode', 'unit-testing']",301,TRUE,0,1
Unit Testing ODataQueryOptions Gives MissingMethodException DependencyInjection,"<p>So here is my problem, I have an OData Web Api service that uses ODataQueryOptions to filter data from our sql server and I am trying to setup a .Net Framework Unit Test project to test the controllers with different query options.  I have been searching for several days now and found many examples but most of them use an older version of OData.  <a href=""https://stackoverflow.com/questions/40504289/how-to-correctly-unit-test-odata-v6-0-controller/40526448"">This example</a> is the best one I have found so far, the only problem is that calling config.EnableDependencyInjection(); gives me the following exception:</p>

<p>Method not found: 'System.IServiceProvider Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(Microsoft.Extensions.DependencyInjection.IServiceCollection)'.</p>

<p>Here is an example of my code:</p>

<pre><code>using System.Collections.Generic; 
using System.Web.Http.Results;
using System.Web.OData;
using System.Web.OData.Query;
using System.Net.Http;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using University.API.OData.Controllers;
using University.API.OData.Models;
using System.Web.OData.Routing;
using System.Web.Http;
using System.Web.OData.Extensions;

[TestClass]
public class SalesforceUnitTest
{
    private HttpRequestMessage request;
    private ODataQueryOptions&lt;Product&gt; _options;

    [TestInitialize]
    public void TestInitialize()
    {
        request = new HttpRequestMessage(HttpMethod.Get, ""http://localhost/odata/product?$top=5"");
        var model = WebApiConfig.GetModel();

        HttpConfiguration config = new HttpConfiguration();
        config.EnableDependencyInjection(); //Throws Missing Method Exception
        WebApiConfig.Register(config);
        config.EnsureInitialized();
        request.SetConfiguration(config);

        ODataQueryContext context = new ODataQueryContext(
            model,
            typeof(Product),
           new ODataPath(
               new Microsoft.OData.UriParser.EntitySetSegment(
                    model.EntityContainer.FindEntitySet(""product""))
            )
        );

        _options = new ODataQueryOptions&lt;Product&gt;(context, request);
    }

    [TestMethod]
    public void ProductTest()
    {
        var controller = new ProductController();
        controller.Request = request;
        var response = controller.Get(_options);
        var contentResult = response as OkNegotiatedContentResult&lt;List&lt;Product&gt;&gt;;

        Assert.IsNotNull(contentResult);
        Assert.IsNotNull(contentResult.Content);
    }
}
</code></pre>

<p>Let me know if there is any other information you may need.
Thank you for any help you can provide.</p>

<p>EDIT:
Here what is referenced in the unit test project:</p>

<pre><code>EntityFramework
EntityFramework.SqlServer
Microsoft.Data.Edm
Microsoft.Data.OData
Microsoft.Extensions.DependencyInjection
Microsoft.Extensions.DependencyInjection.Abstractions
Microsoft.OData.Core
Microsoft.Odata.Edb
Microsoft.Spatial
Microsoft.Threading.Tasks
Microsoft.Threading.Tasks.Extensions
Microsoft.Threading.Tasks.Extensions.Desktop
Microsoft.VisualStudio.TestPlatform.TestFramework
Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions
System
System.ComponentModel.DataAnnotations
System.Net
System.Net.Http
System.Net.Http.Extensions
System.Net.Http.Primitives
System.Net.Http.WebRequest.
System.Spatial
System.Web
System.Web.Http
System.Web.OData
ODataAPI
</code></pre>
",https://stackoverflow.com/questions/49134647/unit-testing-odataqueryoptions-gives-missingmethodexception-dependencyinjection,"['unit-testing', 'dependency-injection', 'asp.net-web-api2', 'odata', 'missingmethodexception']",577,TRUE,0,1
DB Setup Unit testing in Dropwizard,"<p>I have a Dropwizard application and I am trying to create unit tests for testing the application. </p>

<p>I read through a bunch of resources and I am now using DropwizardTestRule to kickstart the application and run some unit tests. I also have a custom config-test.yml that I use to point the application to my local database to run the queries against.</p>

<p>And the Dropwizard version we are using is 0.9.2. That is unfortunately a constraint that cannot be changed at the moment.</p>

<p>The problem I have is running migrations on the DB before the test suite runs.</p>

<p>The issue is:</p>

<ul>
<li><code>mvn package</code> runs unit tests as part of the packaging task. </li>
<li>Unit tests need that migrations be run as a pre-requisite. </li>
<li>Running migrations need the jar created by <code>mvn package</code> as a pre-requisite. </li>
</ul>

<p>This seems like a cyclic dependency to me that can be resolved only by first calling <code>mvn package -DskipTests=true</code> which leads to the <code>jar</code> creation. Then running the migrations. Then running the tests as a separate maven task. </p>

<p>This means my build will now have to be a script of commands. Is there a better way of doing this? Or is this the only hack? </p>

<p>How do I tell Dropwizard to run the migrations before running the test suite? </p>
",https://stackoverflow.com/questions/51000615/db-setup-unit-testing-in-dropwizard,"['java', 'maven', 'unit-testing', 'dropwizard']",328,FALSE,0,0
Unit testing side effects in Elixir,"<p>I'm writing a unit test for a function that calls out to module as part of a side effect of invoking it:</p>

<pre><code>defmodule HeimdallrWeb.VerifyController do
  use HeimdallrWeb, :controller

  def verify(conn, _params) do
    [forwarded_host | _tail] = get_req_header(conn, ""x-forwarded-host"")

    case is_preview_page?(forwarded_host) do
      {:ok, false} -&gt;
        conn |&gt; send_resp(200, """")

      {:ok, %Heimdallr.Commits.Commit{} = commit} -&gt;
        Heimdallr.Commits.touch_commit(commit)
        conn |&gt; send_resp(200, """")

      {:not_found, _reason} -&gt;
        conn |&gt; send_resp(200, """")
    end
  end
end
</code></pre>

<p>The side effect is triggered from the line <code>Heimdallr.Commits.touch_commit(commit)</code>.</p>

<p>A few questions about this:</p>

<ol>
<li>Should my unit test be concerned with testing the effects of the <code>touch_commit</code> method.</li>
<li>If so, should I think about passing in a generic ""touch"" function to verify method to make it easier to test. This might be difficult due to the nature of Phoenix / Elixirs routing system, I haven't investigated.</li>
</ol>

<p>If I was using Rails / Ruby / Rspec then I'd set an expectation that a class level method would be called on the <code>HeimdallrCommits</code> module.</p>

<p>My concern and reason for writing the test is that in the future I may accidentally remove the functionality that is touching a commit by deleting or commenting out the line etc.</p>
",https://stackoverflow.com/questions/49838182/unit-testing-side-effects-in-elixir,"['unit-testing', 'elixir', 'phoenix-framework']",156,FALSE,0,1
Unit testing a function with callbacks,"<p>I have a function in node.js:</p>

<pre><code>fs.readdir(filesPath, function(err, items) {

    items.forEach(function(filename){


        fs.readFile(path.join(filesPath,filename), {encoding: 'utf-8'}, function (err,data){

        //do some calculations with data from each file, the result is an object 'finalOutput'


    fs.stat(path.join(__dirname,'output.csv'), function (err, stat) {
        //check if file exists

            fs.appendFile(path.join(__dirname,'output.csv'), csv, function (err) {
            // append output to csv 
    });
}
        else {
            //create file

            fs.writeFile(path.join(__dirname,'output.csv'), fields, function (err, stat) {
            if (err) console.log(err);
            console.log('File saved');
    });
}
});



   })
  })
});
</code></pre>

<p>I would like to write tests on the 'finalOutput' variable, the content of the files (for example, if a file is empty the output should be X, and so on), and the existence of output files. But when I run npm test (I am using mocha and chai, I get ' TypeError: Cannot read property 'to' of undefined at Context')</p>

<p>This is an example of a test I want to run:</p>

<pre><code>var chai = require('chai'),
expect = chai.expect,
mypreviouscode = require('./mypreviouscode');

describe('test1', function() {
it('There output should always exist', function() {
expect(finalOutput.to.exist);
});
});
</code></pre>
",https://stackoverflow.com/questions/48973312/unit-testing-a-function-with-callbacks,"['javascript', 'node.js', 'mocha.js', 'chai']",563,FALSE,0,1
Unit testing multiple branches with git,"<p>I am using Jest unit testing in a folder called <strong>test</strong> in root, and I am trying to unit test nodejs on multiple branches. Are project is set in a git repository. When my team is done with a branch they will merge it with master. Normally I'd work on master if I was using code, but I'd like to do some things on their branches. Usually I don't touch other branches if the code isn't complete, but since this is for the intent of unit testing their code, and not developing it, I think it's ok to look at their latest commits on branch1 and branch2. Am I correct that this is correct to do so, and if so what would be the best way to use git in this situation?</p>

<p>EDIT - The main problem is that they will not merge without having large changes in between merging, and what I test now can and will be vastly different than what it was on master.</p>

<p>This is how my team is expecting me to solve the issue, but I'm starting to think that the issue itself is how my team using git on a whole separate branch.</p>
",https://stackoverflow.com/questions/48105282/unit-testing-multiple-branches-with-git,"['git', 'unit-testing']",558,FALSE,-2,1
Unit testing a randomly generated string,"<p>I have the following method:</p>

<pre><code>generateKey: () =&gt; {
    let key = Math.random()
      .toString(36)
      .substring(2, 10);

    return key;
  }
</code></pre>

<p>This method generates a random character string and I wish to unit test it.</p>

<p>After searching how to unit test randomness I've come across the following answers but not a concrete application:</p>

<ul>
<li><a href=""https://stackoverflow.com/questions/186619/how-to-unit-test-a-pseudo-random-number-generator"">Answer 01</a></li>
<li><a href=""https://stackoverflow.com/questions/311807/unit-testing-with-functions-that-return-random-results"">Answer 02</a></li>
</ul>

<p>How may I test randomness in this specific case?</p>

<p>Testing the length of the string and its content is simple enough, but testing that values were truly generated randomly seems impossible. </p>
",https://stackoverflow.com/questions/53590135/unit-testing-a-randomly-generated-string,"['unit-testing', 'testing']",1594,TRUE,0,1
Eclipse Unit Testing window is missing,"<p>I got a question about Eclipse ( Im on 4.7.3 afaik ) . I want to know where I could get this C++/C Unit testing Window ?</p>

<p><a href=""https://i.imgur.com/618s6St.png"" rel=""nofollow noreferrer""><img src=""https://i.imgur.com/618s6St.png"" alt=""JUnit window""></a></p>

<p>It's missing in my Eclipse and the Test is just running in the console like this <a href=""https://coderwall-assets-0.s3.amazonaws.com/uploads/picture/file/648/Schermata_2012-10-06_alle_00.25.40.png"" rel=""nofollow noreferrer"">https://coderwall-assets-0.s3.amazonaws.com/uploads/picture/file/648/Schermata_2012-10-06_alle_00.25.40.png</a></p>
",https://stackoverflow.com/questions/50080042/eclipse-unit-testing-window-is-missing,"['java', 'c++', 'eclipse', 'unit-testing', 'junit']",310,FALSE,0,1
Unit testing of Jenkins Shared Library,"<p>Can anyone suggest me the best way to create unit test cases for Jenkins pipeline Shared library?  </p>
",https://stackoverflow.com/questions/52647127/unit-testing-of-jenkins-shared-library,"['unit-testing', 'jenkins', 'shared-libraries']",1996,TRUE,-1,2
Unit Testing for async Task&lt;ActionResult&gt;,"<p>I am very new to ASP.NET CORE MVC and I was wondering if anyone could help me about my problem. </p>

<p>I was working in a project that will get all projects within a specific azure devops organization. </p>

<p>Here is my controller code: </p>

<pre><code>public async Task&lt;ActionResult&gt; Organization(string selectedOrg, string oauth)
{
    var client = new HttpClient();
    IndexViewModel model = new IndexViewModel();
    model.Organizations = OrganizationData.Data;
    if (selectedOrg == null)
    {
        selectedOrg = model.Organizations.FirstOrDefault().OrgName;
    }
    else
    {
        model.SelectedOrg = selectedOrg;
    }
    var token = _cache.Get&lt;TokenModel&gt;(""Token"" + HttpContext.Session.GetString(""TokenGuid""));
    oauth = token.AccessToken;
    var url = ""https://dev.azure.com/"" + selectedOrg + ""/_apis/projects?api-version=4.1"";
    try
    {
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(""Bearer"", oauth);

        var response = await client.GetAsync(url);
        var responseBody = response.Content.ReadAsStringAsync().Result;
        model.Projects = JsonConvert.DeserializeObject&lt;ProjectsModel&gt;(responseBody);

        client.Dispose();
        return View(""Index"", model);
    }
    catch(Exception e)
    {
        client.Dispose();
        return Json(Newtonsoft.Json.JsonConvert.DeserializeObject&lt;dynamic&gt;(e.ToString()));
    }
}
</code></pre>

<p>Can anyone help how to do unit testing with this one? Or do I have to refactor this one? </p>
",https://stackoverflow.com/questions/52972478/unit-testing-for-async-taskactionresult,"['c#', 'unit-testing', 'asp.net-core-mvc']",1331,TRUE,0,1
unit testing C function expecting SIGSEGV,"<p>I am trying to unit test C/glibc code that I know results in undefined behaviour, but will fail with SEGV given appropriate the compiler options. Something like:</p>

<pre><code>void will_fail(char *bar) {
    bar[10000] = 'X';
}

void test_will_fail(void) {
    will_fail(""foo"");    // How can I handle this failing?
}
</code></pre>

<p>Is there a way to trap the next SEGV, possibly GCC specific or asm? If it needs a separate address space (fork/exec), what is a good way to tell that the spawned process ended with SEGV?</p>

<p>I am using c11 / x86-64 / glibc 2.26 / gcc 7.2.0 with -fsanitize=address / CUnit (which does not use a separate address space for unit tests). The only hard requirement is to stay in the realm of C.</p>

<p>Any guidance is much appreciated. Thanks!</p>
",https://stackoverflow.com/questions/50787353/unit-testing-c-function-expecting-sigsegv,"['c', 'testing', 'signals', 'glibc', 'segmentation-fault']",156,FALSE,0,0
Unit Testing the promises in JEST,"<p>The issue is regarding the unit testing using JEST.
How to test the a function X which is returning a promise which is making an async HTTP request. </p>

<p>Function X</p>

<pre><code>import httpHelper from './httpHelper';    

function fetchMoxtraAccessToken(userEWAToken, successCallback, failureCallback) {
        const httpObj = {
            url: '/getAccessToken',
            headers: { Authorization: userEWAToken },
        };

        return httpHelper(httpObj, successCallback, failureCallback);
    }
</code></pre>

<p>How to unit test the function X on the basis of the response?</p>
",https://stackoverflow.com/questions/48316070/unit-testing-the-promises-in-jest,"['promise', 'jestjs']",308,TRUE,0,1
Unit testing Camel/RabbitMQ routes issue,"<p>I'm having issue <strong>unit testing</strong> a camel route which uses rabbitmq for the broker.</p>

<p>I've been researching for weeks but haven't found an effective way to do this.</p>

<p>Firstly, I was having an issue with <strong>NOT calling rabbitmq</strong> in my test, and to keep this a unit test and not an integration test. This was achieved by using <strong>advicewith</strong> and switch out the queue for mock queues.</p>

<p>However, with the following code the messages are not reaching the result or end queue (MOBILE_QUEUE).</p>

<p><code>java.lang.AssertionError: mock://result Received message count. Expected: &lt;1&gt; but was: &lt;0&gt;
Expected :&lt;1&gt; 
Actual   :&lt;0&gt;</code></p>

<hr>

<p>Here is my <strong>route</strong>, which imports rabbitmq.class</p>

<p><code>from(TEST_QUEUE).to(MOBILE_QUEUE).routeId(""test2phone"");</code></p>

<p>My config <strong>rabbitmq.class</strong></p>

<pre><code>@Component
public class RabbitMQ extends Properties {

    public final String TEST_QUEUE = CreateRabbitMQQueue(""TestQueue"", ""camel"");
    public final String MOBILE_QUEUE = CreateRabbitMQQueue(""MobileQueue"", ""camel"");

    public static String CreateRabbitMQQueue(String QueueName, String RoutingKey)
    {
        String hostv;
        String portv;
        String username;
        String password;

        hostv = ""mq-staging"";
        portv = System.getenv(""SERVICE_PORT_AMQP"");
        username = System.getenv(""V_RABBIT_USERNAME"");
        password = System.getenv(""V_RABBIT_PASSWORD"");

        UriComponentsBuilder uriBuilder = UriComponentsBuilder
                .fromPath(""/"" )
                .scheme(""rabbitmq"")
                .host(hostv)
                .port(portv)
                .path(""/"" + QueueName)
                .queryParam(""username"",username)
                .queryParam(""password"", password)
                .queryParam(""routingKey"",RoutingKey)
                .queryParam(""queue"",""Q"" + QueueName);

        return uriBuilder.toUriString();
    }
</code></pre>

<p>}</p>

<p>And my <strong>unit test</strong></p>

<pre><code>@RunWith(CamelSpringRunner.class)
@MockEndpoints
@UseAdviceWith
@SpringBootTest
public class RouteTester extends CamelTestSupport {

    String TEST_QUEUE;
    String MOBILE_QUEUE;

    @Autowired
    Routes routes;

    @Autowired
    CamelContext context;

    @Autowired
    ProducerTemplate template;

    @Before
    public void setUp() throws Exception {
        TEST_QUEUE = routes.getTEST_QUEUE();
        MOBILE_QUEUE = routes.getMOBILE_QUEUE();
        context.getRouteDefinition(""test2phone"").adviceWith(context, new Routes() {
            @Override
            public void configure() throws Exception {
                interceptSendToEndpoint(TEST_QUEUE)
                        .skipSendToOriginalEndpoint()
                        .to(""mock:testQ"");
                interceptSendToEndpoint(MOBILE_QUEUE)
                        .skipSendToOriginalEndpoint()
                        .to(""mock:result"");
            }
        });
        context.start();
    }

    @Test
    public void testTest() throws Exception {
        String body = ""hello123"";

        MockEndpoint resultEndpoint = context.getEndpoint(""mock:result"", MockEndpoint.class);

        resultEndpoint.expectedMessageCount(1);
        resultEndpoint.expectedBodiesReceived(body);
        template.sendBody(TEST_QUEUE, body);
        resultEndpoint.assertIsSatisfied();
    }

    @After
    public void TearDown() throws Exception {
        context.stop();
    }
</code></pre>

<p>}</p>
",https://stackoverflow.com/questions/50061071/unit-testing-camel-rabbitmq-routes-issue,"['spring-boot', 'rabbitmq', 'apache-camel']",1228,TRUE,0,1
Unit testing SSL pinning with URLProtocol,"<p><strong>Aim:</strong> Unit test app's ssl pinning</p>

<p><strong>Approximate implementation aimed for:</strong></p>

<ol>
<li>subclass URLProtocol</li>
<li>Insert custom URLProtocol into Session's configuration</li>
<li>Use session with custom config when generating requests</li>
<li>catch the request and generate response with local certificate</li>
<li>expect that when the app receives the response it will detect the same certificate</li>
</ol>

<p><strong>Problem encountered:</strong></p>

<p>There seems to be no authentication challenge method to subclass in the URLProtocol.</p>

<p><strong>Question:</strong></p>

<p>How to intercept auth challenge with URLProtocol?</p>
",https://stackoverflow.com/questions/52482261/unit-testing-ssl-pinning-with-urlprotocol,"['ios', 'ssl-certificate', 'nsurlprotocol', 'public-key-pinning', 'custom-url-protocol']",375,FALSE,0,0
java - unit testing for REST request,"<p>I have the method:</p>

<pre><code>public HTTPResult get(String url) throws Exception{
        try {
            ResponseEntity&lt;String&gt; response = restTemplate.getForEntity(url, String.class);
            return new HTTPResult(response.getBody(), response.getStatusCode().value());
        }
        catch (ResourceAccessException e) {
            String responseBody = e.getCause().getMessage();
            JSONObject obj = new JSONObject(responseBody);
            return new HTTPResult(obj.getString(""responseBody""), Integer.parseInt(obj.getString(""statusCode"")));
        }
    }
</code></pre>

<p>I want to do unit testing for it and i am not sure how to proceed:</p>

<pre><code>public class MockHttpServerTest {

    private static final int PORT = 51234;
    private static final String baseUrl = ""http://localhost:"" + PORT;
    private MockHttpServer server;
    private SimpleHttpResponseProvider responseProvider;
    private HttpClient client;

    @Before
    public void setUp() throws Exception {
        responseProvider = new SimpleHttpResponseProvider();
        server = new MockHttpServer(PORT, responseProvider);
        server.start();
        client = new DefaultHttpClient();
    }
</code></pre>

<p>I am getting RED for MockHttpServer &amp; SimpleHttpResponseProvider which should be part of org.apache.wink.client.*; which i am importing. so why do i have red ones? is there some simple way to unit test it?
HTTPResult return me response code and message.</p>
",https://stackoverflow.com/questions/52836565/java-unit-testing-for-rest-request,"['java', 'rest', 'unit-testing']",46,FALSE,0,0
Unit testing Prism based WPF application,"<p>I want to unit test a Prism based WPF application. It is a huge application with multiple projects. Each project is based on MVVM design pattern that is it has ViewModel/Views. This application uses Bootstrapper for initialization, uses regions concept and has event handling.</p>

<p>I tried using xunit. I took one project and added a corresponding test project where I tried to implement one test case. In the test case, I created an instance of View class (code behind) and tried to invoke a method from that class. I got the below errors:</p>

<pre><code>*****************

------ Run test started ------
[xUnit.net 00:00:00.3423646]   Discovering: Demo.Test
[xUnit.net 00:00:01.2217151]   Discovered:  Demo.Test
[xUnit.net 00:00:01.2260195]   Starting:    Demo.Test
[xUnit.net 00:00:02.5700093]     TestClassLibrary.TestDemo.TestCase1 [FAIL]
[xUnit.net 00:00:02.5722687]       System.InvalidOperationException : The calling thread must be STA, because many UI components require this.
[xUnit.net 00:00:02.5739943]       Stack Trace:
[xUnit.net 00:00:02.5749537]            at System.Windows.Input.InputManager..ctor()
[xUnit.net 00:00:02.5754038]            at System.Windows.Input.InputManager.GetCurrentInputManagerImpl()
[xUnit.net 00:00:02.5757829]            at System.Windows.Input.KeyboardNavigation..ctor()
[xUnit.net 00:00:02.5762326]            at System.Windows.FrameworkElement.FrameworkServices..ctor()
[xUnit.net 00:00:02.5766521]            at System.Windows.FrameworkElement.EnsureFrameworkServices()
[xUnit.net 00:00:02.5771316]            at System.Windows.FrameworkElement..ctor()
[xUnit.net 00:00:02.5775379]            at System.Windows.Controls.Control..ctor()
[xUnit.net 00:00:02.5792034]            at System.Windows.Controls.UserControl..ctor()
[xUnit.net 00:00:02.5796505]            at Demo.Views.DemoLandingPage..ctor(IDemoViewModel vwModel, IEventAggregator eventAggregator, ISharedService sharedService)
[xUnit.net 00:00:02.5801319]         Demo.Test\Class1.cs(65,0): at TestClassLibrary.TestDemo.&lt;TestCase1&gt;b__0_0()
[xUnit.net 00:00:02.5805993]            at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
[xUnit.net 00:00:02.5810366]            at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
[xUnit.net 00:00:02.5814870]            at System.Windows.Threading.DispatcherOperation.InvokeImpl()
[xUnit.net 00:00:02.5819703]            at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
[xUnit.net 00:00:02.5825284]            at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
[xUnit.net 00:00:02.5831148]            at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
[xUnit.net 00:00:02.5834395]            at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
[xUnit.net 00:00:02.5837782]            at MS.Internal.CulturePreservingExecutionContext.Run(CulturePreservingExecutionContext executionContext, ContextCallback callback, Object state)
[xUnit.net 00:00:02.5842970]            at System.Windows.Threading.DispatcherOperation.Invoke()
[xUnit.net 00:00:02.5848709]            at System.Windows.Threading.Dispatcher.ProcessQueue()
[xUnit.net 00:00:02.5852488]            at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean&amp; handled)
[xUnit.net 00:00:02.5857359]            at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean&amp; handled)
[xUnit.net 00:00:02.5863023]            at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
[xUnit.net 00:00:02.5867150]            at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
[xUnit.net 00:00:02.5872700]            at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
[xUnit.net 00:00:02.5877817]            at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
[xUnit.net 00:00:02.5883386]            at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
[xUnit.net 00:00:02.5889004]            at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG&amp; msg)
[xUnit.net 00:00:02.5894200]            at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
[xUnit.net 00:00:02.5899856]            at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
[xUnit.net 00:00:02.5905323]            at System.Windows.Threading.DispatcherOperation.Wait(TimeSpan timeout)
[xUnit.net 00:00:02.5910927]            at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherOperation operation, CancellationToken cancellationToken, TimeSpan timeout)
[xUnit.net 00:00:02.5915975]            at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
[xUnit.net 00:00:02.5921129]         Demo.Test\Class1.cs(63,0): at TestClassLibrary.TestDemo.TestCase1()
[xUnit.net 00:00:02.6178918]   Finished:    Demo.Test
========== Run test finished: 1 run (0:00:03.1364452) ==========

*****************
</code></pre>

<p>This is the test case code:</p>

<pre><code>************* Class1.cs ******
namespace TestClassLibrary
{
    public class TestDemo
    {
[Fact]
        public void TestCase1()
        {
                if (Application.Current == null)
                {
                    if (System.Windows.Application.Current == null)
                    {
                        new System.Windows.Application { ShutdownMode = ShutdownMode.OnExplicitShutdown };
                    }
                }

(LINE 63)                    Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =&gt;
                {
(LINE 65)                    DemoLandingPage dem = new DemoLandingPage(null, null, null);
                    List&lt;string&gt; countryList = dem.GetCountryList(""CountryList"");
                    bool ret = searchCountry(""Test"", countryList);
                    Assert.True(ret == true);
                }));

        }

        bool searchCountry(string country, List&lt;string&gt; list)
        {
            return list.Contains(country);
        }    

*************
</code></pre>

<p>I would like to know:</p>

<p>Is it possible to unit test Prism based WPF application? If so, could you please let me know what should be my approach to test this application. Any pointers or documents/links would be of great help.</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/51322860/unit-testing-prism-based-wpf-application,"['c#', 'wpf', 'xunit']",974,FALSE,0,0
ngx-translate: Translate string in Unit Testing,"<p>I can get the value if it's a static test, but whenever I'm trying to get the translated value (using <code>ngx-translate</code>), it's empty.</p>

<pre><code>&lt;div id=""header-title""&gt;
    &lt;h1&gt;{{ 'MENU_TITLE' | translate | uppercase }}&lt;/h1&gt;
&lt;/div&gt;
</code></pre>

<p><strong>This works</strong> and returns <code>Test</code></p>

<pre><code>&lt;div id=""header-title""&gt;
    &lt;h1&gt;Test&lt;/h1&gt;
&lt;/div&gt;
</code></pre>

<p><strong>spec.ts</strong></p>

<pre><code>it('should translate a string using the key value', () =&gt; {
    fixture = TestBed.createComponent(NavComponent);
    const title = fixture.nativeElement;
    console.log(title.querySelector('#header-title h1').innerHTML);
});
</code></pre>

<p><strong>Importing translate module</strong></p>

<pre><code>beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
            imports: [RouterTestingModule,
                TranslateModule.forRoot({
                    loader: {
                        provide: TranslateLoader,
                        useFactory: HttpLoaderFactory,
                        deps: [HttpClient]
                    }
                }),
                HttpClientModule
            ],
            declarations: [NavComponent]
        }).compileComponents();

        injector = getTestBed();
        translate = injector.get(TranslateService);
    }));
</code></pre>

<p><strong>-----FIXED-----</strong> but not sure if this is the right way to do</p>

<pre><code>let fixture: ComponentFixture&lt;NavComponent&gt;;

it('should translate a string using the key value', () =&gt; {
    fixture.detectChanges() // fixture = TestBed.createComponent(NavComponent);
    const title = fixture.nativeElement;
    console.log(title.querySelector('#header-title h1').innerHTML);
});
</code></pre>
",https://stackoverflow.com/questions/49172531/ngx-translate-translate-string-in-unit-testing,"['angular', 'unit-testing', 'typescript', 'karma-jasmine', 'ngx-translate']",15032,TRUE,7,2
Unit testing Reader build by JsonItemReaderBuilder,"<p>I have a class which contains Beans used in a Batch Job:</p>

<pre><code>@Configuration
public class JobBeans { 
    @Bean
    JsonItemReader&lt;Rabbit&gt; jsonReader() {
        return new JsonItemReaderBuilder&lt;Rabbit&gt;()
            .jsonObjectReader(new JacksonJsonObjectReader&lt;&gt;(Rabbit.class))
            .resource(new ClassPathResource(""rabbits.json""))
            .name(""rabbitReader"")
            .build();
    }
}
</code></pre>

<p>How can I test Beans like this?</p>

<p>My current Test Suite looks like that:</p>

<pre><code>@ContextConfiguration(classes = JobBeans.class)
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, StepScopeTestExecutionListener.class })
@RunWith(SpringRunner.class)
public class RabbitReaderTest {

    @Autowired
    private JsonItemReader&lt;Rabbit&gt; sut;

    @Test
    public void read() throws Exception {
        assertNotNull(sut.read());
    }
}
</code></pre>

<p>It throws a NPE during test execution:</p>

<blockquote>
  <p>10:40:07.684 [Thread-0] WARN
  org.springframework.beans.factory.support.DisposableBeanAdapter -
  Invocation of destroy method 'close' failed on bean with name
  'rabbitReader'
  org.springframework.batch.item.ItemStreamException: Error while
  closing item reader   at
  org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader.close(AbstractItemCountingItemStreamItemReader.java:138)
    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.beans.factory.support.DisposableBeanAdapter.invokeCustomDestroyMethod(DisposableBeanAdapter.java:364)
    at
  org.springframework.beans.factory.support.DisposableBeanAdapter.destroy(DisposableBeanAdapter.java:287)
    at
  org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroyBean(DefaultSingletonBeanRegistry.java:578)
    at
  org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingleton(DefaultSingletonBeanRegistry.java:554)
    at
  org.springframework.beans.factory.support.DefaultListableBeanFactory.destroySingleton(DefaultListableBeanFactory.java:961)
    at
  org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.destroySingletons(DefaultSingletonBeanRegistry.java:523)
    at
  org.springframework.beans.factory.support.DefaultListableBeanFactory.destroySingletons(DefaultListableBeanFactory.java:968)
    at
  org.springframework.context.support.AbstractApplicationContext.destroyBeans(AbstractApplicationContext.java:1033)
    at
  org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:1009)
    at
  org.springframework.context.support.AbstractApplicationContext$2.run(AbstractApplicationContext.java:928)
  Caused by: java.lang.NullPointerException: null   at
  org.springframework.batch.item.json.JacksonJsonObjectReader.close(JacksonJsonObjectReader.java:89)
    at
  org.springframework.batch.item.json.JsonItemReader.doClose(JsonItemReader.java:123)
    at
  org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader.close(AbstractItemCountingItemStreamItemReader.java:135)
    ... 14 common frames omitted</p>
</blockquote>

<p>It appears that the InputStream is null even though the file is provided in the test resources directory.</p>
",https://stackoverflow.com/questions/52035668/unit-testing-reader-build-by-jsonitemreaderbuilder,"['java', 'spring', 'unit-testing', 'spring-boot', 'spring-batch']",643,TRUE,0,1
Unit Testing a Business Logic Interface,"<p>Am I going about this the right way? And if so, am I understanding it correctly? I am a little confused.</p>

<p>My project is setup in three different layers. The UI Layer, the Business Layer, and the Data Access Layer. The Business Layer and Data Access Layer are both built off of interfaces.</p>

<p>I am attempting to write Unit Tests using NUnit and Moq.</p>

<p>Here is my example. I want to test GetSum(int x, int y), which is a simple function that just returns x + y. This function exists in CalculatorLogic and implements ICalculatorLogic. </p>

<pre><code>public class CalculatorLogic : ICalculatorLogic
{
    public int GetSum(int x, int y)
    {
        return x + y;
    }
}
</code></pre>

<p>Now, here is how I am attempting to write a UnitTest.</p>

<pre><code>[TestFixture]
public class CalculatorLogicTests
{
    Mock&lt;ICalculatorLogic&gt; calculatorLogicMock;
    ICalculatorLogic calculatorLogic;

    public CalculatorLogicTests()
    {
        calculatorLogicMock = new Mock&lt;ICalculatorLogic&gt;();

        // now i need to do this setup, right?
        calculatorLogicMock.Setup(x =&gt; x.GetSum(It.IsAny&lt;int&gt;(), It.IsAny&lt;int&gt;())).Returns(6);

        calculatorLogic = calculatorLogicMock.Object;
    }

    [Test]
    public void GetSum_Test()
    {
        int expectedResult = 3 + 3;

        var sum = calculatorLogic.GetSum(3, 3);
        Assert.AreEqual(sum, expectedResult);
    }
}
</code></pre>

<p>Now, the above passes. It runs, and it gets what I am expecting. However, it feels wrong. It's just returning whatever I set it to return in the Setup() call. If I had put a 3 in the Returns() instead of the 6, it would fail.</p>

<p>I must be understanding something wrong. Otherwise, am I really testing my function if I'm telling it what to return?</p>
",https://stackoverflow.com/questions/50766313/unit-testing-a-business-logic-interface,"['c#', 'nunit', 'moq']",2386,FALSE,0,1
Unit testing with Time Zone offset,"<p>I have worked with function in angular 5 using moment:</p>

<pre><code>moment('2013-12-01', 'YYYY-MM-DD').utcOffset('America/Los_Angeles')
    .startOf('Day').format('YYYY-MM-DD HH:mm:ssZ') 
</code></pre>

<p>When I test it in my local it's giving a proper response which I am expecting i.e. <code>-0800</code> time offset.</p>

<p>When we build it in deploying it's throwing error expected +0000 instead of -0800.</p>

<p>Can anyone help me out how to test this function?</p>
",https://stackoverflow.com/questions/49456215/unit-testing-with-time-zone-offset,"['angular', 'unit-testing', 'momentjs', 'karma-jasmine', 'angular-moment']",1705,TRUE,0,1
Unit testing UIImage from a URL,"<p>I'm trying to test a function that creates an image from a url. My unit test looks like this: </p>

<pre><code>func testImageFromURL() {

    //when testing callbacks use a testExpectation
    let testExpectation = expectation(description: ""Format function timed out"")

    //1.Given
    let dictPhotoData = [""isfriend"":false, ""farm"": 1, ""id"":""40946679254"", ""server"":""875"", ""secret"":""c6e491e979"", ""owner"":""138560875@N08"", ""title"":""Is it spring yet? Eastern garter snake (Thamnophis sirtalis)"", ""ispublic"":true, ""isfamily"":false] as [String : Any]

    //2.When
    let thisPhotoObj = FF_PhotoObject(dictPhotoData)
    if let thisPhotoURL = thisPhotoObj?.photoUrl as? URL {

        myAPIManager.getImageFromData(thisPhotoURL, completion: { (_ thisImage:UIImage) in

            //3. Then
            //--&gt;Not sure what to test for here.
            testExpectation.fulfill()

        })
    }

    waitForExpectations(timeout: 7) { error in
        if let error = error {
            XCTFail(""waitForExpectationsWithTimeout errored: \(error)"")
        }
    }
}
</code></pre>

<p>I'm just not sure what to test for the UIImage. </p>
",https://stackoverflow.com/questions/50007922/unit-testing-uiimage-from-a-url,"['swift', 'unit-testing', 'uiimage']",175,FALSE,0,0
Unit Testing win form validation method,"<p>Im trying to create some unit tests for CoordinateValidation, but it requires some controls being passed into it. I've tried doing MVC (still new to it) and I dont think I've done a good job, as if I had I wouldn't have to pass in controls?</p>

<p>Is the problem that I have not done MVC correctly or that Im just missing something? </p>

<p>Heres my method im trying to test and the actual unit test:    </p>

<pre><code>private static bool ValidRange(TextBox tb)
        {
            float x = float.Parse(tb.Text.Split(',')[0]);
            float y = float.Parse(tb.Text.Split(',')[1]);

            if ((x &lt; 10 || x &gt; 1000) || (y &lt; 10 || y &gt; 730))
            {
                return false;
            }
            return true;
        }

public static bool CoordinateValidation(Panel pointsPanel, ErrorProvider errorProvider)
        {
            bool status = true;
            Regex regex = new Regex(@""^((\d+\.?\d*),{1}(\d+\.?\d*))$"");

            foreach (TextBox tb in pointsPanel.Controls)
            {
                Match match = regex.Match(tb.Text);

                if (!match.Success)
                {
                    errorProvider.SetError(tb, ""Invalid coordinates!"");
                    status = false;
                }

                else if (!ValidRange(tb))
                {
                    errorProvider.SetError(tb, ""Invalid range!"");
                    status = false;
                }

                else
                {
                    errorProvider.SetError(tb, """");
                }
            }
            return status;
        }

namespace BezierLibrary.UnitTests
{
    [TestClass]
    public class BezierHelperTests
    {
        [TestMethod]
        public void CoordinateValidation_InvalidCoordinate_ReturnFalse()
        {
            //Arrange
            var panel = new Panel();
            var textbox = new TextBox();
            var errorProvider = new ErrorProvider();
            panel.Controls.Add(textbox);
            textbox.Text = ""5"";

            //Act
            var result = BezierHelper.CoordinateValidation(panel, errorProvider);

            //Assert
            Assert.IsFalse(result);

        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/52440563/unit-testing-win-form-validation-method,"['c#', 'unit-testing']",137,TRUE,0,1
Unit testing ICommand.CanExecute when using CommandManager,"<p>(Part of) my ICommand implementation is:</p>

<pre><code>    public void RaiseCanExecuteChanged()
    {
        CommandManager.InvalidateRequerySuggested();
    }

    public event EventHandler CanExecuteChanged
    {
        add
        {
            CommandManager.RequerySuggested -= value;
            CommandManager.RequerySuggested += value;
        }
        remove =&gt; CommandManager.RequerySuggested -= value;
    }
</code></pre>

<p>This works fine in the UI when calling RaiseCanExecuteChanged(), but in a unit test I want to know if the UI has been notified that it should call the CanExecute method. Subscribing to the CanExecuteChanged event doesn't work because this event is not triggered as the CommandManager is used instead.
Does anyone know how to test if CommandManager.InvalidateRequerySuggested has been triggered?</p>

<p>I am also considering not using the CommandManager and changing my implementation to:</p>

<pre><code>    public void RaiseCanExecuteChanged()
    {
        CanExecuteChanged?.Invoke(this, EventArgs.Empty);
    }

    public event EventHandler CanExecuteChanged;
</code></pre>

<p>the advantage seems to be that this only triggers calling the CanExecute for a specific command, rather than for all commands registered with the CommandManager. Can someone confirm that my understanding about the CommandManager is correct? Does anyone know disadvantages for this approach with a ""normal"" CanExecuteChanged event?</p>
",https://stackoverflow.com/questions/53538271/unit-testing-icommand-canexecute-when-using-commandmanager,"['wpf', 'unit-testing', 'icommand', 'canexecute']",294,FALSE,0,1
Unit testing CRUD functions in Django,"<p>I am trying to create a basic unit test for my code. Here is what I'm running...</p>

<pre><code>from django.test import TestCase
from django.contrib.auth.models import User
from feed.models import Post

class PostTests(TestCase):

 def setUp(self):
    user = User.objects.first()
    Post.objects.create(title='test', content='more testing', author=user)

 def test_content(self):
    post = Post.objects.get(id=1)
    expected_object_name = f'{post.content}'
    self.assertEquals(expected_object_name, 'more testing')
</code></pre>

<p>The error I'm getting is ""django.db.utils.IntegrityError: (1048, ""Column 'author_id' cannot be null"")"" I believe the error is finding the user but when I run it in the shell it updates with no problems.</p>
",https://stackoverflow.com/questions/53839058/unit-testing-crud-functions-in-django,"['django', 'unit-testing', 'testing', 'automated-tests']",1323,TRUE,0,1
Unit Testing doFilter for Correlation Id,"<p>I am working on an application build using dropwizard.</p>

<p>I made a filter to intercept and log the correlation ID of the calling service. </p>

<p>If the incoming request doesn't have a header ""Correlation-Id"" in its header, we would attach one to the response.</p>

<p>The following is the filter:</p>

<pre><code>public class CorrelationIdServletFilter implements Filter {

private static final Logger LOGGER =
  LoggerFactory.getLogger(CorrelationIdServletFilter.class);

 private static final String CORRELATION_ID_HEADER_NAME = ""Correlation-ID"";

 private static final String CORRELATION_ID_MDC_KEY = "" "";

 private static final InheritableThreadLocal&lt;String&gt; correlationId =
  new InheritableThreadLocal&lt;&gt;();

  public static String getCorrelationId() {
return correlationId.get();
 }

 @Override
 public void init(FilterConfig filterConfig) throws ServletException {}

 @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
  throws IOException, ServletException {

try {
  HttpServletRequest req = (HttpServletRequest) request;

  HttpServletResponse res = (HttpServletResponse) response;

  String correlationIdHeaderValue = req.getHeader(CORRELATION_ID_HEADER_NAME);

  LOGGER.debug
      (
      ""HTTP Header(""
          + CORRELATION_ID_HEADER_NAME
          + "") = [""
          + correlationIdHeaderValue
          + ""] will generate a new correlationId if incoming is NULL"");

  String correlationIdRaw;

  if (!StringUtils.isEmpty(correlationIdHeaderValue)) {
    correlationIdRaw = correlationIdHeaderValue;
  } else {
    correlationIdRaw = UUID.randomUUID().toString();
  }

  LOGGER.debug(""Request: ("" + req.getRequestURI() + "") is marked as :"" + correlationIdRaw);

  correlationId.set(correlationIdRaw);

  MDC.put(CORRELATION_ID_MDC_KEY, getCorrelationId());

  res.addHeader(CORRELATION_ID_HEADER_NAME, correlationIdRaw);

  LOGGER.debug(
      ""Response holds correlationId : (""
          + res.getHeader(""Correlation-ID"")
          + "") in its header "");

  chain.doFilter(req, res);

} finally {
  correlationId.remove();
  MDC.remove(CORRELATION_ID_MDC_KEY);
}
}

  @Override
  public void destroy() {}
}
</code></pre>

<p>I need to write unit tests for covering two cases:</p>

<ol>
<li><p>When a request is sent without correlation Id. Check a id is generated on server side.</p></li>
<li><p>When a response is sent with correlation Id. Check it is sent back with a response.</p></li>
</ol>

<p>Can anyone point me how this can be done?</p>

<p>I tried using mock but I am not the response has nothing in header.</p>

<pre><code>@Test
  public void testResponse_for_RequestWithoutCcid() throws IOException, ServletException {

HttpServletRequest httpServletRequest = mock(HttpServletRequest.class);
HttpServletResponse httpServletResponse = mock(HttpServletResponse.class);
FilterChain filterChain = mock(FilterChain.class);
CorrelationIdServletFilter CorrelationIdServletFilter = mock(
    CorrelationIdServletFilter.class);
CorrelationIdServletFilter.init(mock(FilterConfig.class));

CorrelationIdServletFilter.doFilter(httpServletRequest, httpServletResponse,
    filterChain);


System.out.println(httpServletResponse.getHeaderNames());

CorrelationIdServletFilter.destroy();

verify(CorrelationIdServletFilter, times(1))
    .doFilter(httpServletRequest, httpServletResponse, filterChain);

}
</code></pre>

<p>Is there any way I can do this? Any help would be really appreciated. Is there a way to this this without mock?</p>
",https://stackoverflow.com/questions/52684664/unit-testing-dofilter-for-correlation-id,"['java', 'servlets', 'correlation', 'servlet-filters', 'dropwizard']",1085,TRUE,0,1
Unit Testing Symfony4 Forms with Collections,"<p>Getting started with unit testing forms, I'm trying to test a form which holds a Collection of Form Types. My test fails asserting that the FeatureOption object is handled after submitting my form.</p>

<p>How do I fully test this form with all the data that I provide?</p>

<blockquote>
  <p>$ ./vendor/bin/simple-phpunit tests/Unit/Form/    PHPUnit 6.5.7</p>
  
  <p>Runtime:       PHP 7.2.4-1+ubuntu16.04.1+deb.sury.org+1 with Xdebug
  2.7.0alpha2-dev   Configuration: /var/www/phpunit.xml.dist</p>
  
  <p>Testing tests/Unit/Form/    F<br>
  1 / 1 (100%)</p>
  
  <p>Time: 599 ms, Memory: 6.00MB</p>
  
  <p>There was 1 failure:</p>
  
  <p>1) App\Tests\Unit\Form\FeatureFormTest::submitValidData
    Failed asserting that two objects are equal.<br>
    --- Expected<br>
    +++ Actual
    @@ @@
    -            0 => App\Entity\FeatureOption Object (...)</p>
  
  <p>/var/www/tests/Unit/Form/FeatureFormTest.php:55</p>
  
  <p>FAILURES!   Tests: 1, Assertions: 2, Failures: 1.</p>
</blockquote>

<p>src\Entity\Feature.php:</p>

<pre><code>namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;

/**
 * Feature Entity
 * 
 * @ORM\Entity()
 * @ORM\Table(name = ""feature"")
 */
class Feature extends AbstractEntity
{
    /**
     * Constructor
     */
    public function __construct()
    {
        parent::__construct();

        $this-&gt;options = new ArrayCollection();
    }
    /**
     * ID
     * 
     * @var integer
     * 
     * @ORM\Id
     * @ORM\Column(name = ""feature_id"", type = ""integer"")
     * @ORM\GeneratedValue(strategy = ""AUTO"")
     */
    protected $id;

    /**
     * Name
     * 
     * @var string
     * 
     * @ORM\Column(name = ""feature_name"", type = ""string"", length = 128)
     */
    protected $name;

    /**
     * Options
     *
     * @var ArrayCollection
     * 
     * @ORM\OneToMany(targetEntity = ""FeatureOption"", mappedBy = ""feature"", cascade = { ""persist"", ""remove"" }, fetch = ""EAGER"")
     */
    protected $options;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this-&gt;id;
    }

    /**
     * Set name
     *
     * @param string $name
     *
     * @return Feature
     */
    public function setName($name)
    {
        $this-&gt;name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this-&gt;name;
    }

    /**
     * Add option
     *
     * @param \App\Entity\FeatureOption $option
     *
     * @return Feature
     */
    public function addOption(FeatureOption $option)
    {
        $option-&gt;setFeature($this);

        $this-&gt;options[] = $option;

        return $this;
    }

    /**
     * Remove option
     *
     * @param \App\Entity\FeatureOption $option
     */
    public function removeOption(FeatureOption $option)
    {
        $this-&gt;options-&gt;removeElement($option);
    }

    /**
     * Get options
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getOptions()
    {
        return $this-&gt;options;
    }
}
</code></pre>

<p>src\Entity\FeatureOption.php</p>

<pre><code>namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;

/**
 * Feature Entity
 * 
 * @ORM\Entity()
 * @ORM\Table(name = ""feature_option"")
 */
class FeatureOption extends AbstractEntity
{
    /**
     * Constructor
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * ID
     * 
     * @var integer
     * 
     * @ORM\Id
     * @ORM\Column(name = ""feature_option_id"", type = ""integer"")
     * @ORM\GeneratedValue(strategy = ""AUTO"")
     */
    protected $id;

    /**
     * Value
     *
     * @var string
     * 
     * @ORM\Column(name = ""feature_option_value"", type = ""string"", length = 256)
     */
    protected $value;

    /**
     * Feature
     *
     * @var Feature
     * 
     * @ORM\ManyToOne(targetEntity = ""Feature"", inversedBy = ""options"")
     * @ORM\JoinColumn(name = ""feature_id"", referencedColumnName = ""feature_id"")
     */
    protected $feature;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this-&gt;id;
    }

    /**
     * Set value
     *
     * @param string $value
     *
     * @return FeatureOption
     */
    public function setValue($value)
    {
        $this-&gt;value = $value;

        return $this;
    }

    /**
     * Get value
     *
     * @return string
     */
    public function getValue()
    {
        return $this-&gt;value;
    }

    /**
     * Set feature
     *
     * @param \App\Entity\Feature $feature
     *
     * @return FeatureOption
     */
    public function setFeature(Feature $feature = null)
    {
        $this-&gt;feature = $feature;

        return $this;
    }

    /**
     * Get feature
     *
     * @return \App\Entity\Feature
     */
    public function getFeature()
    {
        return $this-&gt;feature;
    }
}
</code></pre>

<p>src\Form\FeatureForm.php</p>

<pre><code>namespace App\Form;

use App\Form\Type\FeatureOptionType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;

class FeatureForm extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $translationDomain = ""admin.feature"";

        $builder-&gt;add(""name"", TextType::class, [
            ""label""              =&gt; ""feature.name"",
            ""required""           =&gt; true,
            ""translation_domain"" =&gt; $translationDomain,
        ]);

        $builder-&gt;add(""options"", CollectionType::class, [
            ""label""              =&gt; ""feature.options"",
            ""entry_type""         =&gt; FeatureOptionType::class,
            ""by_reference""       =&gt; false,
            ""allow_add""          =&gt; true,
            ""allow_delete""       =&gt; true,
            'prototype'          =&gt; true,
            ""translation_domain"" =&gt; $translationDomain,
        ]);
    }
}
</code></pre>

<p>src\Form\Type\FeatureOptionType.php</p>

<pre><code>namespace App\Form\Type;

use App\Entity\FeatureOption;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class FeatureOptionType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $translationDomain = ""admin.feature"";

        $builder-&gt;add(""value"", TextType::class, [
            ""label""              =&gt; ""feature.option.value"",
            ""required""           =&gt; true,
            ""translation_domain"" =&gt; $translationDomain,
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver-&gt;setDefaults(array(
            'data_class' =&gt; FeatureOption::class,
        ));
    }
}
</code></pre>

<p>tests\Unit\Form\FeatureFormTest.php</p>

<pre><code>namespace App\Tests\Unit\Form;

use App\Entity\Feature;
use App\Entity\FeatureOption;
use App\Form\FeatureForm;
use App\Form\Type\FeatureOptionType;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Form\PreloadedExtension;
use Symfony\Component\Form\Test\TypeTestCase;

class FeatureFormTest extends TypeTestCase
{
    /**
     * @test
     */
    public function submitValidData()
    {
        $date = new \DateTime();

        $featureOption = new FeatureOption();
        $featureOption-&gt;setValue(""Indestructable"");

        $formData = [
            ""name""      =&gt; ""Durability"",
            ""options""   =&gt; new ArrayCollection(array($featureOption)),
        ];

        $featureComparedToForm = new Feature();
        $featureComparedToForm-&gt;setCreatedAt($date);
        $featureComparedToForm-&gt;setName($formData[""name""]);

        foreach ($formData[""options""] as $option) {
            $featureComparedToForm-&gt;addOption($option);
        }

        $featureHandledByForm = new Feature();
        $featureHandledByForm-&gt;setCreatedAt($date);

        $form = $this-&gt;factory-&gt;create(FeatureForm::class, $featureHandledByForm);

        $form-&gt;submit($formData);

        static::assertTrue($form-&gt;isSynchronized());
        static::assertEquals($featureComparedToForm, $featureHandledByForm);

        $view = $form-&gt;createView();

        foreach (array_keys($formData) as $key) {
            static::assertArrayHasKey($key, $view-&gt;children);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function getExtensions()
    {
        $featureOptionType = new FeatureOptionType();

        return [
            new PreloadedExtension([$featureOptionType], []),
        ];
    }
}
</code></pre>
",https://stackoverflow.com/questions/49769461/unit-testing-symfony4-forms-with-collections,"['unit-testing', 'symfony', 'collections', 'symfony4']",1026,FALSE,0,1
Unit testing WebFlux Routers with Spek,"<p>I have been using Spring's <a href=""https://docs.spring.io/spring/docs/current/spring-framework-reference/web-reactive.html"" rel=""nofollow noreferrer"">WebFlux</a> framework with Kotlin for about a month now, and have been loving it. As I got ready to make the dive into writing production code with WebFlux and Kotlin I found myself struggling to unit test my routers in a simple, lightweight way. </p>

<p><a href=""https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html"" rel=""nofollow noreferrer"">Spring Test</a> is an excellent framework, however it is heavier weight than what I was wanting, and I was looking for a test framework that was more expressive than traditional JUnit. Something in the vein of JavaScript's Mocha. Kotlin's <a href=""https://github.com/spekframework/spek"" rel=""nofollow noreferrer"">Spek</a> fit the bill perfectly. </p>

<p>What follows below is an example of how I was able to unit test a simple router using Spek.</p>
",https://stackoverflow.com/questions/50954719/unit-testing-webflux-routers-with-spek,"['kotlin', 'spring-webflux', 'spek']",608,TRUE,0,1
Angular - Unit testing focusing on button,"<p>I am attempting to unit test whether my button has been focused on, but I cannot seem to get the spy to work correctly?</p>

<p>I saw [this post][1], but it hasn't helped fully.</p>

<p>Am I missing something obvious?</p>

<p><strong>component.ts</strong></p>

<pre><code>ngOnInit() {
    // autofocus on the cancel button to guard against mistakes
    document.getElementById('cancel').focus();
  }
</code></pre>
",https://stackoverflow.com/questions/52093496/angular-unit-testing-focusing-on-button,"['javascript', 'angular', 'testing', 'karma-runner']",3723,TRUE,0,2
Unit testing Doctrine: can&#39;t mock repository method,"<p>I'm trying to mock a Doctrine repository and the entityManager, but PHPUnit keeps telling me that: </p>

<blockquote>
  <p>1) CommonUserTest::testGetUserById Trying to configure method ""findBy""
  which cannot be configured because it does not exist, has not been
  specified, is final, or is static</p>
</blockquote>

<p>Here's the snippet:</p>

<pre class=""lang-php prettyprint-override""><code>&lt;?php
use \Domain\User as User;
use PHPUnit\Framework\TestCase;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\EntityManager;

class CommonUserTest extends PHPUnit_Framework_TestCase
{    
    public function testGetUserById()
    {
        // mock the repository so it returns the mock of the user (just a random string)
        $repositoryMock = $this
            -&gt;getMockBuilder(EntityRepository::class)
            -&gt;disableOriginalConstructor()
            -&gt;getMock();

        $repositoryMock-&gt;expects($this-&gt;any())
            -&gt;method('findBy')
            -&gt;willReturn('asdasd');

        // mock the EntityManager to return the mock of the repository
        $entityManager = $this
            -&gt;getMockBuilder(EntityManager::class)
            -&gt;disableOriginalConstructor()
            -&gt;getMock();

        $entityManager-&gt;expects($this-&gt;any())
            -&gt;method('getRepository')
            -&gt;willReturn($repositoryMock);

        // test the user method
        $userRequest = new User($entityManager);
        $this-&gt;assertEquals('asdasd', $userRequest-&gt;getUserById(1));
    }
}
</code></pre>

<p>Any help? I tried a few variations of this code but can't get passed this specific error.</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/48277568/unit-testing-doctrine-cant-mock-repository-method,"['php', 'testing', 'doctrine-orm', 'doctrine', 'phpunit']",5999,TRUE,7,1
Scala/Spark unit testing logging log4j,"<p>I would like to make some unit tests for a function inside my class, simplified example:</p>

<pre><code>Class Datachecks {
   df = spark.read.parquet(..)
   val logger = Logger(getClass)
   def logColumns(df: DatFrame): Unit = {
      df.columns.foreach(logger.info(_))
}
</code></pre>

<p>Which i then want to test with something like </p>

<pre><code>Class DataChecksSuite extends FunSuite with initSpark {
   val initDataChecks = new DataChecks()
   val df = spark.read.parquet()
   test(""Example test"") {
      assert(initDataChecks.logColumns(df) === ""myOutput"")
   }
}
</code></pre>

<p>Now I know this won't run, because my column does not output a String, nor would I like to rewrite/refacter my entire DataChecks Class to make this possible.</p>

<p>Now I was wondering: is it possible to catch the console output of log4j and turn this into a String? Or would it be possible to mock my logger class to output a String? (I have tried with Mockito but without success..)</p>

<p>My (required) dependencies are log4j &amp; FunSuite (if it's really necessary I could still switch, but as the project is rather large I would like to keep all things consistent.</p>

<p>I can provide a more detailed example when needed, as this is only a very simplified spoof example.</p>
",https://stackoverflow.com/questions/53104666/scala-spark-unit-testing-logging-log4j,"['scala', 'unit-testing', 'apache-spark', 'log4j']",806,TRUE,0,2
How to mock/spy an imported function in Angular unit testing,"<p>Let's say i have an angular 6 component with a method <code>test</code> which returns some value:</p>

<pre><code>import { doSomething } from './helper';

@Component({
    ...
})
export class AppComponent {
    test() {
        const data = doSomething(1);
        return data.something ? 1: 2;
    }
}
</code></pre>

<p><code>doSomething</code> is just a simple helper function:</p>

<pre><code>export function doSomething() {
    return { something: 1 };
}
</code></pre>

<p>Is it possible to mock or spy this function in a unit test (so i can control its returnValue)? Or do i have to change my approach in the component?</p>

<p>Please note: <code>doSomething()</code> can be a lodash function, a const, a class etc. I just tried to keep the example as simple as possible.</p>

<hr>

<p>Things i've tried:</p>

<ul>
<li><p><code>SpyOn</code> doesn't work because function is not attached to anything</p></li>
<li><p>Importing an mock-function into the <code>imports</code> array of <code>TestBed.configureTestingModule</code> gives <code>Unexpected value 'doSomething' imported by the module 'DynamicTestModule'. Please add a @NgModule annotation.</code></p></li>
<li><p>Creating a service for it works but it feels silly to have to create services for each imported function</p></li>
</ul>
",https://stackoverflow.com/questions/50605327/how-to-mock-spy-an-imported-function-in-angular-unit-testing,"['javascript', 'angular', 'unit-testing', 'mocking', 'spy']",29238,TRUE,34,2
Unit testing parallel function using moq,"<p>I've got basic interface, and a class that takes it implementation in constructor, then fetches some data sequentialy or parallely depending on input.</p>

<pre><code>    public interface ISomeService
    {
        List&lt;int&gt; FetchSomeData(int a);
    }      

    public class SomeClass
    {
        private ISomeService sr { get; }

        public SomeClass(ISomeService sr) =&gt; this.sr = sr;

        public int DoMagic(bool paralell)
        {
            int sum = 0;
            if (paralell)
            {
                Parallel.For(0, 10, (x) =&gt;
                {
                    sum += sr.FetchSomeData(x).Sum(z =&gt; z);
                });
            }
            else
            {
                for (int i = 0; i &lt; 10; i++)
                {
                    sum += sr.FetchSomeData(i).Sum(z =&gt; z);
                }
            }
            return sum;
        }
    }
</code></pre>

<p>then i've got test:</p>

<pre><code>    [Test]
    public void DoTest()
    {

        var service = new Mock&lt;ISomeService&gt;(MockBehavior.Strict);
        service.Setup(x =&gt; x.FetchSomeData(It.IsAny&lt;int&gt;()))
            .Returns(() =&gt; new List&lt;int&gt; { 3 });

        var someClass = new SomeClass(service.Object);

        var notParallel = someClass.DoMagic(false);

        var parallel = someClass.DoMagic(true);

        Assert.AreEqual(30, notParallel);

        Assert.AreEqual(30, parallel);
    }
</code></pre>

<p>And the problem:</p>

<p>NotParallel results are always the same ( 30 ), but in parallel case there results vary ( sometimes 15, other time 21 etc ).
What may be the problem? How to solve this ? </p>
",https://stackoverflow.com/questions/53379512/unit-testing-parallel-function-using-moq,"['c#', '.net', 'unit-testing', 'mocking', 'moq']",361,TRUE,0,1
Add Javascript class to unit testing,"<p>I added a Pusher javascript library to my <code>index.html</code> in the scripts. </p>

<p><code>&lt;script src=""https://cdnjs.cloudflare.com/ajax/libs/pusher/4.2.2/pusher.min.js""&gt;&lt;/script&gt;
</code></p>

<p>Now to use it in my component. I need to add this below the imports <code>declare var Pusher: any</code> and on my <code>ngOnInit</code> method I need to instantiate the class like this</p>

<p><code>ngOnInit(){ this.pusher = new Pusher(key, {obj} )}</code> </p>

<p>The problem lies when I'm trying to unit test the component, this is the <code>beforeEach</code> function</p>

<pre><code>TestBed.configureTestingModule({
        declarations: [
            HeaderComponent,
            SidebarComponent,
            SearchComponent,
            DashboardComponent,
            FooterComponent,
            LoginComponent,
            LogOutComponent,
            NoContentComponent,
            UnAuthorizedComponent
        ],
        imports: [
            HttpClientTestingModule,
            RouterModule,
            FormsModule,
            ReactiveFormsModule,
            CalendarModule,
            RouterModule.forRoot(ROUTES, {
                useHash: Boolean(history.pushState) === false,
                preloadingStrategy: PreloadAllModules
              }),
        ],
        providers: [
            DoctorServices,
            AnnouncementService,
            LoginService,
            {provide: APP_BASE_HREF, useValue : '/' }
        ]
    }).compileComponents();

fixture = TestBed.createComponent(DashboardComponent);
        component = fixture.componentInstance;
</code></pre>

<p>and below is the my actual test</p>

<pre><code> it(`should be readily initialized`, () =&gt; {
    expect(fixture).toBeDefined();
    expect(component).toBeDefined();
});
</code></pre>

<p>everytime I run <code>npm run test:ci</code> I get a <code>Pusher is not defined error.</code> How do I deal with that?</p>
",https://stackoverflow.com/questions/51353504/add-javascript-class-to-unit-testing,"['angular', 'unit-testing']",312,FALSE,0,1
"unit testing in javascript, first approach","<p>I'm new to unit testing procedures and I'm trying to figure out how to do it properly.</p>

<p>In my project, the javascript i wrote basically interacts with dom object via events, so i need to write a test that basically manipulate the DOM.</p>

<p>now, i have this project structure:</p>

<pre><code>init
|--node_modules
|--spec
|--src
    |--assets
    |--dist
    |--js
    |--scss
    |--index.html
|--gulpfile.js
|--package.lock.json
|--package.json
</code></pre>

<p>i set up the jasmine spec folder in the root, but maybe, because i need to working whit the dom, have I to set up the spec folder inside the scr path? and then insert the test.spec.js at the end of my index.html?</p>

<p>for now i create this test file, for testing the Contacts.js:</p>

<pre><code>const contactsHandler              = require('../src/js/Contacts.js');

const contacts = new contactsHandler.Contacts();


describe(""A suite"", function() {
  it(""contains spec with an expectation"", function() {
    expect(typeof(contactsHandler)).toBe('object');
  });
});
</code></pre>

<p>Now if i remove the second line: <code>const contacts = new contactsHandler.Contacts();</code> test is passed, instead i will get an error.
this is my Contacts class:</p>

<pre><code>class Contacts{
  constructor(){
    this.contactsButton = document.getElementById('contacts-button');
    this.contactsContainer = document.getElementById('contacts-container');
    this.phoneTrigger = document.getElementById('phone-trigger');
    this.mailTrigger = document.getElementById('mail-trigger');
    this.phone = document.getElementById('phone');
    this.mail = document.getElementById('mail');
    this.close = Array.from(document.querySelectorAll('.close-contact'));
    this.mailText = '.contacts--mail--text';
    this.phoneText = '.contacts--phone--text';
    this.init()
  }
  init(){
    this._initContacts();
    this._initPhone();
    this._initMail();
    this._close();
    this._textAnimation();

  }

  _initContacts(){
    let self = this;
    this.contactsButton.addEventListener('click',function(){
      TweenLite.from(self.contactsContainer,2,
        {
          autoAlpha:0,
        })
    })
  }

  _initPhone(){
    let self = this;
    this.phoneTrigger.addEventListener('click',function(){
      TweenLite.to(self.phone,1,{autoAlpha:1,top:'0',left:'0',zIndex:20})
      $(self.phoneText).textillate('start')
    })
  }
  _close(){
    this.close.forEach(function(el){
      el.addEventListener('click',function(){
        if(this.parentElement.classList.contains('contacts--mail')){
          TweenLite.to(this.parentElement,1,{autoAlpha:0,top:'-50%'})
        }else{
          TweenLite.to(this.parentElement,1,{autoAlpha:0,top:'50%'})
        }
      })
    })
  }

  _initMail(){
    let self = this;
    this.mailTrigger.addEventListener('click',function(){
      TweenLite.to(self.mail,.7,{autoAlpha:1,top:'0',left:'0',zIndex:20})
      $(self.mailText).textillate('start')
    })
  }

  _textAnimation(){
    $(this.phoneText).textillate({
        in: { effect: 'bounceIn' },
        autoStart:false
    })
    $(this.mailText).textillate({
        in: { effect: 'bounceIn' },
        autoStart:false
    })
  }
}




module.exports = {
  Contacts
}
</code></pre>

<p>I think that i get an error because when i call the constructor it tries to reach some DOM elements, that of course couldn't find. So: have I to put the test.spec.js file into the src folder and then calling it in the html file? is it a good procedure?
thanks</p>
",https://stackoverflow.com/questions/48769431/unit-testing-in-javascript-first-approach,"['javascript', 'unit-testing', 'jasmine']",47,FALSE,0,0
unit testing vuetify component v-checkbox,"<p>I wanted to test v-checkbox component.
Calling once trigger click will change the checkbox status checked.</p>

<pre><code>  const flag = wrapper.find('.input-group--selection-controls__ripple')[0]
  flag.trigger('click')
</code></pre>

<p>Calling twice trigger click will not change checkbox status unchecked.
How to implement?</p>

<pre><code>  const flag = wrapper.find('.input-group--selection-controls__ripple')[0]
  flag.trigger('click')
  flag.trigger('click')
</code></pre>
",https://stackoverflow.com/questions/50109182/unit-testing-vuetify-component-v-checkbox,"['unit-testing', 'vue.js', 'vuetify.js']",2671,TRUE,0,3
unit testing static method C# program,"<p>I want to unit test a static method of my main program:</p>

<pre><code>public class Program
{
    public static int Main(string[] args)
    { ... }
    private static bool TheAnswer(int ans)
    { 
        if (ans == 42)
            return true;
        return false;
     }
}
</code></pre>

<p>To test it, in my unit test project, I have:</p>

<pre><code>var t = new PrivateType(typeof(Program));
bool result = Convert.ToBoolean(t.InvokeStatic(""TheAnswer"", 42));
Assert.AreEqual(result, true);
</code></pre>

<p>but this is failing on the call to InvokeStatic with </p>

<blockquote>
  <p>An exception of type 'System.MissingMethodException' occurred in
  mscorlib.dll but was not handled in user code</p>
  
  <p>Additional information: Attempted to access a missing member.</p>
</blockquote>

<p>How can I make this work (can I?)</p>

<p>Stack trace:
'vstest.executionengine.x86.exe' (CLR v4.0.30319: UnitTestAdapter: Running test): Loaded 'C:\PROGRAM FILES (X86)\MICROSOFT VISUAL STUDIO 14.0\COMMON7\IDE\COMMONEXTENSIONS\MICROSOFT\TESTWINDOW\Extensions\Microsoft.VisualStudio.TestPlatform.Extensions.VSTestIntegration.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'vstest.executionengine.x86.exe' (CLR v4.0.30319: UnitTestAdapter: Running test): Loaded 'C:\Windows\assembly\GAC_MSIL\Microsoft.VisualStudio.QualityTools.UnitTestFramework\10.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'vstest.executionengine.x86.exe' (CLR v4.0.30319: UnitTestAdapter: Running test): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_32\System.Data\v4.0_4.0.0.0__b77a5c561934e089\System.Data.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'vstest.executionengine.x86.exe' (CLR v4.0.30319: UnitTestAdapter: Running test): Loaded 'C:\Projects\myprogram\Test_the_test\bin\Debug\Test_the_test.dll'. Symbols loaded.
'vstest.executionengine.x86.exe' (CLR v4.0.30319: UnitTestAdapter: Running test): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_32\System.Transactions\v4.0_4.0.0.0__b77a5c561934e089\System.Transactions.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'vstest.executionengine.x86.exe' (CLR v4.0.30319: UnitTestAdapter: Running test): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_32\System.EnterpriseServices\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.EnterpriseServices.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'vstest.executionengine.x86.exe' (CLR v4.0.30319: UnitTestAdapter: Running test): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_32\System.EnterpriseServices\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.EnterpriseServices.Wrapper.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'vstest.executionengine.x86.exe' (CLR v4.0.30319: UnitTestAdapter: Running test): Loaded 'C:\Projects\myprogram\Test_the_test\bin\Debug\myprogram.exe'. Symbols loaded.
Exception thrown: 'System.MissingMethodException' in mscorlib.dll
'vstest.executionengine.x86.exe' (CLR v4.0.30319: UnitTestAdapter: Running test): Loaded 'C:\Windows\assembly\GAC_MSIL\Microsoft.VisualStudio.Debugger.Runtime\14.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.Debugger.Runtime.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.</p>
",https://stackoverflow.com/questions/49282950/unit-testing-static-method-c-program,"['c#', 'unit-testing', 'private']",249,FALSE,-3,1
Integration and Unit testing Nifi process groups,"<p>I have a few Nifi process groups which I want to run integration tests on before promoting to production. The issue is that I can't seem to find any documentation on how to do so.</p>

<p>Data Provenance seems like a promising tool to accomplish what I want, however, over the course of the flowfile's lifecycle, data is published to/from kafka or the file system. As a result, the flowfile UUID changes so I cannot query for it using the <code>nifi-api</code>. </p>

<p>Additionally, I know that Nifi offers a <code>TestRunner</code> library to run tests, however, this seems to only be for processors/processor groups generated via code and not the UI. </p>

<p>Does anyone know of a tool, framework, or pattern for integration and unit testing nifi process groups. Ideally this would be a solution where you can programatically compare input/output of the processor/processor group without modifying the existing workflow. </p>
",https://stackoverflow.com/questions/51831506/integration-and-unit-testing-nifi-process-groups,"['testing', 'apache-nifi']",2833,TRUE,6,2
How to skip @PostConstruct when unit testing,"<p>I have a scheduled task that aggregates data every night. The task runs whenever I start up the application and I would like to stop it from running when I run jUnit tests on the applicaton. </p>

<pre><code>@Scheduled(cron = ""0 0 0 1 * ?"")
public void SalesDataAggregation() {
    //aggregation
}
</code></pre>

<p><strong>Edit</strong></p>

<p>The method above is also being called here</p>

<pre><code>@PostConstruct
public void init(){
    SalesDataAggregation();
}
</code></pre>
",https://stackoverflow.com/questions/51618123/how-to-skip-postconstruct-when-unit-testing,"['java', 'spring', 'junit4', 'postconstruct']",10325,TRUE,6,3
Unit Testing - How to structure Firebase mocks?,"<p>I'm unit testing my application using the Mockito framework.</p>
<h2>TL;DR</h2>
<p>Should I create a mock for every possible result of a class and set their behaviours in the @Before or should I create just one mock for every class and then define their behaviours in each test that uses them?</p>
<h2>Context</h2>
<p>Right now I'm testing the <code>DataRepository</code>, that has <code>getPosts(String postId)</code>. <code>DataRepository</code> receives a <code>FirebaseFirestore</code> instance via DI.</p>
<p><code>getPosts</code> returns a <code>Maybe&lt;List&lt;Post&gt;&gt;</code> with the following code:</p>
<pre><code>fun getPosts(companyId: String): Maybe&lt;List&lt;Post&gt;&gt; {
    return Maybe.create { emitter -&gt;
        firestore.collection(&quot;companies/$companyId/posts&quot;).get()
                .addOnCompleteListener {
                    if (it.isSuccessful) {
                        if (it.result.isEmpty) {
                            emitter.onComplete()
                        } else {
                            emitter.onSuccess(it.result.toObjects(Post::class.java))
                        }
                    } else {
                        emitter.onError(it.exception ?: UnknownError())
                    }
                }
    }
}
</code></pre>
<h2>Problem</h2>
<p>To test this function and the various cases (success/empty/failed) I have to mock FirebaseFirestore, then the CollectionReference, then the Task, then the OnCompleteListener (with an argument captor) and so on. Basically everything.</p>
<h2>Question</h2>
<p>When I mock the task should I</p>
<p>a. Create a <code>successfulTaskMock</code> that I set in the @Before to always be successful and one for the failure? Same thing with a valid/empty <code>validQuerySnapshot</code>/<code>emptyQuerySnapshot</code>?</p>
<p>b. Create only a <code>taskMock</code> and then change its return value directly inside the test? (Make taskMock.isSuccessful return true in the success test and false in the failure test)</p>
<p>I've looked at some GitHub repos: some do a., some do b.</p>
<p>Problem with a. is I would end up with tons of mocks for the same class, but with very clean and readable tests.</p>
<p>Problem with b. is I should setup each mock at the start of every test, thus having a lot of boilerplate code.</p>
<h2>Conclusion</h2>
<p>I've read that I could use deep mocking to only create the end result of a call (the QuerySnapshot, as opposed to Firestore + Collection + Task etc.) but that seems to be very frowned upon and I can see why.</p>
<p>Maybe there is even a third way that I don't know of. Any suggestion is greatly appreciated.</p>
<p>Thank you very much.</p>
",https://stackoverflow.com/questions/49812182/unit-testing-how-to-structure-firebase-mocks,"['unit-testing', 'firebase', 'junit', 'mockito', 'google-cloud-firestore']",903,FALSE,6,0
Unit testing a ThreeJS application with Jest,"<p>I am having difficulties testing a JavaScript file with Jest which encapsulate a lot of interactions with ThreeJS. I first tried not to mock ThreeJS, which did not work :</p>

<pre><code>  ● TestSuite › Should instantiate a renderer attached to a specific element of the DOM

    TypeError: Cannot read property 'getExtension' of null

      36 |      */
      37 |     constructor(containerId: string) {
    &gt; 38 |         this.renderer = new WebGLRenderer({ antialias: true });
      39 |         this.attachRenderer(containerId);
      40 |         this.createCamera();
      41 |         this.createScene();
</code></pre>

<p>That's normal, because we are <a href=""https://github.com/facebook/jest/issues/3905"" rel=""noreferrer"">testing in a browser-like environment which has no webgl context</a> . So what I did to solve this problem was mocking three.js.</p>

<p>I then mocked my external module with <code>jest.mock(""three"");</code></p>

<pre><code>  ● TestSuite › Should instantiate a renderer attached to a specific element of the DOM

    TypeError: this.renderer.setSize is not a function

      64 |             throw new Error(""Cannot find DOM element object matching the specified ID: "" + containerId);
      65 |         }
    &gt; 66 |         this.renderer.setSize(window.innerWidth, window.innerHeight);
      67 |         element.appendChild(this.renderer.domElement);
      68 |     }
      69 |
</code></pre>

<p>And that's expected behavior, since every mock from jest returns <code>undefined</code>, <code>new WebGLRenderer();</code> returns <code>undefined</code> and I cannot do anything with it.</p>

<p>My current work-around is to define everything I uses in ThreeJS in my test file :</p>

<pre><code>jest.mock(""three"", () =&gt; ({
    Scene: class Scene {
        public add(): void {
            return;
        }
    },
    WebGLRenderer: class WebGlRenderer {
        public render(): void {
            return;
        }
        public setSize(): void {
            return;
        }
    }
    // And a lot more...
}));
</code></pre>

<p>But I am well aware that this is not the optimal solution. Before that I was doing the same thing, but in a file in mocks/three.js ( <a href=""https://jestjs.io/docs/en/manual-mocks"" rel=""noreferrer"">https://jestjs.io/docs/en/manual-mocks</a> ), which was also working fine but that does not satisfy my need. </p>

<p>Is there a way to test this file properly, without having to write tons of manual mocks of threejs ? </p>
",https://stackoverflow.com/questions/51330753/unit-testing-a-threejs-application-with-jest,"['javascript', 'unit-testing', 'three.js', 'jestjs']",3826,TRUE,6,1
Unit Testing when using EF Core 2.0,"<p>For the project I am doing in my internship we have to use a repository pattern. Since the project was already using EF Core and I read that there was already repository and unit of work in the underlying implementation. I figured I would just use the EF Core methods directly without implementing repository classes as I wanted to prevent clutter.</p>

<p>Well now I am in a bit of a problem, I can't seem to find much useful information on unit testing when I implement this way. The requirement is a hard requirement, and I required 100% coverage of CRUD functions within my controllers due to the standards of this firm. I found some of the Microsoft Documentation <a href=""https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-with-dotnet-test?view=aspnetcore-2.1"" rel=""noreferrer"">here</a>, <a href=""https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/testing?view=aspnetcore-2.1"" rel=""noreferrer"">here</a>, and the integration testing <a href=""https://learn.microsoft.com/en-us/ef/core/miscellaneous/testing/sqlite"" rel=""noreferrer"">using SQLite</a> but I still can't seem to figure out unit testing. I did some googling as well and I can't find resources aside from integration testing.</p>

<p>Is there some way I can unit test using EF Core directly, or am I gonna have to make repositories in order to properly unit test this program?</p>
",https://stackoverflow.com/questions/51749932/unit-testing-when-using-ef-core-2-0,"['c#', 'unit-testing', 'asp.net-core', 'entity-framework-core', 'asp.net-core-mvc-2.0']",7507,TRUE,6,2
"JS, unit testing : expect on a callback","<p>I am using Leaflet, and I am creating a marker on it. Once the mouse is out of this marker, I would like to remove the pop-up I am displaying on <code>mouseenter</code> : </p>

<pre><code>marker.on('mouseout', e =&gt; this.leafletMap.closePopup());
</code></pre>

<p>In my testing, I would like to know if the callback provided is what I expect. </p>

<p>I already test if the event happens on mouseout with </p>

<pre><code>expect((mockedMarker.on as jasmine.Spy).calls.argsFor(0)[0]).toEqual('mouseover');
</code></pre>

<p>Any ideas on how to do that ? </p>

<p>I tried something like this </p>

<pre><code>expect((mockedMarker.on as jasmine.Spy).calls.argsFor(0)[1]).toEqual(JSON.stringify(component.leafletMap.closePopup));
</code></pre>

<p>But I don't know what I'm doing (I'm new to unit testing), and I can't find a solution online because I don't really know how to call this kind of test.</p>

<p>I should state that I work in <strong>Typescript</strong>.</p>
",https://stackoverflow.com/questions/48863599/js-unit-testing-expect-on-a-callback,"['angular', 'unit-testing', 'typescript', 'jasmine', 'leaflet']",661,TRUE,5,2
Unit Testing With Dependency Injection On controller,"<p>I'am tired to need to make fill the fields then login logout to do a simple test.</p>

<p>I search for xUnit and NUnit and i found several tuturials but. I want to test my modification to AccountController (asp.net core 2 mvc) i use a repository to put logic this repo.</p>

<p>The problem is how to make the arrange of test with all those dependency injection.</p>

<p><strong>Controller example.</strong></p>

<pre><code>namespace Inside.Controllers
{
[Authorize]
[Route(""[controller]/[action]"")]
public class AccountController : Controller
{
    private readonly UserManager&lt;ApplicationUser&gt; _userManager;
    private readonly SignInManager&lt;ApplicationUser&gt; _signInManager;
    private readonly IEmailSender _emailSender;
    private readonly ILogger _logger;
    private readonly IUsersRepository _users;

    public AccountController(
            UserManager&lt;ApplicationUser&gt; userManager,
            SignInManager&lt;ApplicationUser&gt; signInManager,
            IEmailSender emailSender,
            ILogger&lt;AccountController&gt; logger,
            IUsersRepository users
        )
    {
        _userManager = userManager;
        _signInManager = signInManager;
        _emailSender = emailSender;
        _logger = logger;
        _users = users;
    }

    [HttpGet]
    [AllowAnonymous]
    public IActionResult RegisterFirstUser(string returnUrl = null)
    {
        if (!_users.HasUsersInDB())
        {
            return RedirectToAction(nameof(SetupWebApp));
        }
        if (!_users.HasOnlySystemUser())
        {
            return RedirectToAction(nameof(Login)); ;
        }
        ViewData[""ReturnUrl""] = returnUrl;
        return View();
    }
}
</code></pre>

<p>Now i don't know how to make a test to test this controller since have a lot of dependency injection. Specialy this two UserManager userManager, SignInManager signInManager</p>

<p>Sorry for the newbie question. :p</p>
",https://stackoverflow.com/questions/48918222/unit-testing-with-dependency-injection-on-controller,"['asp.net-mvc', 'unit-testing', 'dependency-injection']",7803,TRUE,5,1
Unit Testing ES6 Class with External Dependency,"<p>I'm trying to set a unit testing boilerplate for my company. Our front end projects are built with ES6 classes and have a dependency to our core product. The front end code gets wrapped through a build process in a whole other block of code that is basically a closure and captures the dependency. So we don't have to manually import it in order to use it. </p>

<p>Let's say the dependency is called <code>productScope</code> and it's an object that has some DOM models, internal APIs and parameters among many other things necessary for each project. At the moment, Mocha throws <code>ReferenceError: productScope is not defined.</code> How can I mock this object? Or should I just use the actual object?</p>

<p>Example:</p>

<pre><code>class someClass {
    constructor() {
        const id = productScope.items[0].id
        const item = productScope.domModel.querySelector('.some-div')

        item.classList.add(`added-${id}`)
    }
}
</code></pre>

<p>This get wrapped in core code like below:</p>

<pre><code>(function(productScope) {
    // front end code goes here
}(productScope)
</code></pre>

<p>Testing file:</p>

<pre><code>import someClass from '../../js/someClass'

describe('someClass', function() {
    const someClass = new someClass()
    it('should be a class', function() {
        console.log(someClass)
    });
});
</code></pre>
",https://stackoverflow.com/questions/53398084/unit-testing-es6-class-with-external-dependency,"['javascript', 'unit-testing', 'mocking', 'mocha.js']",1542,TRUE,5,3
Jest unit-testing if super() is called,"<p>I have a custom error class that extends the built-in Error class in Javascript. The problem I came up with is that ""super()"" method is not checked if it is called or not through my Jest unit testing.</p>

<pre><code>export class AppError extends Error {
  public name: string;
  public message: string;
  public status?: number;
  public data?: any;
  constructor(message: string, status?: number, data?: any) {
    super(); &lt;-- this guy!!
    this.name = 'AppError';
    this.status = status || 500;
    this.message = message;
    this.data = data;
  }
}
</code></pre>

<p>Is there any way to test it? Thanks.</p>
",https://stackoverflow.com/questions/51216056/jest-unit-testing-if-super-is-called,"['unit-testing', 'ecmascript-6', 'jestjs', 'super']",10309,TRUE,5,1
Unit testing for dropdown selection angular 5,"<p>I am trying to test drop down selection, I am able to get nativeElement and options, but I am facing error with dispatch event </p>

<p>some how event is not captured.</p>

<blockquote>
  <p><strong>HTML</strong></p>
</blockquote>

<pre><code>&lt;select [(ngModel)]='selectedTemplate' class=""gridDropdowns"" name=""compareDropdown"" (ngModelChange)=""onTemplateChange($event)""&gt;
    &lt;option *ngFor='let option of templateDropdown' [attr.id] = ""option.text"" [ngValue]=""option.value"" &gt;{{option.text}}&lt;/option&gt;
&lt;/select&gt;
</code></pre>

<blockquote>
  <p><strong>component</strong></p>
</blockquote>

<pre><code>   public templateDropdown: Array&lt;{ text: string, value: string }&gt; = 
    [
        { text: 'Layer Summary - Final Share', value: 'final' },
        { text: 'Layer Summary - Authorized Share', value: 'authorize' },
        { text: 'Layer Summary - Quote Share', value: 'quote' },
        { text: 'PML Summary (100%)', value: 'pmlSummary' },
        { text: 'Metric Comp Summary', value: 'metricComp' }
    ];

onTemplateChange(event: any) {
    console.log(event);
}
</code></pre>

<blockquote>
  <p><strong>Component.spec.ts</strong></p>
</blockquote>

<pre><code>it('Load corresponding data on Template dropdown change', async(() =&gt; {
    fixture = TestBed.createComponent(CompareComponent);
    component = fixture.componentInstance;
    spyOn(component, 'onTemplateChange');
    component.selectedTemplate= component.templateDropdown[1].value;
    fixture.detectChanges();
    const templateDropdown = fixture.debugElement.query(By.css('select'));
    fixture.whenStable().then(() =&gt;{
        templateDropdown.nativeElement.value = 'Layer Summary - Authorized Share'
        templateDropdown.nativeElement.dispatchEvent(new Event('change'));
        fixture.detectChanges();
        expect(component.onTemplateChange).toHaveBeenCalledWith('authorize')
    })

}));
</code></pre>

<blockquote>
  <p><strong>Error that I am getting</strong></p>
</blockquote>

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

<p>I am taking this <a href=""https://stackoverflow.com/a/47391665"">Reference</a></p>
",https://stackoverflow.com/questions/52602067/unit-testing-for-dropdown-selection-angular-5,"['angular', 'jasmine', 'angular5']",1963,FALSE,4,0
Unit testing: How to test generic repository,"<p>I am trying to test my generic repository which looks like this </p>

<pre><code>public class GenericRepository&lt;T&gt; : IGenericRepository&lt;T&gt; where T : BaseEntity
{
    protected readonly DbContext DbContext;
    public GenericRepository(DbContext dbContext)
    {
        DbContext = dbContext;
    }

    public string Create(T item)
    {
        if (string.IsNullOrEmpty(item.Id))
        {
            item.Id = Guid.NewGuid().ToString(""N"");
        }
        item.CreatedAt = DateTime.UtcNow;
        DbContext.Entry(item).State = EntityState.Added;
        DbContext.SaveChanges();
        return item.Id;
        /*using (var dbContext = new MyDbContext())
        {
            item.Id = Guid.NewGuid().ToString(""N"");
            item.CreatedAt = DateTime.UtcNow;
            dbContext.Entry(item).State = EntityState.Added;
            dbContext.SaveChanges();
            return item.Id;
        }*/
    }
    public T GetById(string id)
    {
        return GetFirst(x =&gt; x.Id == id);
    }      

    public T GetFirst(Expression&lt;Func&lt;T, bool&gt;&gt; @where, params Expression&lt;Func&lt;T, object&gt;&gt;[] nav)
    {
        return GetFiltered(nav).FirstOrDefault(where);
        /*using (var context = new MyDbContext())
        {
            return GetFiltered(context, nav).FirstOrDefault(where);
        }*/
    }


    private IQueryable&lt;T&gt; GetFiltered(params Expression&lt;Func&lt;T, object&gt;&gt;[] nav)
    {
        IQueryable&lt;T&gt; q = DbContext.Set&lt;T&gt;();
        return nav.Aggregate(q, (current, n) =&gt; current.Include(n));
    }

}
</code></pre>

<p>Based on the <a href=""https://learn.microsoft.com/en-us/ef/ef6/fundamentals/testing/mocking"" rel=""nofollow noreferrer"">microft's testing fundamental site</a> I tried to write few test cases.</p>

<p>Below is unit test code </p>

<pre><code>[TestClass]
public class GenericRepositoryTest
{
    private Foo _foo;
    private IQueryable&lt;Foo&gt; _fooList;
    private Mock&lt;DbSet&lt;Foo&gt;&gt; _mockSet;  

    [TestInitialize]
    public void Setup()
    {
        _foo = new Foo
        {            
            EmailId = ""foo@bar.com"",
            FirstName = ""foo"",
            LastName = ""bar"",               
            ProfileId = 27,
            IsDeleted = false,
        };  

        _fooList = new List&lt;Foo&gt;
        {
            new Foo{EmailId = ""one@bar.com"", FirstName = ""one"", LastName = ""bar"", ProfileId = 28, IsDeleted = false}, 
            new Foo{EmailId = ""two@bar.com"", FirstName = ""two"", LastName = ""bar"", ProfileId = 29, IsDeleted = false},    
        }.AsQueryable();
        _mockSet = new Mock&lt;DbSet&lt;Foo&gt;&gt;();
        _mockSet.As&lt;IQueryable&lt;Foo&gt;&gt;().Setup(m =&gt; m.Provider).Returns(_fooList.Provider);
        _mockSet.As&lt;IQueryable&lt;Foo&gt;&gt;().Setup(m =&gt; m.Expression).Returns(_fooList.Expression);
        _mockSet.As&lt;IQueryable&lt;Foo&gt;&gt;().Setup(m =&gt; m.ElementType).Returns(_fooList.ElementType);
        _mockSet.As&lt;IQueryable&lt;Foo&gt;&gt;().Setup(m=&gt;m.GetEnumerator()).Returns(_fooList.GetEnumerator());
    }

    [TestMethod]
    public void Create_GivenEntity_ReturnsGuidId()
    {
        //Arrange
        var guidId = Guid.NewGuid().ToString(""N"");
        var dbContext = new Mock&lt;MyDbContext&gt;().Object;

        IGenericRepository&lt;Foo&gt; genericRepository = new Mock&lt;GenericRepository&lt;Foo&gt;&gt;(dbContext).Object;

        //Act
        _waitingQueue.Id = guidId;
        var actualId = genericRepository.Create(_foo);

        //Assert
        Assert.IsNotNull(actualId);
        Assert.AreEqual(actualId, guidId);

    }

    [TestMethod]
    public void GetById_GivenEntityId_ReturnsEntity()
    {
        //Arrange
        var id = Guid.NewGuid().ToString(""N"");
        _foo.Id = id;

        var mockContext = new Mock&lt;MyDbContext&gt;();
        mockContext.Setup(c =&gt; c.Foo).Returns(_mockSet.Object);
        IGenericRepository&lt;Foo&gt; genericRepository = new Mock&lt;GenericRepository&lt;Foo&gt;&gt;(mockContext.Object).Object;

        //Act
        var fooId = genericRepository.Create(_foo);
        var fooObject = genericRepository.GetById(id);

        //Assert
        fooObject.PropertiesShouldEqual(_foo);
    }
}
</code></pre>

<p>Here is DbContext</p>

<pre><code>public class MyDbContext : DbContext
{
    public MyDbContext() : base(""fakeConnectionString"")
    {
    }

    public virtual DbSet&lt;Foo&gt; WaitingQueues { get; set; }
}
</code></pre>

<p>I am new to unit testing and I don't know if the approach I am taking is the right one.</p>

<p>Currently, the first test <code>Create_GivenEntity_ReturnsGuidId</code> passes but the second test <code>GetById_GivenEntityId_ReturnsEntity</code> fails. </p>

<p>The error I get is on <code>GetFirst(Expression&lt;Func&lt;T, bool&gt;&gt; @where, params Expression&lt;Func&lt;T, object&gt;&gt;[] nav)</code> method of GenericRepository</p>

<p>This is because the <code>GetFiltered(params Expression&lt;Func&lt;T, object&gt;&gt;[] nav)</code> when called by <code>GetFirst</code> returns null.</p>

<p>Is it becuase at this point <code>T</code> is unknown for <code>GenericRepository&lt;T&gt;</code>?</p>

<p>Error I get is </p>

<pre><code>System.ArgumentNullException
HResult=0x80004003
Message=Value cannot be null.
Parameter name: source
</code></pre>

<p>When I debug I can see that <code>GetById(string id)</code> method has proper id passed into it</p>

<p>Can anyone suggest me what should I do? and what approach should I take?</p>
",https://stackoverflow.com/questions/51985752/unit-testing-how-to-test-generic-repository,"['c#', 'unit-testing', 'generics', 'moq', 'mstest']",2123,TRUE,4,1
Unit testing with Dagger and AWS Lambda,"<p>I am trying to set up <a href=""https://github.com/google/dagger"" rel=""nofollow noreferrer"">Dagger</a> in my <a href=""https://github.com/serverless/serverless"" rel=""nofollow noreferrer"">Serverless</a> project which has a number of Java AWS Lambda implementations. The Lambda code is relatively straightforward and mostly deals with reading the request and writing the response, with service classes doing most of the heavy lifting.</p>

<p>I would like to unit test my Lambda code but I'm having some trouble setting up Dagger for this. The specific problem I'm having is that I rely on an environment variable to specify the AWS region to construct a DynamoDB client. When running unit tests this environment variable is null, causing the builder to throw an exception. This is the full exception (which hopefully makes some sense with the code below):</p>

<pre><code>org.mockito.exceptions.base.MockitoException: 
Cannot instantiate @InjectMocks field named 'handler' of type 'class com.mealplanner.function.ListMealsHandler'.
You haven't provided the instance at field declaration so I tried to construct the instance.
However the constructor or the initialization block threw an exception : Could not find region information for 'null' in SDK metadata.

    at org.mockito.junit.jupiter.MockitoExtension.beforeEach(MockitoExtension.java:165)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeBeforeEachCallbacks$0(TestMethodTestDescriptor.java:129)
    at org.junit.jupiter.engine.execution.ThrowableCollector.execute(ThrowableCollector.java:40)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeBeforeMethodsOrCallbacksUntilExceptionOccurs(TestMethodTestDescriptor.java:155)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeBeforeEachCallbacks(TestMethodTestDescriptor.java:128)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:107)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:58)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:113)
    at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$2(HierarchicalTestExecutor.java:121)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)
    at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175)
    at java.util.Iterator.forEachRemaining(Iterator.java:116)
    at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
    at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:121)
    at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$2(HierarchicalTestExecutor.java:121)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)
    at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175)
    at java.util.Iterator.forEachRemaining(Iterator.java:116)
    at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
    at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:121)
    at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:55)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:43)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:170)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:154)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:90)
    at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.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:538)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
    Suppressed: java.lang.NullPointerException
        at org.mockito.junit.jupiter.MockitoExtension.afterEach(MockitoExtension.java:211)
        at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeAfterEachCallbacks$11(TestMethodTestDescriptor.java:217)
        at org.junit.jupiter.engine.execution.ThrowableCollector.execute(ThrowableCollector.java:40)
        at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeAllAfterMethodsOrCallbacks$13(TestMethodTestDescriptor.java:229)
        at java.util.ArrayList.forEach(ArrayList.java:1249)
        at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeAllAfterMethodsOrCallbacks(TestMethodTestDescriptor.java:227)
        at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeAfterEachCallbacks(TestMethodTestDescriptor.java:216)
        at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:119)
        ... 46 more
Caused by: com.amazonaws.SdkClientException: Could not find region information for 'null' in SDK metadata.
    at com.amazonaws.client.builder.AwsClientBuilder.getRegionObject(AwsClientBuilder.java:251)
    at com.amazonaws.client.builder.AwsClientBuilder.withRegion(AwsClientBuilder.java:238)
    at com.mealplanner.config.AppModule.providesAmazonDynamoDB(AppModule.java:17)
    at com.mealplanner.config.AppModule_ProvidesAmazonDynamoDBFactory.proxyProvidesAmazonDynamoDB(AppModule_ProvidesAmazonDynamoDBFactory.java:34)
    at com.mealplanner.config.AppModule_ProvidesAmazonDynamoDBFactory.provideInstance(AppModule_ProvidesAmazonDynamoDBFactory.java:25)
    at com.mealplanner.config.AppModule_ProvidesAmazonDynamoDBFactory.get(AppModule_ProvidesAmazonDynamoDBFactory.java:21)
    at com.mealplanner.config.AppModule_ProvidesAmazonDynamoDBFactory.get(AppModule_ProvidesAmazonDynamoDBFactory.java:1)
    at com.mealplanner.dal.DynamoDbAdapter_Factory.provideInstance(DynamoDbAdapter_Factory.java:25)
    at com.mealplanner.dal.DynamoDbAdapter_Factory.get(DynamoDbAdapter_Factory.java:21)
    at com.mealplanner.dal.DynamoDbAdapter_Factory.get(DynamoDbAdapter_Factory.java:1)
    at dagger.internal.DoubleCheck.get(DoubleCheck.java:47)
    at com.mealplanner.dal.MealRepository_Factory.provideInstance(MealRepository_Factory.java:24)
    at com.mealplanner.dal.MealRepository_Factory.get(MealRepository_Factory.java:20)
    at com.mealplanner.dal.MealRepository_Factory.get(MealRepository_Factory.java:1)
    at dagger.internal.DoubleCheck.get(DoubleCheck.java:47)
    at com.mealplanner.config.DaggerAppComponent.getMealRepository(DaggerAppComponent.java:52)
    at com.mealplanner.function.ListMealsHandler.&lt;init&gt;(ListMealsHandler.java:31)
    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.mockito.internal.util.reflection.FieldInitializer$NoArgConstructorInstantiator.instantiate(FieldInitializer.java:195)
    at org.mockito.internal.util.reflection.FieldInitializer.acquireFieldInstance(FieldInitializer.java:137)
    at org.mockito.internal.util.reflection.FieldInitializer.initialize(FieldInitializer.java:91)
    at org.mockito.internal.configuration.injection.PropertyAndSetterInjection.initializeInjectMocksField(PropertyAndSetterInjection.java:94)
    at org.mockito.internal.configuration.injection.PropertyAndSetterInjection.processInjection(PropertyAndSetterInjection.java:79)
    at org.mockito.internal.configuration.injection.MockInjectionStrategy.process(MockInjectionStrategy.java:68)
    at org.mockito.internal.configuration.injection.MockInjectionStrategy.relayProcessToNextStrategy(MockInjectionStrategy.java:89)
    at org.mockito.internal.configuration.injection.MockInjectionStrategy.process(MockInjectionStrategy.java:71)
    at org.mockito.internal.configuration.injection.MockInjectionStrategy.relayProcessToNextStrategy(MockInjectionStrategy.java:89)
    at org.mockito.internal.configuration.injection.MockInjectionStrategy.process(MockInjectionStrategy.java:71)
    at org.mockito.internal.configuration.injection.MockInjection$OngoingMockInjection.apply(MockInjection.java:92)
    at org.mockito.internal.configuration.DefaultInjectionEngine.injectMocksOnFields(DefaultInjectionEngine.java:25)
    at org.mockito.internal.configuration.InjectingAnnotationEngine.injectMocks(InjectingAnnotationEngine.java:87)
    at org.mockito.internal.configuration.InjectingAnnotationEngine.processInjectMocks(InjectingAnnotationEngine.java:48)
    at org.mockito.internal.configuration.InjectingAnnotationEngine.process(InjectingAnnotationEngine.java:42)
    at org.mockito.MockitoAnnotations.initMocks(MockitoAnnotations.java:69)
    at org.mockito.internal.framework.DefaultMockitoSession.&lt;init&gt;(DefaultMockitoSession.java:36)
    at org.mockito.internal.session.DefaultMockitoSessionBuilder.startMocking(DefaultMockitoSessionBuilder.java:78)
    ... 52 more
</code></pre>

<p>I have looked at <a href=""https://github.com/fabioCollini/DaggerMock"" rel=""nofollow noreferrer"">DaggerMock</a> to provide mocks for my objects but I've failed to get it working.</p>

<p>Here are the pieces of code which set up Dagger and other relevant classes:</p>

<p><strong>AppModule.java</strong></p>

<pre><code>import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;

import dagger.Module;
import dagger.Provides;

@Module
public class AppModule {

    private static final String AWS_REGION = System.getenv(""region"");

    @Provides
    public AmazonDynamoDB providesAmazonDynamoDB() {
        return AmazonDynamoDBClientBuilder.standard()
                .withRegion(AWS_REGION)
                .build();
    }
}
</code></pre>

<p><strong>AppComponent.java</strong></p>

<pre><code>import javax.inject.Singleton;

import com.mealplanner.dal.DynamoDbAdapter;
import com.mealplanner.dal.MealRepository;

import dagger.Component;

@Singleton
@Component(modules = { AppModule.class })
public interface AppComponent {

    DynamoDbAdapter getDynamoDbAdapter();

    MealRepository getMealRepository();
}
</code></pre>

<p><strong>DynamoDbAdapter.java</strong></p>

<pre><code>import javax.inject.Inject;
import javax.inject.Singleton;

import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig;

@Singleton
public class DynamoDbAdapter {

    private final AmazonDynamoDB client;

    @Inject
    public DynamoDbAdapter(final AmazonDynamoDB client) {
        this.client = client;
    }

    public DynamoDBMapper createDbMapper(final DynamoDBMapperConfig mapperConfig) {
        return new DynamoDBMapper(client, mapperConfig);
    }
}
</code></pre>

<p><strong>MealRepository.java</strong></p>

<pre><code>import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.inject.Singleton;

import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBQueryExpression;
import com.amazonaws.services.dynamodbv2.datamodeling.PaginatedQueryList;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.mealplanner.domain.Meal;

@Singleton
public class MealRepository {

    private static final String MEALS_TABLE_NAME = System.getenv(""tableName"");

    private final DynamoDBMapper mapper;

    @Inject
    public MealRepository(final DynamoDbAdapter dynamoDbAdapter) {
        final DynamoDBMapperConfig mapperConfig = DynamoDBMapperConfig.builder()
                .withTableNameOverride(new DynamoDBMapperConfig.TableNameOverride(MEALS_TABLE_NAME))
                .build();

        this.mapper = dynamoDbAdapter.createDbMapper(mapperConfig);
    }
}
</code></pre>

<p><strong>ListMealsHandler.java</strong></p>

<p>See notes below code snippet for some explanations.</p>

<pre><code>import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.mealplanner.config.AppComponent;
import com.mealplanner.config.DaggerAppComponent;
import com.mealplanner.dal.MealRepository;
import com.mealplanner.domain.Meal;
import com.mealplanner.function.util.ApiGatewayRequest;
import com.serverless.ApiGatewayResponse;

public class ListMealsHandler implements RequestHandler&lt;ApiGatewayRequest, ApiGatewayResponse&gt; {

    @Inject
    MealRepository repository;

    public ListMealsHandler() {
        final AppComponent component = DaggerAppComponent.builder().build();
        this.repository = component.getMealRepository();
    }

    @Override
    public ApiGatewayResponse handleRequest(final ApiGatewayRequest request, final Context context) {
        //read from request, call repository, and build response
    }
}
</code></pre>

<ul>
<li>I have included an injectable field for <code>repository</code> purely for testing, ideally I would have the dependency injected into the constructor</li>
<li>I create the <code>AppComponent</code> in the constructor as this seems to be the ""entry"" point for Lambdas. I understand that you would normally set this up in the <code>onCreate</code> method or the <code>main</code> method but I don't think I have access to these for Lambdas.</li>
</ul>

<hr>

<p>And this is how I'd like to test the Lambda function, i.e. mock the dependencies and perform assertions based on that.</p>

<p><strong>ListMealsHandlerTest.java</strong></p>

<pre><code>import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;

import java.util.Arrays;
import java.util.List;

import org.junit.Rule;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import com.amazonaws.services.lambda.runtime.Context;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mealplanner.config.AppComponent;
import com.mealplanner.config.AppModule;
import com.mealplanner.dal.MealRepository;
import com.mealplanner.domain.Meal;
import com.mealplanner.function.ListMealsHandler;
import com.mealplanner.function.util.ApiGatewayRequest;
import com.mealplanner.function.util.Identity;
import com.mealplanner.function.util.RequestContext;
import com.serverless.ApiGatewayResponse;

@ExtendWith(MockitoExtension.class)
public class ListMealsHandlerTest {

    private static final String USER_ID = ""user1"";

    @Mock
    private MealRepository mealRepository;

    @Mock
    private ApiGatewayRequest request;

    @Mock
    private RequestContext requestContext;

    @Mock
    private Identity identity;

    @Mock
    private Context context;

    @InjectMocks
    private ListMealsHandler handler;

    @Test
    public void all_users_meals_are_returned() throws Exception {
        final List&lt;Meal&gt; meals = Arrays.asList();
        when(mealRepository.getAllMealsForUser(USER_ID)).thenReturn(meals);

        when(request.getRequestContext()).thenReturn(requestContext);
        when(requestContext.getIdentity()).thenReturn(identity);
        when(identity.getCognitoIdentityId()).thenReturn(USER_ID);

        final ApiGatewayResponse response = handler.handleRequest(request, context);
        final ObjectMapper objectMapper = new ObjectMapper();
        final List&lt;Meal&gt; actualMeals = objectMapper.readValue(response.getBody(), new TypeReference&lt;List&lt;Meal&gt;&gt;() {
        });

        assertThat(actualMeals).containsExactlyInAnyOrderElementsOf(meals);
    }
}
</code></pre>

<hr>

<h1>Questions</h1>

<ol>
<li>Have I set up Dagger correctly?</li>
<li>If not, how should I have set it up?</li>
<li>Is it correct to build the <code>AppComponent</code> in the constructor of my Lambda function?</li>
<li>Is it possible to unit test like I want to?</li>
<li>If so, how should I set up Dagger for this testing?</li>
</ol>
",https://stackoverflow.com/questions/51856500/unit-testing-with-dagger-and-aws-lambda,"['java', 'testing', 'aws-lambda', 'dagger-2', 'daggermock']",2649,FALSE,4,1
J Unit Testing for Multiplication in Java,"

<pre><code>public static int multiply(int a, int b) {
    int product = a * b;
    return product;
}
</code></pre>

<p>I am trying to write a J Unit test for this code. Right now it passes, but I am not fully sure if I have it correct. I am also not fully sure if the code is correct to begin with. The code is suppose to take two rational numbers as parameters and return a Rational number as their product.</p>



<pre><code>@Test   
public void multiplyTest() {        
    int product = Rational.multiply(5/7,2/3);       
    assertEquals(product, Rational.multiply(5/7, 2/3));     
}
</code></pre>

<p><strong>Update</strong></p>

<p>Here is my Rational class with my actual code:</p>

<pre><code>public class Rational {

    private int num;
    private int den;

    public Rational(int numIn, int denIn) {
        num = numIn;
        den = denIn;

    }

    public int getNum() {
        return num;
    }

    public int getDen() {
        return den;
    }

    public String toString() {
        return num + ""/"" + den;
    }

    public String reciprocal() {
        return den + ""/"" + num;
    }

    public static int multiply(int a, int b) {
        int product = a * b;
        return product;
    }

    public int divide(int a) {
        int number = num / den;
        return number / a;
    }

    public int add(int number) {
        int sum = ((this.num * den) + (num * this.den)) / (this.den * den);
        return sum;
    }

}
</code></pre>
",https://stackoverflow.com/questions/49502607/j-unit-testing-for-multiplication-in-java,"['java', 'junit']",2456,TRUE,4,2
Mock User.Identity in ASP.NET Core for Unit Testing,"<p>I am struggling to implement unit testing for action methods that incorporate <code>User.Identity.Name</code> functionality. The methods that I've come across fail because the properties that they suggest writing to throw 'read-only' errors (e.g. writing to <code>HttpContext</code> or the controller <code>User</code>)</p>

<p>I have an action method:</p>

<pre><code>[Authorize]
        public async Task&lt;ViewResult&gt; EditProject(int projectId)
        {
            Project project = repository.Projects.FirstOrDefault(p =&gt; p.ProjectID == projectId);
            if (project != null)
            {
            //HOW DO I MOCK USER.IDENTITY.NAME FOR THIS PORTION?
                var user = await userManager.FindByNameAsync(User.Identity.Name); 
                bool owned = await checkIfUserOwnsItem(project.UserID, user);
                if (owned)
                {
                    return View(project);
                }
                else
                {
                    TempData[""message""] = $""User is not authorized to view this item"";
                }
             }
            return View(""Index"");
        }
</code></pre>

<p>If I want to unit test this action method, how can I mock up the <code>User.Identity</code> object?</p>

<pre><code>[Fact]
        public async Task Can_Edit_Project()
        {
            //Arrange
            var user = new AppUser() { UserName = ""JohnDoe"", Id = ""1"" };
            Mock&lt;IRepository&gt; mockRepo = new Mock&lt;IRepository&gt;();
            mockRepo.Setup(m =&gt; m.Projects).Returns(new Project[]
            {
                new Project {ProjectID = 1, Name = ""P1"", UserID = ""1""},
                new Project {ProjectID = 2, Name = ""P2"", UserID = ""1""},
                new Project {ProjectID = 3, Name = ""P3"", UserID = ""1""},
            });
            Mock&lt;ITempDataDictionary&gt; tempData = new Mock&lt;ITempDataDictionary&gt;();
            Mock&lt;UserManager&lt;AppUser&gt;&gt; userMgr = GetMockUserManager();
            //Arrange
            ProjectController controller = new ProjectController(mockRepo.Object, userMgr.Object)
            {
                TempData = tempData.Object,
            };


           //HOW WOULD I MOCK THE USER.IDENTITY.NAME HERE?
           //The example below causes two errors:
           // 1) 'Invalid setup on a non-virtual (overridable in VB) member
           //mock =&gt; mock.HttpContext
           //and 2) HttpContext does not contain a definition for IsAuthenticated
           var mock = new Mock&lt;ControllerContext&gt;();
           mock.SetupGet(p =&gt; p.HttpContext.User.Identity.Name).Returns(user.UserName);
          mock.SetupGet(p =&gt; p.HttpContext.Request.IsAuthenticated).Returns(true);

            //Act
            var viewResult = await controller.EditProject(2);
            Project result = viewResult.ViewData.Model as Project;

            //Assert
            Assert.Equal(2, result.ProjectID);
        }
</code></pre>

<p>EDIT:
Making some progress by adding the code below. </p>

<pre><code>var claims = new List&lt;Claim&gt;()
            {
                new Claim(ClaimTypes.Name, ""John Doe""),
                new Claim(ClaimTypes.NameIdentifier, ""1""),
                new Claim(""name"", ""John Doe""),
            };
            var identity = new ClaimsIdentity(claims, ""TestAuthType"");
            var claimsPrincipal = new ClaimsPrincipal(identity);

            var mockPrincipal = new Mock&lt;IPrincipal&gt;();
            mockPrincipal.Setup(x =&gt; x.Identity).Returns(identity);
            mockPrincipal.Setup(x =&gt; x.IsInRole(It.IsAny&lt;string&gt;())).Returns(true);

            var mockHttpContext = new Mock&lt;HttpContext&gt;();
            mockHttpContext.Setup(m =&gt; m.User).Returns(claimsPrincipal);
</code></pre>

<p>The <code>User.Identity.Name</code> is set properly now, but the line below still returns a <code>user = null</code></p>

<p><code>var user = await userManager.FindByNameAsync(User.Identity.Name);</code></p>

<p>How can I make sure my mocked <code>UserManager</code> can return a mocked logged in user?</p>
",https://stackoverflow.com/questions/49330154/mock-user-identity-in-asp-net-core-for-unit-testing,"['c#', 'unit-testing', 'asp.net-core-mvc', 'xunit']",21032,TRUE,10,3
Unit testing a formik component with jest/enzyme,"<p>I've put together a pretty basic contact form that works just fine. However I now need to start writing my unit tests and I've run into a load of problems (like I literally have only managed to get a snapshot test to pass so far).</p>

<p>So to start with I'm trying to test that the form should render my validation messages when you click the submit button if you have not filled out all the required sections.</p>

<p>I thought I could achieve this by calling the <code>handleSubmit()</code> function e.g:
<code>componentRender.find('Formik').instance().props.handleSubmit(badFormValues, { resetForm });</code></p>

<p>However when I run <code>componentRender.debug()</code> , my validation messages aren't being rendered. It's like the validationSchema function isn't being called?</p>

<p>Is there something special that needs to be done? I feel like the <code>mapPropsToValues()</code> function is working, from looking at the state object it's being populated with the values I'm passing the form. I just can't see why validation is seemingly being skipped?</p>

<p>I've been at this for 2 days now and can't find any good examples through google (probably my fault) so any help would be massively appreciated.</p>

<p>For reference here is the test file so far:</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, mount } from 'enzyme';
import { BrowserRouter as Router } from 'react-router-dom';
import PartnerRegistrationForm from 'Components/partner-registration-form/PartnerRegistrationForm';

describe('PartnerRegistrationForm component', () =&gt; {
    const formValues = {
        companyName: 'some company',
        countryCode: 'GB +44',
        telNumber: 12345678,
        selectCountry: 'United Kingdom',
        postcode: 'ABC1 234',
        addressSelect: '123 street',
        siteName: 'blah',
        siteURL: 'https://www.blah.com',
        contactName: 'Me',
        email: 'me@me.com',
    };

    const componentShallow = shallow(&lt;PartnerRegistrationForm {...formValues} /&gt;);

    describe('Component Snapshot', () =&gt; {
        it('should match stored snapshot', () =&gt; {
            expect(componentShallow).toMatchSnapshot();
        });
    });

    describe('Component functionality', () =&gt; {
        it('should not submit if required fields are empty', () =&gt; {
            const badFormValues = {
                companyName: 'some company',
                countryCode: 'GB +44',
                telNumber: 12345678,
            };
            const resetForm = jest.fn();
            const componentRender = mount(
                &lt;Router&gt;
                    &lt;PartnerRegistrationForm {...badFormValues} /&gt;
                &lt;/Router&gt;,
            );
            componentRender.find('Formik').instance().props.handleSubmit(badFormValues, { resetForm });
            // console.log(componentRender.update().find('.validation-error'));
            // console.log(componentRender.find('Formik').instance());
            // expect(componentRender.find('.validation-error').text()).toEqual('Company Name is required');
        });
    });
});</code></pre>
</div>
</div>
</p>

<p>And here is my <code>withFormik()</code> function:</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 WrappedFormWithFormik = withFormik({
    mapPropsToValues({
        companyName,
        countryCode,
        telNumber,
        selectCountry,
        postcode,
        addressSelect,
        siteName,
        siteURL,
        contactName,
        email,
    }) {
        return {
            companyName: companyName || '',
            countryCode: countryCode || '',
            telNumber: telNumber || '',
            selectCountry: selectCountry || '',
            postcode: postcode || '',
            addressSelect: addressSelect || '',
            siteName: siteName || '',
            siteURL: siteURL || '',
            contactName: contactName || '',
            email: email || '',
        };
    },
    validationSchema, // This is a standard Yup.object(), just importing it from a separate file
    handleSubmit: (values, { resetForm }) =&gt; {
        console.log('submitting');
        const {
            companyName,
            countryCode,
            telNumber,
            selectCountry,
            postcode,
            addressSelect,
            siteName,
            siteURL,
            contactName,
            email,
        } = values;

        const emailBody = `Name: ${contactName},`
        + `Email: ${email},`
        + `Company Name: ${companyName},`
        + `Country Code: ${countryCode},`
        + `Telephone Number: ${telNumber},`
        + `Country: ${selectCountry},`
        + `Postcode: ${postcode},`
        + `Address: ${addressSelect},`
        + `Website Name: ${siteName},`
        + `Website URL: ${siteURL}`;

        // TODO set up actual contact submit logic
        window.location.href = `mailto:test@test.com?subject=New partner request&amp;body=${emailBody}`;
        resetForm();
    },
})(PartnerRegistrationForm);</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/52532781/unit-testing-a-formik-component-with-jest-enzyme,"['javascript', 'reactjs', 'jestjs', 'enzyme', 'formik']",14821,TRUE,10,2
Unit testing in Python Pygame for key.get_pressed(),"<p>I am new to python coding and need some help with unit testing. I want to test my modules that move the images location in Pygame based on what the user has pressed. Here are my modules:</p>

<pre><code>def moveRight(self):
    self.x = self.x + self.speed

def moveLeft(self):
    self.x = self.x - self.speed
</code></pre>

<p>Here is where i call these modules:</p>

<pre><code>def on_execute(self):

    # While game is running
    while( self._running ):
        pygame.event.pump()

        keys = pygame.key.get_pressed() 

        if (keys[K_RIGHT]):
            self.player.moveRight()

        if (keys[K_LEFT]):
            self.player.moveLeft()

        # Use class players function moveUp to move up
        if (keys[K_UP]):
            self.player.moveUp()

        self.on_render()
</code></pre>

<p>How do i go about testing these? is unit testing different when working with Pygame?</p>
",https://stackoverflow.com/questions/52917479/unit-testing-in-python-pygame-for-key-get-pressed,"['python', 'unit-testing', 'pygame']",1592,TRUE,3,1
Unit testing .timeout() operator constantly returns TimeoutException,"<p>Spend a few hours trying to figure out why my unit test keeps returning a TimeoutException on an Rx chain that has a timeout operator. Without any luck, I dumbed down my chain to just the timeout operator, and it still fails.</p>

<pre><code>    @Test
    @DisplayName(""Custom timeout"")
    fun customTimeout() {
        val observer: TestObserver&lt;Boolean&gt; = TestObserver()
        val scheduler = TestScheduler()
        val subject: PublishSubject&lt;Boolean&gt; = PublishSubject.create()

        subject.subscribeOn(scheduler)
                .timeout(30, TimeUnit.SECONDS)
                .subscribe(observer)

        scheduler.advanceTimeBy(5, TimeUnit.SECONDS)
        subject.onNext(true)
        scheduler.advanceTimeBy(5, TimeUnit.SECONDS)
        subject.onNext(false)
        scheduler.advanceTimeBy(5, TimeUnit.SECONDS)

        observer.await().assertValueCount(2)
    }
</code></pre>

<p>Can someone please tell me why the values are not coming through?</p>
",https://stackoverflow.com/questions/48914056/unit-testing-timeout-operator-constantly-returns-timeoutexception,"['kotlin', 'rx-java', 'rx-java2']",1280,FALSE,3,0
Xamarin Forms&#39; FreshMvvm FreshPageModelResolver.ResolvePageModel for Unit Testing,"<p>While unit testing, I stumbled across the static <code>FreshPageModelResolver.ResolvePageModel</code> which is, obviously, untestable.</p>

<p>I was going to go through doing a wrapper and an interface but part of me was saying ""FreshMvvm is a modern framework, made for a modern architecture that should be fully testable""</p>

<p>Am I missing anything? Should I have not used <code>FreshPageModelResolver.ResolvePageModel</code> ?</p>

<p>Looking at the source code, there is no real need for static implementation: <a href=""https://github.com/rid00z/FreshMvvm/blob/master/src/FreshMvvm/FreshPageModelResolver.cs"" rel=""nofollow noreferrer"">https://github.com/rid00z/FreshMvvm/blob/master/src/FreshMvvm/FreshPageModelResolver.cs</a></p>
",https://stackoverflow.com/questions/48083240/xamarin-forms-freshmvvm-freshpagemodelresolver-resolvepagemodel-for-unit-testin,"['c#', 'unit-testing', 'xamarin.forms', 'freshmvvm']",391,TRUE,3,1
Angular 5: Unit testing fail on Firefox,"<p>I write test with Karma and Jasmine for Angular 5 component. Tests are running on Chrome and Firefox (karma-chrome-launcher v2.1.1 and karma-firefox-launcher v1.1.0)</p>

<p>On Chrome all tests are successfully but for Firefox there is a strange error: <code>[object ErrorEvent] thrown</code></p>

<pre><code>Firefox 58.0.0 (Mac OS X 10.12.0) Component: Login should redirect if user click Forgot password button FAILED
        [object ErrorEvent] thrown
Firefox 58.0.0 (Mac OS X 10.12.0): Executed 33 of 43 (1 FAILED) (skipped 6) (0 secs / 10.761 secs)
Chrome 64.0.3282 (Mac OS X 10.12.6): Executed 33 of 43 (skipped 6) SUCCESS (0 secs / 5.868 secs)
Firefox 58.0.0 (Mac OS X 10.12.0) Component: Login should redirect if user click Forgot password button FAILED
        [object ErrorEvent] thrown
Firefox 58.0.0 (Mac OS X 10.12.0): Executed 37 of 43 (1 FAILED) (skipped 6) (13.172 secs / 12.945 secs)
Chrome 64.0.3282 (Mac OS X 10.12.6): Executed 37 of 43 (skipped 6) SUCCESS (7.108 secs / 6.964 secs)
</code></pre>

<p>Test <em>should redirect if user click Forgot password button</em>:</p>

<pre><code>  it('should redirect if user click Forgot password button', inject([UserService], (userService: UserService) =&gt; {
    // GIVEN
    spyOn(userService, 'goToLogin');

    // WHEN
    component.goToForgotPassword();

    // THEN
    expect(userService.goToLogin).toHaveBeenCalledWith(Constants.AUTH_PAGES.FORGOT_PASSWORD);
  }));
</code></pre>

<p>If I run this test individually then everything works normally.</p>

<p>The problems started when I include one test with <code>fakeAsync</code>. If I remove this test then everything works normally.</p>

<p>Had someone similar problems or do I do something wrong?
Thanks</p>
",https://stackoverflow.com/questions/49069228/angular-5-unit-testing-fail-on-firefox,"['angular', 'unit-testing', 'firefox']",280,FALSE,3,0
Unit Testing an SSH Client in Go,"<p>I wrote an SSH client in Go and I would like to write some tests. The problem is that I've never really written proper unit tests before, and most tutorials seem to focus on writing tests for a function that adds two numbers or some other toy problem. I've read about mocking, using interfaces, and other techniques, but I'm having trouble applying them. Also, my client is going to be used concurrently to allow fast configuration of multiple devices at a time. Not sure if that would change the way I write my tests or would add additional tests. Any help is appreciated.</p>

<p>Here is my code. Basically, a <code>Device</code> has 4 main functions: <code>Connect</code>, <code>Send</code>, <code>Output</code>/<code>Err</code> and <code>Close</code> for connecting to a device, sending it a set of configuration commands, capturing the output of the session, and closing the client, respectively.</p>

<pre><code>package device

import (
    ""bufio""
    ""fmt""
    ""golang.org/x/crypto/ssh""
    ""io""
    ""net""
    ""time""
)

// A Device represents a remote network device.
type Device struct {
    Host    string         // the device's hostname or IP address
    client  *ssh.Client    // the client connection
    session *ssh.Session   // the connection to the remote shell
    stdin   io.WriteCloser // the remote shell's standard input
    stdout  io.Reader      // the remote shell's standard output
    stderr  io.Reader      // the remote shell's standard error
}

// Connect establishes an SSH connection to a device and sets up the session IO.
func (d *Device) Connect(user, password string) error {
    // Create a client connection
    client, err := ssh.Dial(""tcp"", net.JoinHostPort(d.Host, ""22""), configureClient(user, password))
    if err != nil {
        return err
    }
    d.client = client
    // Create a session
    session, err := client.NewSession()
    if err != nil {
        return err
    }
    d.session = session
    return nil
}

// configureClient sets up the client configuration for login
func configureClient(user, password string) *ssh.ClientConfig {
    var sshConfig ssh.Config
    sshConfig.SetDefaults()
    sshConfig.Ciphers = append(sshConfig.Ciphers, ""aes128-cbc"", ""aes256-cbc"", ""3des-cbc"", ""des-cbc"", ""aes192-cbc"")
    config := &amp;ssh.ClientConfig{
        Config:          sshConfig,
        User:            user,
        Auth:            []ssh.AuthMethod{ssh.Password(password)},
        HostKeyCallback: ssh.InsecureIgnoreHostKey(),
        Timeout:         time.Second * 5,
    }
    return config
}

// setupIO creates the pipes connected to the remote shell's standard input, output, and error
func (d *Device) setupIO() error {
    // Setup standard input pipe
    stdin, err := d.session.StdinPipe()
    if err != nil {
        return err
    }
    d.stdin = stdin
    // Setup standard output pipe
    stdout, err := d.session.StdoutPipe()
    if err != nil {
        return err
    }
    d.stdout = stdout
    // Setup standard error pipe
    stderr, err := d.session.StderrPipe()
    if err != nil {
        return err
    }
    d.stderr = stderr
    return nil
}

// Send sends cmd(s) to the device's standard input. A device only accepts one call
// to Send, as it closes the session and its standard input pipe.
func (d *Device) Send(cmds ...string) error {
    if d.session == nil {
        return fmt.Errorf(""device: session is closed"")
    }
    defer d.session.Close()
    // Start the shell
    if err := d.startShell(); err != nil {
        return err
    }
    // Send commands
    for _, cmd := range cmds {
        if _, err := d.stdin.Write([]byte(cmd + ""\r"")); err != nil {
            return err
        }
    }
    defer d.stdin.Close()
    // Wait for the commands to exit
    d.session.Wait()
    return nil
}

// startShell requests a pseudo terminal (VT100) and starts the remote shell.
func (d *Device) startShell() error {
    modes := ssh.TerminalModes{
        ssh.ECHO:          0, // disable echoing
        ssh.OCRNL:         0,
        ssh.TTY_OP_ISPEED: 14400,
        ssh.TTY_OP_OSPEED: 14400,
    }
    err := d.session.RequestPty(""vt100"", 0, 0, modes)
    if err != nil {
        return err
    }
    if err := d.session.Shell(); err != nil {
        return err
    }
    return nil
}

// Output returns the remote device's standard output output.
func (d *Device) Output() ([]string, error) {
    return readPipe(d.stdout)
}

// Err returns the remote device's standard error output.
func (d *Device) Err() ([]string, error) {
    return readPipe(d.stdout)
}

// reapPipe reads an io.Reader line by line
func readPipe(r io.Reader) ([]string, error) {
    var lines []string
    scanner := bufio.NewScanner(r)
    for scanner.Scan() {
        lines = append(lines, scanner.Text())
    }
    if err := scanner.Err(); err != nil {
        return nil, err
    }
    return lines, nil
}

// Close closes the client connection.
func (d *Device) Close() error {
    return d.client.Close()
}

// String returns the string representation of a `Device`.
func (d *Device) String() string {
    return fmt.Sprintf(""%s"", d.Host)
}
</code></pre>
",https://stackoverflow.com/questions/49418982/unit-testing-an-ssh-client-in-go,"['unit-testing', 'testing', 'go', 'ssh', 'network-programming']",3684,TRUE,3,1
Unit testing http service on Angular 5,"<p>I'm pretty confused about how to test a data service, there's just way too many possibilities and it's overwhelming.</p>

<p>I have this simple service: </p>

<pre><code>@Injectable()
export class DataService {

  constructor(private _http: HttpClient) { }

  getData&lt;T&gt;(path: string): Observable&lt;T&gt; {
    return this._http.get&lt;T&gt;(path);
  }

}
</code></pre>

<p>I want to test that calling <code>getData&lt;number&gt;</code> will, infact, return a data type of <code>number</code>.</p>

<p>The <a href=""https://angular.io/guide/testing"" rel=""nofollow noreferrer"">angular testing guide </a> frustratingly shows several ways (use testbed, use beforeEach, use jasmine without testBed) and I've tried all of them but not with much success.</p>

<p>How do I do this please? I have so far failed to even get as far as calling the <code>getData</code>. I want to be able to mock the Http, emit mock return values (like in <code>jasmine.spy.and.returnValue(mockData)</code>) and verify that dataService is OK</p>

<p>I've got this in my <code>data.service.spec.ts</code>:</p>

<pre><code>describe('DataService', () =&gt; {

  beforeEach(() =&gt; {

    TestBed.configureTestingModule({
      imports: [
        HttpClientModule
      ],
      providers: [
        DataService,
        HttpClient
      ]
    });

  });

  // This was auto generated, and works
  it('should be created', inject([DataService], (service: DataService) =&gt; {
    expect(service).toBeTruthy();
  }));

  // I added this, but doesn't work
  describe('When getData() is called', () =&gt; {

    it('should return an observable of type T', inject([DataService], (service: DataService) =&gt; {

      service.getData&lt;number&gt;('mock-url')
        .subscribe(data =&gt; {
          expect(typeof(data)).toBe('number');
        });

    }));

  });

});
</code></pre>

<p>When I say it doesn't work... the second test passes! but it shouldn't. I can see the real request go out on dev console to the (invalid) url, and that errors out as expected, but the test just passes...</p>

<p>So I guess, my question is simply, in Angular 5, how do I mock my backend service and unit test it please?</p>
",https://stackoverflow.com/questions/50582680/unit-testing-http-service-on-angular-5,"['angular', 'unit-testing']",2551,TRUE,3,1
C# Unit testing a Newtonsoft JSON model,"<p>I am starting with unit testing and am doing so with XUnit.</p>

<p>I have a model :</p>

<pre><code>using Newtonsoft.Json;
namespace HomeAddressSearch
{
    public class Properties
    {
        [Required]
        [JsonProperty(PropertyName = ""civic_number"")]
        public string CivicNumber { get; set; }

        [JsonProperty(PropertyName = ""address"")]
        public string Address { get; set; }

        [JsonProperty(PropertyName = ""postal_code"")]
        public string PostalCode { get; set; }

        [JsonProperty(PropertyName = ""city_name"")]
        public string CityName { get; set; }
    }
}
</code></pre>

<p>and I have a JSON from which I am getting values like :</p>

<pre><code>[
  {
    ""properties"": {
      ""civic_number"": ""100"",
      ""address"": ""100, king street"",
      ""postal_code"": ""H0H0H0"",
      ""city_name"": ""Windsor""
    },
    ""owner"": {
      ""name"": ""John Doe"",
      ""age"": ""40""
    },
  }
]
</code></pre>

<p>So I want to test that model and for so I though of:</p>

<ul>
<li>As CivicNumber is Required I want to make sure there is no Null value or empty string in the JSON, so a test with a null value crashing the test</li>
<li>If ever someone would change the JSON and remove one of the field in the properties object, like city_name, then the test would fail so I know I either need to adapt my model or get back to the original JSON format</li>
<li>Check that format of JSON values, in this case all of them are string, are ok to be injected in my model</li>
<li>Run an injection from a shorter version of a JSON file with like only 3 entries into the model to make sure everything is ok</li>
</ul>

<p>Am I on the right path and how to do this, that would greatly help and kickstart me for a lot of other things.</p>

<p>THanks!</p>
",https://stackoverflow.com/questions/52415325/c-unit-testing-a-newtonsoft-json-model,"['c#', 'json', 'testing', 'xunit']",10843,TRUE,3,1
Swift 4 Unit Testing with Core Data,"<p>I have an iOS project that is working fine on the simulator and whatnot, but cannot seem to link up nicely to the Core Data resources when I'm working from its testing bundle.</p>

<p>I've made the <code>NSManagedObjectContext</code> from memory in the set-up function of my testing class. However, when I attempt to run the program, the test functions fail, and the console has output</p>

<pre><code>""An NSManagedObject of class 'Projectname.Deck' must have a valid NSEntityDescription.""
</code></pre>

<p>Is there something I'm missing? I'd like to be able to make unit tests for my app's data structure as I develop it.</p>

<p>Thanks!</p>

<p>Edit</p>

<p>Relevant sections of the test class:</p>

<pre><code>class ProjectNameTests: XCTestCase {

var testDeck: Deck? = nil

    func setUpInMemoryManagedObjectContext() -&gt; NSManagedObjectContext {
    let managedObjectModel = NSManagedObjectModel.mergedModel(from: [Bundle.main])!

    let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel)

    do {
        try persistentStoreCoordinator.addPersistentStore(ofType: NSInMemoryStoreType, configurationName: nil, at: nil, options: nil)
    } catch {
        print(""Adding in-memory persistent store failed"")
    }

    let managedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
    managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator

    return managedObjectContext
}//setUpInMemoryManagedObjectContext

override func setUp() {
    super.setUp()

    self.context = setUpInMemoryManagedObjectContext()
    testDeck = Deck(context: context)
    testDeck!.name = ""Test Deck""
}//setUp
}//ProjectNameTests
</code></pre>
",https://stackoverflow.com/questions/49701397/swift-4-unit-testing-with-core-data,"['ios', 'swift', 'unit-testing', 'core-data']",2216,TRUE,3,1
QTimer timout doesnt trigger in unit testing,"<p>I'm trying to create a unit testing for a class i made named Counter. Such class should decrease its value ""count"" every 0.1 second, so I connected the method in the class constructor. Everything seems to work just fine in the original program, but when I try to run the unit tester it seems as the connection didnt happen or the QTimer doesnt send the timout signal at all.</p>

<p>gitHub link: <a href=""https://github.com/allocro/TimerLFdP/tree/master/testCounter"" rel=""nofollow noreferrer"">https://github.com/allocro/TimerLFdP/tree/master/testCounter</a></p>

<pre><code>Counter::Counter(QLineEdit *editSec, QLineEdit *editMin, QObject *parent) : 
QObject(parent)
{
    timer= new QTimer(this);
    [...]
    connect(timer, &amp;QTimer::timeout, this, &amp;Counter::decCount);
}
</code></pre>

<p>EDIT: K, I'm gonna try to fit other code part in here as I'm being asked to do so.</p>

<p>In the precedend code, here is the constructor of the class I want to test, what decCount() doesis nothing else than that:</p>

<pre><code>void Counter::decCount(){
    if (count&gt;0)
        count--;
    else
        timer-&gt;stop();

    int countsec = count % 600;
    int countmin = (count - countsec)/600;

    QString secOut = QString::number(countsec/10) + ""."" 
    +QString::number(countsec%10);

    emit showCountMin(countmin);
    emit showCountSec(secOut);
} 
</code></pre>

<p>The above signals are irrelevant to the unit tester code, they were used in the complete program.</p>

<p>Now, in the tst_testCounter.cpp, that as far as I understood, is the test unit version of the classic main, and I got </p>

<pre><code>testCounter::testCounter() : QObject ()
{   int i;
    editSec= new QLineEdit();
    editMin= new QLineEdit();
    counter= new Counter(editSec, editMin);
    for(i=0; i&lt;=10; i++){
        int randsec= rand() %60;
        int randmin= rand() %60;
        randsec=3;
        randmin=0; //To test the tester faster

        QString randsecString= QString::number(randsec);
        QString randminString= QString::number(randmin);


        editSec-&gt;setText(randsecString);
        editMin-&gt;setText(randminString);

        counter-&gt;set();//those are to input, they work fine, I checked
        std::cout &lt;&lt; ""Starting the Timer at "" &lt;&lt; (counter-&gt;count)/10 &lt;&lt; 
        ""sec"" &lt;&lt;std::endl;
        counter-&gt;start(); //{timer-&gt;start();}

        while(counter-&gt;count&gt;0){
            std::cout &lt;&lt;counter-&gt;count &lt;&lt;std::endl;
        }
        auto end= std::chrono::system_clock::now();
        counter-&gt;stop();

        auto check= std::chrono::duration_cast&lt;std::chrono::seconds&gt;(end - 
        start);
        int checkInt= check.count();

        if(checkInt==randsec+(randmin*60)){
            std::cout &lt;&lt; ""Timer matches"" &lt;&lt;std::endl;
        }else{
        std::cout &lt;&lt; ""Timer doesnt match"" &lt;&lt;std::endl;
        std::cout &lt;&lt; ""Sec counted: "" &lt;&lt; (counter-&gt;count)/10 &lt;&lt;std::endl;
        std::cout &lt;&lt; ""Sec passed: "" &lt;&lt; checkInt &lt;&lt;std::endl;
        break;
        }
    }
}
</code></pre>

<p>And obviously the .cpp ends in </p>

<pre><code>QTEST_MAIN(testCounter)

#include ""tst_testcounter.moc""
</code></pre>
",https://stackoverflow.com/questions/52442271/qtimer-timout-doesnt-trigger-in-unit-testing,"['c++', 'qt', 'unit-testing', 'qt5', 'qtimer']",1005,TRUE,3,1
.Net Core DynamodDB unit testing with XUnit,"<p>Using C#, .net core 2.0, dynamo db</p>

<p>I have my web api, that interact with my dynamo db database having both Get and Post methods.</p>

<p>Example of Mehthod:</p>

<pre><code>    [HttpGet(""api/data"")]
    public async Task&lt;List&lt;string&gt;&gt; GetAllData(string userId, string type, string status)
    {
        var creds = new BasicAWSCredentials(awsId, awsPassword);
        var dynamoClient = new AmazonDynamoDBClient(creds, dynamoRegion);
        var context = new DynamoDBContext(dynamoClient);
        List&lt;ScanCondition&gt; conditions = new List&lt;ScanCondition&gt;();
        conditions.Add(new ScanCondition(""UserId"", ScanOperator.Equal, userId));
        conditions.Add(new ScanCondition(""Type"", ScanOperator.Equal, type));
        conditions.Add(new ScanCondition(""Status"", ScanOperator.Equal, status));

        var results = await context.ScanAsync&lt;Common.Job&gt;(conditions, new DynamoDBOperationConfig() { OverrideTableName = MyDynamoTable }).GetRemainingAsync();
        return results.Select(x =&gt; x.UpdatedBy.ToLower()).ToList();
    }
</code></pre>

<p>Now I want to write unit/integration tests for my api methods. Earlier I had used NUnit but with .net core 2.0 I believe we have to use XUnit: <a href=""https://xunit.github.io/docs/getting-started-dotnet-core"" rel=""nofollow noreferrer"">https://xunit.github.io/docs/getting-started-dotnet-core</a></p>

<p>Setting up Xunit in my project should not be an issue.</p>

<p>I wanted to know how can I write test which involve dynamo db here. This is the first time I am using any AWS service here.</p>

<p>So bascially I need to know how can I mock up a aws connection, dynamo db and then use various params as shown in my method above.</p>

<p>I could not find much details or any earlier helpful post on this topic so posting one here.</p>

<hr>

<p>If aws dynamo db part is not testable. Can anyone share the example of xunit test where we can test the params may be and see the expected result?</p>
",https://stackoverflow.com/questions/52784546/net-core-dynamoddb-unit-testing-with-xunit,"['amazon-web-services', 'asp.net-core', '.net-core', 'amazon-dynamodb', 'xunit.net']",6705,TRUE,3,1
Qt Unit Testing C++ with QML qtquick,"<p>I am trying to implement a Qt unit test and I would like to ""click"" a qtquick Button in QML from C++. I am successfully able to use QCompare on the properties of one of my QML objects in <code>test_case3</code> but I can't figure out how to create a click event in <code>test_case4</code>. My Files are below.</p>

<p><strong>tst_case_1.cpp</strong></p>

<pre><code>void tst_case_1::test_case3()
{

    QScopedPointer&lt;MouseMemory&gt; mouse(new MouseMemory);
    QQmlEngine engine;
    engine.rootContext()-&gt;setContextProperty(""mouse"", mouse.data());

    QQmlComponent component(&amp;engine, QUrl(QStringLiteral(""qrc:/main.qml"")));
    QObject *object = component.create();

    QQuickItem *clear = object-&gt;findChild&lt;QQuickItem*&gt;(""clear"");
    QVariant tmp = clear-&gt;property(""text"");
    QCOMPARE(tmp.toString(), ""Clear2"");

    delete object;
}

void tst_case_1::test_case4()
{
    QScopedPointer&lt;MouseMemory&gt; mouse(new MouseMemory);
    QQmlEngine engine;
    engine.rootContext()-&gt;setContextProperty(""mouse"", mouse.data());

    QQmlComponent component(&amp;engine, QUrl(QStringLiteral(""qrc:/main.qml"")));
    QObject *object = component.create();

    QQuickItem *clear = object-&gt;findChild&lt;QQuickItem*&gt;(""clear"");

    /* INSERT CODE HERE
    Implement QML QQuickItem Button click
    /*

    delete object;
}
</code></pre>

<p><strong>main.qml</strong></p>

<pre><code>import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 1.4

Window {
    id: root
    visible: true
    width: 500
    height: 500

    Row {
        id: tools

        Button {
            id: clear
            objectName: ""clear""
            text: ""Clear""
            onClicked: {
                canvas.clear()
            }
        }

        Button {
            id: save
            text: ""Save""
            onClicked: {
                mouse.save()
            }
        }
    }

    Canvas {
        id: canvas
        anchors.top: tools.bottom
        width: 500
        height: 500
        property int lastX: 0
        property int lastY: 0

        function clear() {
            var ctx = getContext(""2d"")
            ctx.reset()
            canvas.requestPaint()
            mouse.clear()
        }

        onPaint: {
            var ctx = getContext(""2d"")
            ctx.lineWidth = 2
            ctx.strokeStyle = color.red

            ctx.beginPath()

            ctx.moveTo(lastX, lastY)

            lastX = area.mouseX
            lastY = area.mouseY

            ctx.lineTo(lastX, lastY)

            ctx.stroke()

            mouse.test()
            mouse.add(lastX, lastY)
        }

        MouseArea {
            id: area
            anchors.fill: parent
            onPressed: {
                canvas.lastX = mouseX
                canvas.lastY = mouseY
            }

            onPositionChanged: {
                canvas.requestPaint()
            }
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/53698574/qt-unit-testing-c-with-qml-qtquick,"['c++', 'qt', 'qml', 'qt5', 'qttest']",909,FALSE,3,0
spring-boot unit testing get application properties,"<p>I'm new to spring-boot, currently trying to develop a kafka producer
I want to test method that use value define in properties file. but it show value is null how solve this.I have added my property files to separate resource file in test folder also
<a href=""https://i.stack.imgur.com/8b4yi.png"" rel=""nofollow noreferrer"">this is my folder structure</a></p>
<pre class=""lang-java prettyprint-override""><code>@SpringBootTest
public class KafkaProducerImplTest {
    @BeforeEach
    void setUp() {
    }

    @Test
    void check() {
        KafkaProducerImpl kpi = new KafkaProducerImpl();
        kpi.check();
    }
    }

    
    @Service
    public class KafkaProducerImpl implements KafkaProducerInterface
    {
    @Value(&quot;${kafka.brokers.local}&quot;)
    private String kafkaBrokers;
    @Value(&quot;${schema-registry}&quot;)
    private String schemaRegistry;

    private Properties config()
    {
        Properties props = new Properties();
        props.setProperty(&quot;bootstrap.servers&quot;,kafkaBrokers);
        props.setProperty(&quot;acks&quot;, &quot;1&quot;);
        props.setProperty(&quot;reties&quot;, &quot;10&quot;);
        props.setProperty(&quot;key.serializer&quot;, StringSerializer.class.getName());                
        props.setProperty(&quot;value.serializer&quot;,Serializer.class.getName());
        props.setProperty(&quot;schema.registry.url&quot;,schemaRegistry);
        return props;
    }

    public &lt;K,T&gt;KafkaProducer&lt;K,T&gt; getProducer()
    {
        return new KafkaProducer&lt;&gt;(config());
    }

    public &lt;T&gt;ProducerRecord createRecord(String Topic,T msg)
    {
        return new ProducerRecord&lt;&gt;(
                Topic,msg
        );
    }


    public void sendMessage(KafkaProducer producer,ProducerRecord record)
    {
        producer.send(record, (recordMetadata, e) -&gt; {
            if (e == null){
                System.out.println(&quot;success&quot;);
            }
        });

        producer.flush();
    }
    public void closeProducer(KafkaProducer producer){
        producer.close();
    }
    public void check(){
        System.out.println(schemaRegistry);
    }
}
</code></pre>
",https://stackoverflow.com/questions/51892576/spring-boot-unit-testing-get-application-properties,"['spring-boot', 'testing', 'junit', 'properties']",3089,TRUE,3,2
Unit Testing : Raise Event From Nested Type,"<p>I have an Interface which has a property on another interface,</p>

<pre><code>public interface IInnerInterface
{
    event EventHandler OnCompleted;
}

public class InnerClassImplementation : IInnerInterface
{
    public event EventHandler OnCompleted;

    private void CompletedState()
    {
        OnCompleted?.Invoke(this, new EventArgs());
    }
}

public interface IOuterInterface
{
    IInnerInterface InnerInterface { get; }
}

public class Main : IOuterInterface
{
    public IInnerInterface InnerInterface { get; }

    public bool IsOperationComplete { get; set; }

    public Main(IInnerInterface innerInterface)
    {
        InnerInterface = innerInterface;
        InnerInterface.OnCompleted += InnerInterface_OnCompleted;
    }

    private void InnerInterface_OnCompleted(object sender, EventArgs e)
    {
        IsOperationComplete = true;
    }
}
</code></pre>

<p>I am trying to test the Main class. One of the test case is to validate the Handler method for the event.</p>

<p>I tried the following code implementation to test,</p>

<pre><code>[TestClass]
public class MainTest
{
    private Mock&lt;IInnerInterface&gt; _innerInterfaceMock;
    private Main _main;

    [TestInitialize]
    public void Initialize()
    {
        _innerInterfaceMock = new Mock&lt;IInnerInterface&gt;();
        _main = new Main(_innerInterfaceMock.Object);
    }

    [TestMethod]
    public void OnCompleted_ShouldDoSomething()
    {
        //Act
        _main.Raise(m=&gt;m.InnerInterface.OnCompleted+=null, new EventArgs());

        //Assert
        _main.IsOperationComplete.Should().BeTrue();

    }
}
</code></pre>

<p>I am getting the following error,</p>

<blockquote>
  <p>Test method
  Samples.MainTest.OnCompleted_ShouldDoSomething
  threw exception:  Telerik.JustMock.Core.MockException: Unable to
  deduce which event was specified in the parameter.
      at Telerik.JustMock.Core.Behaviors.RaiseEventBehavior.RaiseEventImpl(Object
  instance, EventInfo evt, Object[] args)    at
  Telerik.JustMock.Core.ProfilerInterceptor.GuardInternal(Action
  guardedAction)    at
  Samples.MainTest.OnCompleted_ShouldDoSomething()</p>
</blockquote>

<p>Don't know what am I doing wrong?</p>
",https://stackoverflow.com/questions/48547533/unit-testing-raise-event-from-nested-type,"['c#', 'unit-testing', 'justmock']",421,TRUE,2,1
"Unit testing with Arquillian , no default container","<p>I get the following Arquillian error : <strong>org.jboss.arquillian.container.test.impl.client.deployment.ValidationException: DeploymentScenario contains a target (<em>DEFAULT</em>) not matching any defined Container in the registry.
Please include at least 1 Deployable Container on your Classpath.</strong></p>

<p>This are my camel routes class</p>

<p>@Singleton
public class App extends RouteBuilder {</p>

<pre><code>@Inject
private CamelContext context;

@Override
public void configure() throws Exception {

    from(""file://src/main/resources/temp2/"").routeId(""camelmarian"")
            .onException(WrongFileException.class)
            .handled(true)
            .process(new Processor() {
                public void process(Exchange exchange) throws Exception {
                    System.out.println(""Wrong File Name "" + exchange.getIn().getHeader(""CamelFileName""));
                    exchange.getIn().setBody(""Wrong extension"");
                }
            })
            .id(""mockerror"")
            .end()
            .choice()
            .when(header(""CamelFileName"").regex(""data[0-9]*.xml""))
            .process(new XmlProcessor())
            .id(""mockxml"")
            //.to(""mock:xml"")
            .when(header(""CamelFileName"").regex(""data[0-9]*.csv""))
            .process(new CsvProcessor())
            // .to(""mock:csv"")
            .id(""mockcsv"")
            .when(header(""CamelFileName"").regex(""data[0-9]*.txt""))
            .process(new TextProcessor())
            //.to(""mock:txt"")
            .id(""mocktext"")
            .otherwise()
            .throwException(new WrongFileException(""Wrong file extension""));

}
</code></pre>

<p>}</p>

<p>This is the class with endpoints which i am going to mock:</p>

<p>@Singleton<br>
public class CamelContextSetup {</p>

<pre><code>@Inject
private CamelContext camelContext;

private MockEndpoint afterCSV;

private MockEndpoint afterXML;

private MockEndpoint afterTXT;

private MockEndpoint afterError;

@Before
public void setup() throws Exception {

    afterCSV = new MockEndpoint(""mockCSV"");
    afterXML = new MockEndpoint(""mockXML"");
    afterTXT = new MockEndpoint(""mockTXT"");
    afterError = new MockEndpoint(""mockError"");

    camelContext.getRouteDefinition(""camelmarian"").adviceWith(((ModelCamelContext) camelContext), new AdviceWithRouteBuilder() {
        @Override
        public void configure() throws Exception {
            weaveById(""mockcsv"").after().to(afterCSV);
        }
    });

    camelContext.getRouteDefinition(""camelmarian"").adviceWith(((ModelCamelContext) camelContext), new AdviceWithRouteBuilder() {
        @Override
        public void configure() throws Exception {
            weaveById(""mockxml"").after().to(afterXML);
        }
    });

    camelContext.getRouteDefinition(""camelmarian"").adviceWith(((ModelCamelContext) camelContext), new AdviceWithRouteBuilder() {
        @Override
        public void configure() throws Exception {
            weaveById(""mocktext"").after().to(afterTXT);
        }
    });

    camelContext.getRouteDefinition(""camelmarian"").adviceWith(((ModelCamelContext) camelContext), new AdviceWithRouteBuilder() {
        @Override
        public void configure() throws Exception {
            weaveById(""mockerror"").after().to(afterError);
        }
    });

    camelContext.start();

}

@After
public void destroy() {
    afterCSV.reset();
    afterError.reset();
    afterTXT.reset();
    afterCSV.reset();
}

@PreDestroy
public void stopContext() throws Exception {
    camelContext.stop();
}

public MockEndpoint getAfterCSV() {
    return afterCSV;
}

public MockEndpoint getAfterXML() {
    return afterXML;
}

public MockEndpoint getAfterTXT() {
    return afterTXT;
}

public MockEndpoint getAfterError() {
    return afterError;
}
</code></pre>

<p>}</p>

<p>This are the unit tests . When i run them i get that error</p>

<p>@RunWith(Arquillian.class)<br>
public class TestFiles extends CamelTestSupport {</p>

<pre><code>@Inject
CamelContextSetup camelContextSetup;


@Before
public void before() throws Exception {
    camelContextSetup.setup();
}

@After
public void after() {
    camelContextSetup.destroy();
}

@Deployment(testable = false)
public static Archive&lt;?&gt; createArchive() {
        return ShrinkWrap.create(JavaArchive.class)
                .addClass(App.class)
                .addClass(CamelContextSetup.class);
}

@Test
public void testReceived() throws InterruptedException {

    File tempFile = new File(""src/main/resources/temp/data.xml"");
    if (tempFile.renameTo(new File(""src/main/resources/temp2/"" + tempFile.getName())))
        System.out.println(""failed to move file"");
    else {
        camelContextSetup.getAfterXML().expectedMessageCount(1);
        assertMockEndpointsSatisfied();
    }
}

@Test
public void testError() throws InterruptedException {
    File tempFile = new File(""src/main/resources/temp/data4.pl"");
    if (tempFile.renameTo(new File(""src/main/resources/temp2/"" + tempFile.getName())))
        System.out.println(""failed to move file"");
    else {
        camelContextSetup.getAfterError().expectedMessageCount(1);
        assertMockEndpointsSatisfied();
    }
}
</code></pre>

<p>}</p>
",https://stackoverflow.com/questions/48116901/unit-testing-with-arquillian-no-default-container,"['unit-testing', 'jboss', 'jboss-arquillian']",1010,TRUE,2,1
Do Guard Clauses Alone Require Unit Testing?,"<h1>TLDR</h1>

<p>Does this method require <strong>Unit</strong> Testing?  If your answer is Yes, please ensure you understand my thought process by reading the whole Question.</p>

<pre><code>public void UpdateChildSomethings(int parentId, string newVal, int bulkSize) {
    var skip = 0;
    List&lt;Child&gt; children = null;
    while ((children = _.GetChildrenFromDB(parentId, skip, bulkSize)).Count &gt; 0) {
        var alteredChildren = AlterChildren(children, newValue); // Note: AlterChildren is fully tested separately.
        _.BulkUpdateDB(alteredChildren);
        skip += bulkSize;
    }
}
</code></pre>

<h1>Foreword</h1>

<p>First off, I am a heavy Unit Tester.  I do it often, and I do it well.  But given my experience, I have gained opinions and may need somebody to put my in my place, or provide me with documentation to support or oppose me.</p>

<p>Opening Disclaimer: If I have an obviously tested method (Like <code>Alter</code> and <code>AlterChildren</code> below), and they have Guard Clauses in them, I'm probably going to end up testing the Guard Clauses, if for nothing more than 100% coverage in those tests.  But apart from that...</p>

<h1>The Question</h1>

<p>Let's begin my question with this method:</p>

<pre><code>public void UpdateSomething(int id, string newVal) {
    var actualSomething = _.GetFromDB(id);
    var alteredSomething = Alter(actualSomething, newVal);
    _.UpdateDB(id, alteredSomething);
}
</code></pre>

<p>Does this method require Unit Testing?  For multiple reasons, I would personally say no, at least not at this time.  Especially if <code>Alter()</code> is abundantly tested.  The action of Getting from DB and Updating DB have no value to Unit Test, and would be mocked anyway.</p>

<p>Assuming you follow my mindset and agree that method shouldn't be tested, what about this method?</p>

<pre><code>public void UpdateSomething(int id, string newVal) {
    var actualSomething = _.GetFromDB(id);
    if (actualSomething == null) return;
    var alteredSomething = Alter(actualSomething, newVal);
    _.UpdateDB(id, alteredSomething);
}
</code></pre>

<p>I added a ""Guard Clause"".  This is not business logic or calculation.  It is code which determines the flow of code and early return.  If I were to Unit Test this, I would essentially be testing the result of GetFromDB, and therefore be <strong>Testing a Mock</strong>.  As far as I am concerned, Testing a Mock is not a useful test.</p>

<h1>More Complex</h1>

<p>But assuming you STILL follow my mindset and agree that Guard Clauses based on External Data is a waste to Unit Test, what about this method?</p>

<pre><code>public void UpdateChildSomethings(int parentId, string newVal, int bulkSize) {
    var skip = 0;
    List&lt;Child&gt; children = null;
    while ((children = _.GetChildrenFromDB(parentId, skip, bulkSize)).Count &gt; 0) {
        var alteredChildren = AlterChildren(children, newValue);
        _.BulkUpdateDB(alteredChildren);
        skip += bulkSize;
    }
}
</code></pre>

<p>For clarity, I'll refactor this to break down the <code>while</code> clause</p>

<pre><code>/// Uses parentId to retrieve applicable children in chunks of bulkSize.
/// children are processed separately.
/// Passes processed children to the DB to be updated.
public void UpdateChildSomethings(int parentId, string newVal, int bulkSize) {
    var skip = 0;
    List&lt;Child&gt; children = null;
    while (true) {
        children = _.GetChildrenFromDB(parentId, skip, bulkSize);
        if (children.Count == 0) break;
        var alteredChildren = AlterChildren(children, newValue);
        _.BulkUpdateDB(alteredChildren);
        skip += bulkSize;
    }
}
</code></pre>

<p>At first glance, this looks complex enough to test, but what are you testing?  Once again assuming that <code>AlterChildren()</code> is abundantly tested, the only thing left to test is the result of GetChildrenFromDB(), which is mocked.  Once again <strong>Testing a Mock</strong>.  The only line here doing something is <code>skip += bulkSize</code>.  What would you be testing there, the <code>+=</code> operator?  I still don't see the point.</p>

<p>So, that is my most complex example, should it be Unit Tested?</p>
",https://stackoverflow.com/questions/51468598/do-guard-clauses-alone-require-unit-testing,"['c#', 'unit-testing']",545,TRUE,2,2
unit-testing Angular 5 with socket.io mockup,"<p>Im trying to unit-test a service which has <a href=""https://github.com/socketio/socket.io"" rel=""nofollow noreferrer"">socket.io</a> imported by using <a href=""https://github.com/thoov/mock-socket#readme"" rel=""nofollow noreferrer"">mock-socket</a>. I looked at similar problem such as <a href=""https://stackoverflow.com/questions/44656279/unit-testing-socket-io-in-angular?answertab=active#tab-top"">this</a> one and I'm not being able to get it to work with following.</p>

<pre><code>import { TestBed, inject, async } from '@angular/core/testing';
import { SocketIO, Server } from 'mock-socket';
import { BackendService } from './backend.service';

  describe('BackendService', () =&gt; {

  /* setup for mock-socket in order to test socket.io */
  const SERVER_URL = window.location.host;
  const mockServer = new Server(SERVER_URL);

  // setting up server mock
  mockServer.on('connection', socket =&gt; {
    mockServer.emit('server-message', 'test message 1');
  });

  beforeEach(() =&gt; {

    TestBed.configureTestingModule({
        imports: [ ],
        providers: [ BackendService ]
    });

    jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000;

  });

  it('tests simple connection and messaging works with mock-socket setup', async(inject([BackendService], (service: BackendService) =&gt; {

  (window as any).io = SocketIO;  

  // setting up client
  service.socket = io(window.location.host);

  setTimeout(() =&gt; {
      service.socket.on('connect', (message) =&gt; {
          expect(message).toEqual('test message 1');
          mockServer.stop();
      });  
  }, 100);

  })));

});
</code></pre>

<p>Anyone that has come around this?</p>

<p>I've created a <a href=""https://stackblitz.com/edit/ngx-unit-test-socketio?embed=1&amp;file=src/app/test-view-socketIO/backend.service.spec.ts&amp;view=preview"" rel=""nofollow noreferrer"">Stackblitz</a> to recreate the scenario if it makes things easier to follow.</p>
",https://stackoverflow.com/questions/51205639/unit-testing-angular-5-with-socket-io-mockup,"['angular', 'typescript', 'unit-testing', 'socket.io', 'jasmine']",1705,TRUE,2,1
mockito unit testing Wanted but not invoked:,"<p>I have seen there are similar question already exist in SO , I tried all the solution , but couldn't fix my problem , as I am new to <code>tdd</code> </p>

<p>I have a class like this </p>

<pre><code>public class AppUpdatesPresenter  {

    public void stopService() {
        ServiceManager.on().stopService();
    }
}
</code></pre>

<p>I have the test class like this</p>

<pre><code>@RunWith(MockitoJUnitRunner.class)
public class AppUpdatesPresenterTest {
       @Mock
       AppUpdatesPresenter appUpdatesPresenter;

       @Mock
       ServiceManager serviceManager;

       @Mock
       Context context;

       @Test
       public void test_Stop_Service() throws Exception {
            appUpdatesPresenter.stopService();
            verify(serviceManager,times(1)).stopService();
       }

}
</code></pre>

<p>When I tried to test that , if I call <code>stopService()</code> method , then <code>ServiceManager.on().stopService();</code> called at least once . </p>

<p>But I am getting the following error</p>

<pre><code>Wanted but not invoked:
serviceManager.stopService();
-&gt; at io.example.myapp.ui.app_updates.AppUpdatesPresenterTest.test_Stop_Service(AppUpdatesPresenterTest.java:103)
Actually, there were zero interactions with this mock.
</code></pre>

<p>Not sure whats gone wrong . </p>
",https://stackoverflow.com/questions/52268931/mockito-unit-testing-wanted-but-not-invoked,"['junit', 'mockito', 'tdd']",2464,TRUE,2,1
Unit testing Angular 6 location go back,"<p>I need simple unit testing of location go back.</p>

<p><strong>main.ts</strong></p>

<pre><code>import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';

@Component({
  selector: 'app-product-information',
  templateUrl: './product-information.component.html',
  styleUrls: ['./product-information.component.scss']
})
export class ProductInformationComponent implements OnInit {

  constructor(
    private location: Location
  ) { }

  ngOnInit() {
  }

  close(): void {
    this.location.back();
  }
}
</code></pre>

<p>Tried in <strong>main.spec.ts</strong></p>

<pre><code>  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(ProductInformationComponent);
    component = fixture.componentInstance;
    de = fixture.debugElement;
    loc = jasmine.createSpyObj('Location', ['back']);
    fixture.detectChanges();
  });

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });

  it('should clicked back', () =&gt; {
    el = fixture.debugElement.query(By.css('.btn-cancel')).nativeElement.click();
    expect(loc.back).toHaveBeenCalledTimes(1);
  });
</code></pre>

<p>It didnt worked i got error </p>

<p><strong>Expected spy Location.back to have been called once. It was called 0 times.</strong></p>
",https://stackoverflow.com/questions/53495617/unit-testing-angular-6-location-go-back,"['angular', 'unit-testing']",2670,FALSE,2,2
mock bufio external package for unit testing,"<p>I need to mock bufio <a href=""https://golang.org/pkg/bufio/#NewReader"" rel=""nofollow noreferrer"">Reader</a> for testing. specifically the <a href=""https://golang.org/pkg/bufio/#Reader.ReadString"" rel=""nofollow noreferrer"">ReadString</a> API.</p>

<pre><code>func NewReader(rd io.Reader) *Reader
func (b *Reader) ReadString(delim byte) (string, error)
</code></pre>

<p>The <code>NewReader</code> returns <code>bufio.Reader</code>.
Since it does not return an abstraction/interface, I cannot create a adapter for the Reader.</p>

<p>Could you please help. </p>
",https://stackoverflow.com/questions/50803598/mock-bufio-external-package-for-unit-testing,['go'],798,TRUE,2,1
adding unit testing to vue cli build,"<p>I've been adding some unit tests to my project recently and was wondering is it possible to add those unit tests to my yarn run build process. Or would it be better to create a bash script the runs both cmds like yarn run unit then yarn run build. </p>

<p>How would I go about this?</p>

<p>I'm using VueJs cli along with Jest for the unit testing </p>
",https://stackoverflow.com/questions/51539006/adding-unit-testing-to-vue-cli-build,"['javascript', 'vue.js', 'jestjs']",610,TRUE,2,1
unit testing libgdx with using gdx functionallity,"<p>I have a runnig libgdx project, which I would like to unittest.</p>

<p>I don't know how to use gdx funtionality in a unittest, which I do not like to mock. I get errors using libgdx framework in my unittest.</p>

<p>I get the following error with following code (Texture texture = new Texture(""ship.png"");):</p>

<pre><code>java.lang.NullPointerException
    at com.badlogic.gdx.graphics.Texture.&lt;init&gt;(Texture.java:88)
</code></pre>

<p>Code : </p>

<pre class=""lang-java prettyprint-override""><code>public class MapDrawerTest extends ApplicationAdapter {

    MapDrawer mapDrawer;
    SpriteBatch batch;

    @Before
    public void setUp() throws Exception {

        Schiff schiff = new Schiff();
        World world = new World(100,100);
        mapDrawer = new MapDrawer(world, schiff);
        batch =  Mockito.mock(SpriteBatch.class);
    }

    @Test
    public void drawFeld() {

        Feld feld1 = new Feld(new Feldkoordinate(1,1), Feldtyp.LANDPALMEN);

        Texture texture = new Texture(""ship.png"");
        List&lt;Texture&gt; textures = new ArrayList&lt;Texture&gt;();
        textures.add(texture);
        feld1.addTexture(new FeldTexture(textures,60));

        mapDrawer.drawFeld(batch, feld1);

    }
}
</code></pre>
",https://stackoverflow.com/questions/53010755/unit-testing-libgdx-with-using-gdx-functionallity,['libgdx'],417,TRUE,2,1
Asp.net FluentValidation unit testing object as null,"<p>I'm doing some unit testing using FluentValidation in Asp.net. I have setup a rule stating that an object is not allowed to be null, as it's going to be used as an argument in a method. The rule is made in a validator-class in the constructor: </p>

<pre><code> //Object itself.
 RuleFor(x =&gt; x).NotNull();
</code></pre>

<p>The unit test looks like (I'm using NUnit):</p>

<pre><code>[Test]
public void RequestObjectIsNull_ExpectError()
{
    BusinessRequest request = null;
    var result = validator.Validate(request);

    Assert.IsFalse(result.IsValid);
}
</code></pre>

<p>It fails with the message:</p>

<blockquote>
  <p>Message: System.ArgumentNullException : Cannot pass null model to Validate.
  Parameter name: instanceToValidate</p>
</blockquote>

<p>How do I test this?</p>
",https://stackoverflow.com/questions/53392865/asp-net-fluentvalidation-unit-testing-object-as-null,"['asp.net', 'unit-testing', 'nunit', 'fluentvalidation']",1826,TRUE,2,1
Unit testing database: no such table: migrations,"<p>Trying to use an in-memory <code>testing</code> database for my unit tests. It seems that it can't even run the migrations, because the <code>migrations</code> table does not exist.</p>

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

<pre><code>abstract class TestCase extends BaseTestCase
{
    use DatabaseMigrations;

    public function setUp()
    {
        parent::setUp();

        // use testing database
        $this-&gt;setUpDatabase();
    }

    public function setUpDatabase()
    {
        $this-&gt;app['config']-&gt;set('database', [
            'default' =&gt; 'testing',
            'connections' =&gt; [
                'testing' =&gt; [
                    'driver' =&gt; 'sqlite',
                    'database' =&gt; ':memory:',
                ],
            ],
        ]);
    }
</code></pre>

<p>This gives me the error:</p>

<blockquote>
  <p>PDOException: SQLSTATE[HY000]: General error: 1 no such table: migrations</p>
</blockquote>

<p>Not only that, but it also seems to be running migrations on my main database.</p>
",https://stackoverflow.com/questions/53618786/unit-testing-database-no-such-table-migrations,"['php', 'laravel', 'unit-testing']",603,FALSE,2,0
Custom Annotation not found while unit testing,"<p>say i've an Annotation like that:</p>

<pre><code>@Retention(RetentionPolicy.RUNTIME)
public @interface AutoConvert {
    boolean enabled() default true;
}
</code></pre>

<p>and class annotated with it:</p>

<pre><code>@AutoConvert
public class ExampleCommandToExample extends BaseConverter{}
</code></pre>

<p>On the superclass i'am doing the following:</p>

<pre><code>public void convert(){
  Annotation annotation = (AutoConvert) this.getClass().getAnnotation(AutoConvert.class);
}
</code></pre>

<p>Everything works fine on runtime! Annotation is getting found and properly set!</p>

<p>But! While unit testing the convert method with JUnit:
this.getClass().getAnnotation(AutoConvert.class) 
<strong>always returns null.</strong></p>

<p>The test looks like this:</p>

<pre><code>@Test
public void convertTest(){
    //when
    exampleCommandToExample.convert();
}
</code></pre>

<p>Are custom annotations not being found by reflection while running unit tests?
Does anyone has an answer for me?
I would really really appreciate it.</p>

<p>Thank you in advance.</p>

<p><strong>EDIT:</strong>
Alright it seems to be grounded in the kind of intatiation...
I do the following:</p>

<pre><code>exampleCommandToExample = new ExampleCommandToExample() {
    @Override
    public Type overideSomeMethod() {
        return type;
    }
};
</code></pre>

<p>May it be possible that an instance looses all it's annotations 
if I override some methods on instantiation?</p>
",https://stackoverflow.com/questions/50587122/custom-annotation-not-found-while-unit-testing,"['java', 'reflection', 'junit', 'annotations']",2337,TRUE,2,1
Angular 4 unit testing template parse errors:,"<p>I am getting the following error when I run angular unit test using Jasmine.  </p>

<p>Error: Template parse errors:
Property binding cdkHeaderRowDef not used by any directive on an embedded template. Make sure that the property name is spelled correctly and all directives are listed in the ""@NgModule.declarations"". (""
    
[ERROR ->]
    

<pre><code>&lt;mat-header-row *cdkHeaderRowDef=""displayedColumns""&gt;&lt;/mat-header-row&gt;
[ERROR -&gt;]&lt;mat-row *cdkRowDef=""let row; columns: displayedColumns; let i = index; let isOdd = odd; let isEven =""): ng:///DynamicTestModule/TabledataComponent.html@57:4
</code></pre>

<p>Its looks like material design parsing error. Please suggest me what would be the issue?</p>
",https://stackoverflow.com/questions/49383637/angular-4-unit-testing-template-parse-errors,"['angular', 'jasmine', 'angular-unit-test']",2490,TRUE,2,1
php unit testing - Property does not exist,"<p>I am creating some test cases for my application and i am stuck at a point. I am trying to set a property to the class. But its a parent Class property. This is my actual method</p>

<pre><code>public function uploadFiles($files, $endpoint = 'outbox', $config = [])
    {
        $user = $this-&gt;_BxApi-&gt;users-&gt;getUser($config);
        $result = [];
        foreach ($files as $key =&gt; $file) {
            $policy = 'policy' . $key;
            $result[] = $this-&gt;_fileUploader-&gt;uploadFile($file, $policy, $config);
        }

        return $result;
    }
</code></pre>

<p>This is a method in Class <code>Uploads</code> which extent Class <code>API</code> and the API class is </p>

<pre><code>class Api
{

    public function __construct(BxClient $bxclient)
    {
        $this-&gt;_BxApi = $bxclient;
    }
}
</code></pre>

<p>And my test case is </p>

<pre><code>public function testUploadFiles_Upload2Files()
{
    $bxMock = $this-&gt;_getMock(\BxClient\Core\Api\Uploads::class, [
        '_request' =&gt; true
    ]);

    $this-&gt;_setProperty($bxMock, 'users', $this-&gt;_getMock(Users::class, [
        'getUser' =&gt; (object) ['userId' =&gt; 'test']
    ]));
    $this-&gt;_setProperty($bxMock, '_fileUploader', $this-&gt;_getMock(FileUploader::class, [
        'uploadFile' =&gt; true,
    ]));

    $result = $bxMock-&gt;uploadFiles(['1.txt', '2.txt']);

    $this-&gt;assertEquals(2, count($result));
    $this-&gt;assertTrue($result[0]);
    $this-&gt;assertTrue($result[1]);
}
</code></pre>

<p>I think I am doing something wrong in </p>

<pre><code>$this-&gt;_setProperty($bxMock, 'users', $this-&gt;_getMock(Users::class, [
        'getUser' =&gt; (object) ['userId' =&gt; 'test']
    ]));
</code></pre>

<p><strong>Update</strong>
This is the error</p>

<blockquote>
  <p>ReflectionException: Property users does not exist</p>
</blockquote>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/50795709/php-unit-testing-property-does-not-exist,"['php', 'unit-testing', 'oop', 'testing']",940,FALSE,2,1
Jest unit testing - Async tests failing Timeout,"<p>I got the following error message ""Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL."" On top of that, I also received an error message stating that 0 assertions were executed while expecting 2 assertions.</p>

<p>I've tried extending the timeout to 10 seconds using <code>jest.setTimeout(10000)</code>, which should be more than sufficient time to execute that code, but the problem persisted.</p>

<p>I know <code>m.employeeGetAll()</code> works because when I test my web app using the browser, I can see the list of employees in the view.</p>

<p>Here's how my test looks like</p>

<pre><code>it('Lists all employees successfully', () =&gt; {
  expect.assertions(2);
  return m.employeeGetAll().then(result =&gt; { //m.employeeGetAll() returns a promise       
    expect(result).toBeDefined();
    expect(result.length).toBe(3);
  });  
});
</code></pre>
",https://stackoverflow.com/questions/48142811/jest-unit-testing-async-tests-failing-timeout,"['javascript', 'jestjs']",5238,TRUE,2,2
Unit Testing Vue Component - Jest Setup - Unexpected Identifier error,"<p>I am new to Jest and am trying to run a simple unit test just to ensure everything is set up correctly and have been running in to lots of issues troubleshooing errors during compile time.</p>

<p>When running the testing suite, Jest is successfully finding the file I am trying to test and generates the following Unexpected Identifier error message on line 1.
Any idea why this is? is something missing? I have been trying to troubleshoot this for quite some time.  </p>

<pre><code>/Users/foo/Sites/test/Test.spec.js:1
    ({""Object.&lt;anonymous&gt;"":function(module,exports,require,__dirname,__filename,global,jest){import Test from './Test.vue';
                                                                                                    ^^^^

    SyntaxError: Unexpected identifier

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
</code></pre>

<p>Note, removing the import statements altogether runs the test successfully. However, the whole reason I set up Jest was to test vue components. </p>

<p>Test.vue</p>

<pre><code>&lt;template&gt;
        &lt;div class=""test""&gt;
        &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
    export default {
        name: 'test',
        components: { },
        data() {
            return {

            }
        },
        methods: {
            helloWorld() {
                return 'hello world';
            }
        }
    }
&lt;/script&gt;
</code></pre>

<p>Test.spec.js</p>

<pre><code>import Test from './Test.vue'

describe('Test',() =&gt; {
   it('test', () =&gt; {
     expect(true).toBe(true);
   });
});
</code></pre>

<p>package.json</p>

<pre><code>""devDependencies"": {
    ""@vue/test-utils"": ""^1.0.0-beta.25"",
    ""axios"": ""^0.18.0"",
    ""babel-core"": ""^6.26.0"",
    ""babel-jest"": ""^23.6.0"",
    ""babel-loader"": ""^7.1.2"",
    ""cross-env"": ""^5.1.1"",
    ""file-loader"": ""^2.0.0"",
    ""jest"": ""^23.6.0"",
    ""jquery"": ""^3.2"",
    ""laravel-mix"": ""^2.0"",
    ""lodash"": ""^4.17.4"",
    ""popper.js"": ""^1.14.3"",
    ""source-map-support"": ""^0.5.9"",
    ""vue"": ""^2.5.7"",
    ""vue-jest"": ""^3.0.0"",
    ""vue-test-utils"": ""^1.0.0-beta.11"",
    ""webpack"": ""^3.8.1""
  },
  ""jest"": {
    ""moduleFileExtensions"": [
      ""js"",
      ""json"",
      ""vue""
    ],
    ""transform"": {
      "".*\\.(vue)$"": ""vue-jest"",
      ""^.+\\.js$"": ""babel-jest""
    }
  }
</code></pre>
",https://stackoverflow.com/questions/52807578/unit-testing-vue-component-jest-setup-unexpected-identifier-error,"['javascript', 'unit-testing', 'vue.js', 'npm', 'jestjs']",2385,TRUE,15,1
Unit testing a periodic timer via handle_info,"<p>I have a GenServer which performs a periodic action like so:</p>

<pre><code>defmodule Hello
  use GenServer
  def init(_) do
    Process.send_after(self(), :timer, 1000)
    {:ok, %{}}
  end

  def handle_info(:timer, state) do
    # do stuff
    Process.send_after(self(), :timer, 1000)
    {:noreply, state}
  end
end
</code></pre>

<p>I'm trying to figure out the best way to unit test it. My initial idea was to use <a href=""https://github.com/plataformatec/mox"" rel=""nofollow noreferrer"">mox</a> to stub the Process.send_after call. This works fine, but then in my unit test, I tried something like this:</p>

<pre><code>test ""the timer callback does the right thing"" do
  MyMock |&gt; expect(:timer, fn -&gt; :ok end)
  {:ok, pid} = start_supervised(Hello, [])
  Process.send(pid, :timer)
  # assert the right thing happens
end
</code></pre>

<p>However, this doesn't work because <code>Process.send</code> is async and doesn't return me anything. How else can I test the <code>handle_info</code> callback?</p>
",https://stackoverflow.com/questions/50914907/unit-testing-a-periodic-timer-via-handle-info,"['unit-testing', 'async-await', 'elixir', 'gen-server']",708,FALSE,1,1
ClassCastException onAttach() when unit testing Android Fragment,"<p>I'm trying to test a Fragment that has in interface that must be implemented by the hosting Activity and gets casted to that specific interface's type through <code>onAttach()</code>.</p>

<p><strong>Problem</strong>: I'm not sure how to implement the necessary interface methods within an Android Unit Test or if it's even necessary to do so. Surprisingly, I haven't found any posts or forums that address this issue.</p>

<p><strong>Test</strong>:</p>

<pre><code>public class FragmentTest {

    private ActivityForUnitTesting fragmentHostActivity;
    private ExampleFragment fragmentToTest;

    @Rule
    public ActivityTestRule activityTestRule = new ActivityTestRule&lt;&gt;(ActivityForUnitTesting.class);

    @Before
    public void setUp() {
        fragmentHostActivity = (ActivityForUnitTesting) activityTestRule.getActivity();
        fragmentManager = fragmentHostActivity.getSupportFragmentManager();
        fragmentToTest = new ExampleFragment();
    }

    @Test
    public void testExample() {
        fragmentManager.beginTransaction()
                .replace(R.id.frame_layout_container, fragmentToTest)
                .commit();
    }

}
</code></pre>

<p><strong>Fragment</strong>:</p>

<pre><code>public class ExampleFragment extends Fragment {

    private ExampleFragmentListener exampleFragmentListener;

    ...

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            exampleFragmentListener = (ExampleFragmentListener) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString() + "" must implement ExampleFragmentListener"");
        }
    }

    ...

}
</code></pre>

<p><strong>but when I try running a simple test I get</strong>:</p>

<blockquote>
  <p>java.lang.ClassCastException: com.example.package.ActivityForUnitTesting@1234567 must implement ExampleFragmentListener
  at com.example.package.ExampleFragment.onAttach(ExampleFragment.java:)</p>
</blockquote>

<p>I know that the issue is that my Unit Test ActivityForUnitTesting object does not implement the required interface methods. My question is, <strong>how do I safely implement those methods within my Unit Test</strong>. I haven't had any luck finding a similar question or a solid example.</p>
",https://stackoverflow.com/questions/51976223/classcastexception-onattach-when-unit-testing-android-fragment,"['android', 'unit-testing', 'android-fragments', 'listener', 'classcastexception']",471,TRUE,1,1
Phalcon PHP Unit Testing DI Shared Instance,"<p>So I have started implementing unit testing as part of my phalcon application and have come across an issue in relation to using the Phalcon DI Container. It might just be my lack of understanding but I can't seem to get my service to be used as a shared instance across all test cases. Is this something that's possible to begin with ? I have scoured the web for as many resources as I could find and even followed the tutorial on the Phaclon website, but to no avail. So here are my files so far</p>

<p><em>init.php</em></p>

<pre><code>&lt;?php

 use Phalcon\Loader;
 use Phalcon\Di;
 use Phalcon\Di\FactoryDefault;

 ini_set(""display_errors"", 1);
 error_reporting(E_ALL);

 define(""ROOT_PATH"", __DIR__);
 define(""SRC_PATH"", __DIR__ . '/../src');

 set_include_path(
     ROOT_PATH . PATH_SEPARATOR . get_include_path()
 );

 // Required for phalcon/incubator
 include __DIR__ . ""/../vendor/autoload.php"";

 // Setup Phalcon autoloader.
 $loader = new Loader();

 $loader-&gt;registerDirs(
    [
      ROOT_PATH,
      SRC_PATH . '/util'
    ]
 );

 $loader-&gt;registerNamespaces(
    [
     'App\Test\Libs' =&gt; ROOT_PATH . '/libs'
    ]
);

$loader-&gt;register();

// Setup DI Container.
$di = new FactoryDefault();

$di-&gt;setShared('someClass', function () {
 return new \App\Test\Libs\SomeClass();
});

Di::setDefault($di);
</code></pre>

<p>Now in my <em>UnitTestCase</em> if i do </p>

<pre><code>  public function setUp() { 
     parent::setUp();

     $di = Di::getDefault();

     var_dump($di-&gt;getServices()); // None of my services from the bootstrap show up ???
     $this-&gt;setDi($di);

     $this-&gt;_loaded = TRUE;
  }
</code></pre>

<p>And as a result of the above none of my actual tests which extend <em>UnitTestCase</em> can access the custom services. </p>

<p>I tried moving the Phalcon DI initialisation inside the <em>UnitTestCase</em> <code>setUp()</code> however this meant that a new instance of my service was being returned each time, when I would like to just retrieve the same instance. </p>

<p>So is there something I am missing ? Is this even the correct way to do it ? </p>

<p>I Would really appreciate any form of guidance on this issue</p>
",https://stackoverflow.com/questions/53557700/phalcon-php-unit-testing-di-shared-instance,"['php', 'phpunit', 'phalcon']",400,TRUE,1,1
Unit Testing: should change class after click,"<p>When clicking on <code>&lt;mat-expansion-panel&gt;</code> (<code>Angular Material</code>) it should add a class <code>mat-expanded</code> but whenever I run the function the DOM is still the same when I log it, the class is not added.</p>

<p><strong>HTML</strong></p>

<pre><code>&lt;mat-expansion-panel (opened)=""toggleCollapseRow('open')"" (closed)=""toggleCollapseRow('closed')""&gt;
...
</code></pre>

<p><strong>Function in compononent.ts</strong></p>

<pre><code>public toggleCollapseRow(openOrClosed: string): void {
    if (openOrClosed === 'open') {
        this.expandCollapseIcon = 'ic_collapse_default';
    } else if (openOrClosed === 'closed') {
        this.expandCollapseIcon = 'ic_expand_default';
    }
}
</code></pre>

<p><strong>Unit Test</strong></p>

<pre><code>it('should expand on click', fakeAsync(() =&gt; {
    fixture.detectChanges();
    const panel = fixture.nativeElement.querySelector('mat-expansion-panel');
    const spy = spyOn(component, 'toggleCollapseRow').and.callThrough();
    panel.click();
    component.toggleCollapseRow('open');
    tick();
    fixture.detectChanges();
    // this logs the same output with no class added
    console.log(fixture.nativeElement.querySelector('mat-expansion-panel'));
    expect(spy);
    expect(component.toggleCollapseRow).toHaveBeenCalled();
    expect(component.expandCollapseIcon).toEqual('ic_collapse_default');
}));
</code></pre>

<p>This all succeeds but when I add the following, it fails because the DOM is still the same:</p>

<pre><code>expect(fixture.nativeElement.querySelector('.mat-expanded')).toBeTruthy()
</code></pre>
",https://stackoverflow.com/questions/49282213/unit-testing-should-change-class-after-click,"['angular', 'unit-testing', 'typescript', 'karma-jasmine']",2447,TRUE,1,1
Unit testing an Controller with AutoMapper issue,"<p>I am trying to test a controller in my asp.netcore application. The test is failing because of auto-mapper.
I tried to mock to the auto-mapper but i do not know how to use it correctly.
Would anyone be able to suggest a way of overcoming this?
Thanks.</p>

<p>BooksController.cs</p>

<pre><code>[HttpGet(""{id:int}"")]
public IActionResult GetBook(int id)
{
    var bookfromRepo = _repository.GetBook(id);
    var book = Mapper.Map&lt;BookDto&gt;(bookfromRepo);
    return Ok(book);
}
</code></pre>

<p>startup.cs</p>

<pre><code>AutoMapper.Mapper.Initialize(cfg =&gt;
{
    cfg.CreateMap&lt;Data.Database.Entities.Book, BookDto&gt;();
});
</code></pre>

<p>ControllerTest.cs</p>

<pre><code>[Fact(DisplayName = ""GetBook"")]
public void GetBook()
{
    //act
    var fakerepository = new Mock&lt;IBPDRepository&gt;();
    var sut = new BooksController(fakerepository.Object);

    //act
    var book = new BookDto();
    var viewModelBook = new BookDto {
        Id  =    1,
        Name = ""C#"", 
        Review = ""good"", 
        Pages = ""500"",
        Rating = ""8"",
        Price =""$10.00""
    };

    //var mockMapper = new Mock //stuck here;
    sut.GetBook(1);

    //assert
    IActionResult actionResult = sut.GetBook(2);
    Assert.Equal(""C#"",viewModelBook.Name);
}
</code></pre>
",https://stackoverflow.com/questions/50295436/unit-testing-an-controller-with-automapper-issue,"['c#', 'unit-testing']",65,FALSE,1,1
Unit testing method for WebAPI2 Post method,"<p>I'm planning to create a unit testing project for my WebAPI controller post method.</p>

<p>My WebAPI controller is as follows,</p>

<pre><code>[RoutePrefix(""api/brands"")]
public class HomeController : ApiController
{
    [HttpGet]
    [Route(""{brandID}/employee/{employeeID}"")]
    public IHttpActionResult EnableParticipation(int brandID, int employeeID)
    {
        try
        {
            RequestService _requestService = new RequestService();
            bool result = _requestService.EnableParticipation(brandID, employeeID);
            return Ok(result);
        }
        catch (Exception)
        {
            return InternalServerError();
        }
    }
}
</code></pre>

<p>I need to write a Unit testing class for this HTTP Post method of my WebAPI controller.</p>

<p>What would be the best way to do this with mocking so that it does not hit the database.?</p>

<p>Here is what I have tried so far...</p>

<pre><code>[TestClass]
public class HomeTest
{
    [TestMethod]
    public void EnableParticipation()
    {
        var controller = new HomeController();
        //IHttpResponse response  = controller.EnableParticipation(1, 2);
        // How to mock the call
    }
}
</code></pre>
",https://stackoverflow.com/questions/51156407/unit-testing-method-for-webapi2-post-method,"['c#', 'unit-testing', 'asp.net-web-api2', 'http-post']",24,FALSE,1,0
mlUnitTest not working for MarkLogic Unit Testing,"<p>I have setup the UnitTetsing Framework for Marklogic using the below url-</p>

<p><a href=""https://github.com/marklogic-community/marklogic-unit-test"" rel=""nofollow noreferrer"">https://github.com/marklogic-community/marklogic-unit-test</a></p>

<p>I am able to deploy my project using <code>mlDeploy</code> and able to load my Testing module using <code>mlUnitTestLoadModules</code> but while running the test cases from gradle <code>mlUnitTest</code> i am getting the below error-</p>

<pre><code>Task ':mlUnitTest' is not up-to-date because:
Task has not declared any outputs.
Releasing connection

:mlUnitTest (Thread[Daemon worker Thread 16,5,main]) completed. Took 0.064 secs


FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':mlUnitTest'.
&gt; java.lang.NullPointerException (no error message)

* Try:
Run with --stacktrace option to get the stack trace. Run with --debug option to
get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org 
</code></pre>

<p>Any Suggestions ??</p>
",https://stackoverflow.com/questions/52849490/mlunittest-not-working-for-marklogic-unit-testing,"['unit-testing', 'xquery', 'marklogic', 'marklogic-dhf']",116,FALSE,1,1
Async unit testing with NUnit and C#,"<p>I have the following method I created it's nothing fancy just retrieves data from an HTTP server but it is an async method.</p>

<pre><code>public async Task&lt;string&gt; GetStringFromConsul(string key)
    {
        string s = """";

        // attempts to get a string from Consul
        try
        {
            //async method to get the response
            HttpResponseMessage response = await this.http.GetAsync(apiPrefix + key);

            //if it responds successfully
            if (response.IsSuccessStatusCode)
            {
                //parse out a string and decode said string
                s = await response.Content.ReadAsStringAsync();
                var obj = JsonConvert.DeserializeObject&lt;List&lt;consulValue&gt;&gt;(s);
                s = Encoding.UTF8.GetString(Convert.FromBase64String(obj[0].value));
            }
            else
            {
                s = requestErrorCodePrefix + response.StatusCode + ""&gt;"";
            }
        } 
        catch(Exception e)
        {
            //need to do something with the exception
            s = requestExceptionPrefix + e.ToString() + ""&gt;"";
        }

        return s;
    }
</code></pre>

<p>Then in the test I call the code just like I do during normal execution:</p>

<pre><code>[Test]
    public async Task GetStringFromConsulTest()
    {
        ConsulConfiguration cc = new ConsulConfiguration();

        string a = cc.GetStringFromConsul("""").GetAwaiter().GetResult();
        Assert.AreEqual(a, """");
    }
</code></pre>

<p>However I get an exception like so instead of any sort of string:</p>

<pre><code>Message:   Expected string length 514 but was 0. Strings differ at index 0.
  Expected: ""&lt;Request Exception: System.Threading.Tasks.TaskCanceledExcept...""
  But was:  &lt;string.Empty&gt;
</code></pre>

<p>I've looked around and found a few tutorials on this and tried it but to no avail. If anyone can point me in the right direction I would appreciate it, I'm pretty new to C# unit testing.</p>
",https://stackoverflow.com/questions/49338398/async-unit-testing-with-nunit-and-c,"['c#', 'asynchronous', 'nunit']",3900,TRUE,1,3
How to (should I) mock DocumentClient for DocumentDb unit testing?,"<p>From the new CosmosDb emulator I got sort of a repository to perform basic documentdb operations, this repository gets injected to other classes. I wanted to unit test a basic query. </p>

<pre><code>public class DocumentDBRepository&lt;T&gt; where T : class
{
 //Details ommited...

    public IQueryable&lt;T&gt; GetQueryable()
    {
        return _client.CreateDocumentQuery&lt;T&gt;(
            UriFactory.CreateDocumentCollectionUri(_databaseId, _collectionId),
            new FeedOptions { MaxItemCount = -1, EnableCrossPartitionQuery = true });
    }

    public async Task&lt;IEnumerable&lt;T&gt;&gt; ExecuteQueryAsync(IQueryable&lt;T&gt; query)
    {
        IDocumentQuery&lt;T&gt; documentQuery = query.AsDocumentQuery();
        List&lt;T&gt; results = new List&lt;T&gt;();
        while (documentQuery.HasMoreResults)
        {
            results.AddRange(await documentQuery.ExecuteNextAsync&lt;T&gt;());
        }

        return results;
    }


}
</code></pre>

<p>This repository needs a document client to work, which also gets injected on the constructor. </p>

<pre><code>public DocumentDBRepository(string databaseId, IDocumentClient client)
{
    _client = client;
    _databaseId = databaseId;
    _collectionId = GetCollectionName();
}
</code></pre>

<p>My initial approach was to use the CosmosDb emulator, but that required the emulator to run which I don't like and makes the tests slower. </p>

<p>My second approach was to try and use a mock of the document client. </p>

<pre><code>var data = new List&lt;MyDocumentClass&gt;
{
    new MyDocumentClass{ Description= ""BBB"" },
    new MyDocumentClass{ Description= ""ZZZ"" },

}
.AsQueryable()
.OrderBy(q =&gt; q.Description);
var client = new Mock&lt;IDocumentClient&gt;();
client.As&lt;IDocumentClient&gt;()
    .Setup(foo =&gt; foo.CreateDocumentQuery&lt;MyDocumentClass&gt;(It.IsAny&lt;Uri&gt;(), It.IsAny&lt;FeedOptions&gt;()))
    .Returns(data);

DocumentDBRepository&lt;MyDocumentClass&gt; repo= new DocumentDBRepository&lt;MyDocumentClass&gt;(cosmosDatabase, client.Object);
</code></pre>

<p>The code that uses this repository works like this:</p>

<pre><code>var query = _documentsRepository.GetQueryable()
                .Where(d =&gt; d.Description = description)
                .OrderByDescending(d =&gt; d.description)
                .Take(100);
//Execute query async fails. 
var result = await _documentsRepository.ExecuteQueryAsync(query);
</code></pre>

<p>It fails because the repository tries to convert the <code>IQueryable</code> to a <code>IDocumentQuery</code> object, which is very specific to DocumentDb api (See method <code>ExecuteQueryAsync</code> above). Later on, it executes <code>HasMoreResults</code> method on it. So the problem is, even if I mock <code>.asDocumentQuery()</code> to return my object, I don't know how to provide a result for <code>HasMoreResults</code> and <code>ExecuteNextAsync</code> so that it makes sense for my unit tests. </p>

<p>My third option would be to straight mock my repository instead of the DocumentClient object. Would be, I think, simpler, but I wouldn't be testing much of the DocumentDb api. </p>
",https://stackoverflow.com/questions/48349659/how-to-should-i-mock-documentclient-for-documentdb-unit-testing,"['c#', 'unit-testing', 'moq', 'azure-cosmosdb']",14721,TRUE,22,2
Why &quot;getSharedPreferences&quot; return null in unit testing?,"<p>My classes is written in Kotlin and here is my SharedPreferenceHandler</p>

<pre><code>   class SharedPreferenceHandler(sharedPrefs: SharedPreferences) {

        companion object {
            var mInstance: SharedPreferenceHandler = SharedPreferenceHandler(getPrefs())

            private fun getPrefs(): SharedPreferences {
                return Application.mInstance.getSharedPreferences(
                        ""myApp"", Context.MODE_PRIVATE)
            }

            fun getInstance(): SharedPreferenceHandler {
                return mInstance
            }
        }

        private var sharedPreferences = sharedPrefs

        var accessToken: String?
            get() = sharedPreferences.getString(SharedPreference.ACCESS_TOKEN.name, null)
            set(token) = sharedPreferences.edit().putString(SharedPreference.ACCESS_TOKEN.name, token).apply()
}
</code></pre>

<p>Here is method called in presenter:</p>

<pre><code> override fun reload(vm: ViewModel) {
        super.updateViewModel(vm) {
           //some stuffs
        }
    }
</code></pre>

<p>Here is my test method:</p>

<pre><code>@Test
public void reload() {
    when(SharedPreferenceHandler.Companion.getMInstance().getAccessToken()).thenReturn(""234234234234234"");

    presenter.reload(viewModel);
}
</code></pre>

<p>In handler from <strong>super.updateViewModel(vm)</strong> I call ""SharedPreferenceHandler.mInstance.accessToken!!)""</p>

<p>That is what is thrown:</p>

<blockquote>
  <p>Caused by: java.lang.IllegalStateException:
  Application.mInstanc…m"", Context.MODE_PRIVATE) must not be null
    at
  com.zuum.zuumapp.preferences.SharedPreferenceHandler$Companion.getPrefs(SharedPreferenceHandler.kt:18)
    at
  com.zuum.zuumapp.preferences.SharedPreferenceHandler$Companion.access$getPrefs(SharedPreferenceHandler.kt:14)
    at
  com.zuum.zuumapp.preferences.SharedPreferenceHandler.(SharedPreferenceHandler.kt:15)</p>
</blockquote>

<p>I wanna to get accessToken by calling "" SharedPreferenceHandler.mInstance.accessToken!!"" in my test class.</p>

<p>Is possible to get that in my test method?</p>
",https://stackoverflow.com/questions/50584177/why-getsharedpreferences-return-null-in-unit-testing,"['unit-testing', 'kotlin', 'sharedpreferences']",1637,TRUE,1,2
Unit testing the instance of Sequelize Model,"<p>I have the following code:</p>

<pre><code>async save(id: string) {
 const person = await PersonModel.findOne({
  where: { id: id },
 });

 if (!person) {
  await PersonModel.create({
    id: '2345',
    name: 'John Doe',
    age: 25
  });
  return;
 }

 await person.increment({ age: 15 });
}
</code></pre>

<p>Now, I wanted to test person.increment() in which the age will be added with 15. I have the following code to escape the condition that will create a new record for the model.</p>

<pre><code>const findOneFake = sinon.spy(() =&gt; {
  return {}; //returns empty object or true
});

const proxy = (proxyquire('./path/to/file.ts', {
  './path/to/PersonModel.ts': {
    default: {
      findOne: findOneFake
    }
  }
})).default;

beforeEach(async () =&gt; {
  await save();
});

it('should increment age with 15');
</code></pre>

<p>How am I going to do that? What do I do to test it? I can use sinon.fake() to PersonModel.create or PersonModel.update but I am troubled testing the instance of a Sequelize Model.</p>
",https://stackoverflow.com/questions/53078150/unit-testing-the-instance-of-sequelize-model,"['unit-testing', 'mocha.js', 'sinon', 'chai', 'proxyquire']",478,FALSE,1,0
Unit testing PODO constructor exceptions in dart,"<p>This is my constructor:</p>

<pre class=""lang-dart prettyprint-override""><code>Merchant(
  this._firstName,
  this._lastName,
  this._company,
  this._buildingNumber,
  this._location,
  this._city,
  String pin,
  String phone,
  String email,
  this._image) {
  _validatePin(pin) ? _pin = pin : throw pinFormatException;
  _validatePhone(phone) ? _phone = phone : throw phoneFormatException;
  _validateEmail(email) ? _email = email : throw emailFormatException;
}
</code></pre>

<p>I want to unit test this constructor. I want to test that the correct exception is thrown when the data validation fails.
I want the PIN to be a 6-digit number. So, this is the test I wrote for it:</p>

<pre><code>test('pin must be a 6-digit number', () {
  expect(() {
    new Merchant(FIRST_NAME, LAST_NAME, COMPANY, BUILDING_NUMBER, LOCATION,
        CITY, 1234567/*PIN*/, WHATSAPP_NUMBER, EMAIL, IMAGE_RESOURCE);
  }, throwsA(Exception));
});
</code></pre>

<p>I want to know how to properly use throwsA() function to ensure that the right exception with the right exception message was thrown.</p>

<p>This is the error I get from running the test above:</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>Expected: throws ?:&lt;Exception&gt;
  Actual: &lt;Closure: () =&gt; dynamic&gt;
   Which: threw ?:&lt;Exception: pin codes are 6-digit numbers&gt;
          stack package:mnshi/model/merchant.dart 33:38                                              new Merchant
                /home/raveesh/MyCode/code/production/mnshi/test/cli_tests/merchant_tests.dart 27:21  main.&lt;fn&gt;.&lt;fn&gt;.&lt;fn&gt;
                package:test                                                                         expect
                /home/raveesh/MyCode/code/production/mnshi/test/cli_tests/merchant_tests.dart 27:7   main.&lt;fn&gt;.&lt;fn&gt;

package:test                             expect
test/cli_tests/merchant_tests.dart 27:7  main.&lt;fn&gt;.&lt;fn&gt;</code></pre>
</div>
</div>
</p>

<p>Please Help!</p>
",https://stackoverflow.com/questions/49185319/unit-testing-podo-constructor-exceptions-in-dart,['dart'],286,TRUE,1,1
Unit Testing a Request in Asp.Net Core 2.0,"<p>I'm attempting to write some unit tests for this method, but I can't figure out how to setup the <code>Request</code>. Specifically, I need to set <code>Query</code> and the header attribute <code>Referer</code>. </p>

<pre><code>public IActionResult Index()
{
    if (User.Identity.IsAuthenticated)
    {
        return RedirectToAction(""Index"", ""Home"");
    }

    var query = Request.Query;
    StringValues returnUrlValue;
    if (query.TryGetValue(""returnUrl"", out returnUrlValue))
    {
        var returnUrl = returnUrlValue.ToString();
        var referer = Request.Headers[""Referer""].ToString();
        if (string.IsNullOrEmpty(returnUrl) &amp;&amp; !string.IsNullOrEmpty(referer))
        {
            returnUrl = WebUtility.UrlEncode(referer);
        }

        if (Url.IsLocalUrl(returnUrl) &amp;&amp; !string.IsNullOrEmpty(returnUrl))
        {
            ViewBag.ReturnUrl = returnUrl;
        }
    }

    return View();
}
</code></pre>

<p>I understand that a <code>request</code> goes through the middleware before ever getting to the controller, so it can't be passed into the controller as a parameter. But, the <code>Request</code> object on the controller is <code>readonly</code> and cannot be assigned. Therefore something like the following won't work.</p>

<pre><code>var controller = new LoginController();
controller.Request = new DefaultHttpRequest(new DefaultHttpContext())
{
    QueryString = new QueryString(""?returnUrl"")
};
</code></pre>
",https://stackoverflow.com/questions/48370077/unit-testing-a-request-in-asp-net-core-2-0,"['c#', 'unit-testing', 'asp.net-core-2.0', 'xunit']",966,FALSE,8,0
Boost Unit testing- where to locate makefiles,"<p>I would like to use Boost for unit testing. Writing the unit tests is not a problem. However, I am a little unsure how to structure the makefiles relating to each unit test. I am not an expert on makefiles so I would like to explain how my code base is, what I would like to do and then ask for the best solution.</p>

<p>I have a code base which is a mixture of Python, C++ utility functions in headers and one C++ application/library, but it uses the classes/functions located in other folders (which are not sub folders). So unsurprisingly I only have one makefile for my application. </p>

<p>I would like to add unit tests in each of the various folders my application uses. </p>

<p>I would also like to be able to run all the unit tests (across the multiple folders) by running one executable.</p>

<p>Do I write a boost unit test source file in each folder and add a corresponding makefile, one per each folder I wish to unit test? How do I structure this so that I can run all the unit tests from one executable?</p>

<p>Also, do I need to link my unit test makefiles to my application object file, or just gcc -I flag the headers it requires?</p>

<p>(I am using regular GNU Make)</p>
",https://stackoverflow.com/questions/50426155/boost-unit-testing-where-to-locate-makefiles,"['c++', 'boost', 'makefile', 'build', 'compilation']",154,FALSE,1,0
Unit-testing a probability distribution with conditionals,"<p>I have a function <code>choose(elems) -&gt; elem</code> that calls <code>rand()</code> which makes it non-deterministic.</p>

<p>To be able to better test this, I figured that I could split this function in two,</p>

<pre><code>generate_choices(elems, ...) -&gt; distribution
choose(distribution) -&gt; elem
</code></pre>

<p>where <code>choose()</code> is a thin wrapper around <code>rand()</code> and <code>generate_choices()</code> generates a distribution from which to draw an element. I could then deterministically test that this probability distribution is as expected.</p>

<p>The distribution is uniform <em>but</em> with two conditionals:</p>

<ol>
<li>If there are not enough <code>elems</code>, add a random <em>fallback</em> element uniformly.</li>
<li>If there are still not enough <code>elems</code>, add a random <em>default</em> element uniformly.</li>
</ol>

<p>Some examples:</p>

<pre><code>generate_choices([a, b, c, d], [], []) -&gt; [a, b, c, d]
generate_choices([a, b, c], [fallback1], []) -&gt; [a, b, c, fallback1]
generate_choices([a, b, c], [fb1, fb2], []) -&gt; [a, b, c, (fb1 | fb2)]
generate_choices([a, b], [fb1, fb2], [default1]) -&gt; [a, b, (fb1 | fb2), default1]
generate_choices([a, b], [fb1, fb2], [d1, d2]) -&gt; [a, b, (fb1 | fb2), (d1 | d2) ]
generate_choices([a], [fb1, fb2], [d1, d2]) -&gt; [a, (fb1|fb2), (d1|d2) ]
</code></pre>

<p>My question is then: How should I model <code>distribution</code>?</p>

<ul>
<li>If I choose a simple list and call <code>rand()</code> from within <code>generate_choices()</code> to fill the <em>fallback</em> and <em>default</em>, then I can only test some deterministic parts of <code>generate_choices()</code>.</li>
<li>If I choose three lists, <code>(elems, fallback, default)</code>, then <code>generate_choices()</code> is fully deterministic, but then <code>choice()</code> becomes less trivial and must be tested more thoroughly anyways.</li>
</ul>
",https://stackoverflow.com/questions/50003201/unit-testing-a-probability-distribution-with-conditionals,"['unit-testing', 'testing', 'probability', 'probability-distribution']",154,TRUE,1,1
Configuring unit testing within an Ionic3 application,"<p>I'm implementing unit tests within an ionic3 project based on the following sample project: <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>It works fine but I have some issues:</p>

<ul>
<li><p>I can see compilation errors (for jasmine) whereas these ones don't prevent from running tests</p>

<pre><code>karma start ./test-config/karma.conf.js
webpack: Compiled successfully.
webpack: Compiling...

17 03 2018 15:53:18.403:WARN [karma]: No captured browser, open http://localhost:9876/

ERROR in ./src/pages/test/test.spec.ts
[tsl] ERROR in /home/app-path/src/pages/test/test.spec.ts(11,1)
TS2304: Cannot find name 'describe'.

ERROR in ./src/pages/test/test.spec.ts
[tsl] ERROR in /home/app-path/src/pages/test/test.spec.ts(17,3)
TS2304: Cannot find name 'beforeEach'.

ERROR in ./src/pages/test/test.spec.ts
[tsl] ERROR in /home/app-path/src/pages/test/test.spec.ts(40,39)
TS2304: Cannot find name 'expect'.

ERROR in ./src/pages/test/test.spec.ts
[tsl] ERROR in /home/app-path/src/pages/test/test.spec.ts(42,3)
TS2304: Cannot find name 'it'.

...

webpack: Failed to compile.
17 03 2018 15:53:18.422:INFO [karma]: Karma v1.7.1 server started at http://0.0.0.0:9876/
17 03 2018 15:53:18.422:INFO [launcher]: Launching browser Chrome with unlimited concurrency
17 03 2018 15:53:18.748:INFO [launcher]: Starting browser Chrome
17 03 2018 15:53:20.153:INFO [Chrome 57.0.2987 (Linux 0.0.0)]: Connected on socket py7H3olXgBzYBE2DAAAA with id 24040166
Chrome 57.0.2987 (Linux 0.0.0): Executed 8 of 8 SUCCESS (2.716 secs / 0 secs)
</code></pre></li>
<li><p>I can't display results in the browser launched by karma even if I have the <code>kjhtml</code> reporter configured. See <a href=""https://github.com/ionic-team/ionic-unit-testing-example/blob/master/test-config/karma.conf.js#L52"" rel=""nofollow noreferrer"">https://github.com/ionic-team/ionic-unit-testing-example/blob/master/test-config/karma.conf.js#L52</a>. Note I added the <code>progress</code> reporter and it works fine:</p>

<pre><code>reporters: ['progress', 'kjhtml'],
</code></pre></li>
</ul>

<p>Thanks for your help!</p>
",https://stackoverflow.com/questions/49338304/configuring-unit-testing-within-an-ionic3-application,"['ionic3', 'karma-runner', 'karma-jasmine', 'karma-webpack']",1231,FALSE,1,0
"Error : Yam is Undefined, while unit testing","<p>I was unit testing an application and I am stuck at one point. I am posting the problem below with code snippet.</p>

<p>This code is used to popup yammer window.</p>

<p>The yam variable is declared outside the component like this</p>

<pre><code>declare var yam: any;

@Component({
  selector: 'cs-artifact-related',
  templateUrl: './artifact-related.component.html',
  styleUrls: ['./artifact-related.component.css']
})
</code></pre>

<p>and it is used in the following method</p>

<pre><code>public yammerWindowPopup(ownername, prjName): void {
    yam.platform.yammerShareOpenPopup({
      customButton: true,
      defaultMessage: this.getYammerWindowPopupMessage(ownername, prjName),
      pageUrl: this.copyArtifactUrl.split('?')[0]
    });
  }
</code></pre>

<p>I have written following code to unit test this</p>

<pre><code>it('should call yammerWindowPopup method', () =&gt; {
    component.yammerWindowPopup(""Owner1"", ""Test Project"");
});
</code></pre>

<p>and I am getting this error when I run ng test</p>

<pre><code>yam is not defined
</code></pre>

<p>The constraint is I cannot declare yam inside since it is a pre written code.</p>

<p>So I have two questions</p>

<ol>
<li>How to access variable which is defined outside component in spec file?</li>
<li>How to resolve the above error?
Please help!</li>
</ol>
",https://stackoverflow.com/questions/51245593/error-yam-is-undefined-while-unit-testing,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",220,FALSE,1,1
python unit testing mocking Popen and Popen.communicate,"<p>I'm trying to write a python unittest that does a subprocess call, so I'd like to mock that call.</p>

<p>I've already gone through these SO questions (to no avail):</p>

<ul>
<li><a href=""https://stackoverflow.com/questions/25692440/mocking-a-subprocess-call-in-python"">Mocking a subprocess call in Python</a></li>
<li><a href=""https://stackoverflow.com/questions/50775969/mocking-subprocess-popen"">mocking subprocess.Popen</a></li>
<li><a href=""https://stackoverflow.com/questions/31050888/mocking-subprocess-popen-dependant-on-import-style"">mocking subprocess.Popen dependant on import style</a></li>
<li><a href=""https://stackoverflow.com/questions/15763394/mocking-two-functions-with-patch-for-a-unit-test"">Mocking two functions with patch for a unit test</a></li>
</ul>

<p><strong>benchmark.py</strong></p>

<pre><code>from subprocess import Popen, PIPE, STDOUT

def some_func():

  with Popen(some_list, stdout=PIPE, stderr=STDOUT) as process:

    stdout, stderr = process.communicate(timeout=timeout)
</code></pre>

<p><strong>test.py</strong></p>

<pre><code>import mock

@mock.patch('benchmark.Popen.communicate')
@mock.patch('benchmark.Popen')
def test_some_func(self, mock_popen, mock_comm):

  mock_popen.return_value = 0
  mock_comm.return_value = ('output', 'error')

  foo = benchmark.some_func()
</code></pre>

<p>When running the unittest I get:</p>

<pre><code>    stdout, stderr  = process.communicate(timeout=timeout)
ValueError: not enough values to unpack (expected 2, got 0)
</code></pre>

<p>It looks like I'm not mocking the return value of <code>communicate</code> correctly;  what am I doing wrong?</p>

<h2>solution</h2>

<p>I took the comments and suggested answers to solve things like this:</p>

<p><strong>test.py</strong></p>

<pre><code>import mock

@mock.patch('benchmark.Popen')
def test_some_func(self, mock_popen):

  process = mock_popen.return_value.__enter__.return_value
  process.returncode = 0
  process.communicate.return_value = (b'some output', b'some error')

  foo = benchmark.some_func()
</code></pre>
",https://stackoverflow.com/questions/53784239/python-unit-testing-mocking-popen-and-popen-communicate,"['python', 'unit-testing', 'mocking']",3069,TRUE,1,1
Karma Unit Testing with Angular | Event Listeners,"<p>Consider this part of code :</p>

<pre><code>      @ViewChild('amountSlider') amountSlider: any;
      @ViewChild('amountInput') amountInput: any;

      ** Some Code **

      setvariables()
        {
        const updateStep =  this.renderer.listen(this.amountInput.input.nativeElement, 'keydown', (evt) =&gt; {
          this.amountSlider.step = 1;
          const keyName = evt.key;
          if (keyName == 'Tab') {
            this.amountSlider.step = 100;
          }
        });
         const resetStep = this.renderer.listen(this.amountSlider.slider.nativeElement, 'mouseover', (evt) =&gt; {
          this.amountSlider.step = 100;
        });
  }
</code></pre>

<p>Following part of (Event Listener) my code bothers me in Unit Testing 
I am not calling keydown or mouseover directly from my DOM.
Can someone help me to write Unit Testing to cover this ???</p>

<p>test.spec.ts</p>

<pre><code>describe('setVariables', () =&gt; {
    it('makes expected calls', () =&gt; {
        const renderer2Stub: Renderer2 = fixture.debugElement.injector.get(Renderer2);
        spyOn(renderer2Stub, 'listen');
        comp.setVariables();
        expect(renderer2Stub.listen).toHaveBeenCalled();
    }) 
 });
</code></pre>
",https://stackoverflow.com/questions/51645337/karma-unit-testing-with-angular-event-listeners,"['angular', 'typescript', 'unit-testing', 'karma-jasmine', 'angular-services']",1766,TRUE,1,1
Unit-testing React Components using Context Consumers,"<p>I used to have component that looked like this:</p>

<pre><code>class Foo extends React.Component {
    render() {
        return (
            &lt;div className=""Foo""&gt;
                &lt;div id=""user""&gt;Bar&lt;/div&gt;
                &lt;SomeOtherComponent /&gt;
            &lt;/div&gt;
        )
    }
}
</code></pre>

<p>and this test:</p>

<pre><code>it('renders a help button', () =&gt; {
  expect(shallow(&lt;Foo /&gt;).find('#user').length).toEqual(1);
});
</code></pre>

<p>But now I have added a context consumer to this object:</p>

<pre><code>class Foo extends React.Component {
    render() {
        return (
            &lt;UserContext.Consumer&gt;
                {({user}) =&gt; (
                    &lt;div className=""Foo""&gt;
                        &lt;div id=""user""&gt;{user}&lt;/div&gt;
                        &lt;SomeOtherComponent /&gt;
                    &lt;/div&gt;
                )}
            &lt;/UserContext.Consumer&gt;
        )
    }
}
</code></pre>

<p>How can I test the following conditions?</p>

<ul>
<li>The amount of ""#user"" is 1</li>
<li>The user displayed is the one provided</li>
</ul>
",https://stackoverflow.com/questions/52426494/unit-testing-react-components-using-context-consumers,"['reactjs', 'unit-testing', 'jestjs', 'enzyme', 'react-context']",2408,TRUE,1,1
Unit Testing Controller that uses GetUserASync (User),"<p>I am trying to Unit Test that a controller action returns the correct view. I am using .NET Core, Moq, and NUnit.</p>

<p>I want test the default <code>ManageController</code>,</p>

<p>The Constructor is below,</p>

<pre><code>public ManageController(
  UserManager&lt;ApplicationUser&gt; userManager,
  SignInManager&lt;ApplicationUser&gt; signInManager,
  IEmailSender emailSender,
  ILogger&lt;ManageController&gt; logger,
  UrlEncoder urlEncoder)
{
    _userManager = userManager;
    _signInManager = signInManager;
    _emailSender = emailSender;
    _logger = logger;
    _urlEncoder = urlEncoder;
}
</code></pre>

<p>And am trying to Unit Test the following <code>Index</code> Action, and Assert that it returns the correct ViewModel when successful. (And will add other paths that return different ViewModels in future)</p>

<pre><code>[HttpGet]
public async Task&lt;IActionResult&gt; Index()
{
    var user = await _userManager.GetUserAsync(User);
    if (user == null)
    {
        throw new ApplicationException($""Unable to load user with ID '{_userManager.GetUserId(User)}'."");
    }

    var model = new IndexViewModel
    {
        Username = user.UserName,
        Email = user.Email,
        PhoneNumber = user.PhoneNumber,
        IsEmailConfirmed = user.EmailConfirmed,
        StatusMessage = StatusMessage
    };

    return View(model);
}
</code></pre>

<p>After many attempts, my closest solution is as follows,</p>

<p>I have mocked, <code>UserManager</code>, and Setup the <code>GetUserASync</code> method with a <code>ClaimsPrincipal</code> with the Id ""1"". I have also set the <code>HttpContext</code> to use the same <code>ClaimsPrincipal</code> and passed that the the controller.</p>

<p>As the Action is async, I was forced to make the test method async. Currently the test fails due to the async <code>Task</code> that is returned being null. I can't see if the rest of the test passes as I can't get past this error.</p>

<pre><code>[Test]
public async Task Index_UserExists_ReturnsViewAsync()
{
     var mockUserStore = new Mock&lt;IUserStore&lt;ApplicationUser&gt;&gt;();
     var mockUserManager = new Mock&lt;UserManager&lt;ApplicationUser&gt;&gt;(mockUserStore.Object, null, null, null, null, null, null, null, null);

    var user = new ClaimsPrincipal(new ClaimsIdentity(new Claim[]
    {
        new Claim(ClaimTypes.NameIdentifier, ""1""),
    }));

    mockUserManager.Setup(x =&gt; x.GetUserAsync(user));

    var controller = new ManageController(mockUserManager.Object, null, null, null, null)
    {
        ControllerContext = new ControllerContext()
        {
            HttpContext = new DefaultHttpContext() { User = user }
        }
    };

    //Act
    var result = await controller.Index();

    //Assert
    Assert.IsInstanceOf&lt;ViewResult&gt;(result);
}
</code></pre>
",https://stackoverflow.com/questions/51866713/unit-testing-controller-that-uses-getuserasync-user,"['c#', 'unit-testing', 'asp.net-core', 'nunit', 'moq']",612,TRUE,1,1
Best approach for unit-testing scoped viewmodels,"<p>When dealing with coroutines inside a viewModel is best to have said viewModel implement <code>CoroutineScope</code> so all coroutines are cancelled when the viewModel is cleared. Usually I see <code>coroutineContext</code> defined as <code>Dispatchers.Main + _job</code> so that coroutines are executed in the main UI thread by default. Usually this is done on a open class so that all your viewModels can extend it and get the scope without boilerplate code.</p>

<p>The issue arises when trying to unit test said viewModels as <code>Dispatchers.Main</code> is not available and trying to use it throws an exception. I am tryin to find a good solution that doesn't involve external libraries or too much boiler plate on the child viewModels.</p>

<p>My current solution is to add the maincontext as a contructor paramenter with the <code>Dispatchers.Main</code> as the default value. Then in the unit test, before testing the viewModel I set it to <code>Dispatchers.Default</code>. I don't quiet like this solution as it exposes the coroutineContext implementation details for everyone to see and change: </p>

<pre><code>open class ScopedViewModel(var maincontext = Dispatchers.Main) : ViewModel(), CoroutineScope {
    private val _job = Job()
    override val coroutineContext: CoroutineContext
        get() = maincontext + _job

    override fun onCleared() {
        super.onCleared()
        _job.cancel()
    }
}
class MyViewModel : ScopedViewModel() {}
</code></pre>

<p>In the tests:</p>

<pre><code>fun setup(){
    viewModel = MyViewModel()
    viewModel.maincontext = Dispacther.Default
}
</code></pre>
",https://stackoverflow.com/questions/53479143/best-approach-for-unit-testing-scoped-viewmodels,"['android', 'unit-testing', 'kotlin', 'kotlinx.coroutines', 'android-viewmodel']",923,TRUE,1,1
Unit testing method that interacts with Build.TAGS,"<p>Is it possible through the use of Mockito or Reflection to unit test a method that interacts with <code>android.os.Build.TAGS</code>? </p>

<p>I'd prefer to be able to dictate what value is returned by <code>Build.TAGS</code>.</p>
",https://stackoverflow.com/questions/51396444/unit-testing-method-that-interacts-with-build-tags,"['android', 'junit']",21,FALSE,1,0
Android Architecture sample unit testing live data,"<pre><code>@Test
fun sendResultToUI() {

    val foo = MutableLiveData&lt;Resource&lt;User&gt;&gt;()
    val bar = MutableLiveData&lt;Resource&lt;User&gt;&gt;()
    `when`(userRepository.loadUser(""foo"")).thenReturn(foo)
    `when`(userRepository.loadUser(""bar"")).thenReturn(bar)
    val observer = mock&lt;Observer&lt;Resource&lt;User&gt;&gt;&gt;()
    userViewModel.user.observeForever(observer) //Create foo and bar, observe user live data

    userViewModel.setLogin(""foo"")
    verify(observer, never()).onChanged(any()) //Make sure that setting login to foo did not touch vm.user?

    /*val fooUser = TestUtil.createUser(""foo"")
    val fooValue = Resource.success(fooUser)
    foo.value = fooValue
    verify(observer).onChanged(fooValue)
    reset(observer)

    val barUser = TestUtil.createUser(""bar"")
    val barValue = Resource.success(barUser)
    bar.value = barValue
    userViewModel.setLogin(""bar"")
    verify(observer).onChanged(barValue)*/
}
</code></pre>

<p>Can anyone please explain wtf this line: <code>verify(observer, never()).onChanged(any())</code> is doing in Google's <a href=""https://github.com/googlesamples/android-architecture-components/tree/master/GithubBrowserSample"" rel=""nofollow noreferrer"">GithubBrowser</a> sample? I just don't understand it, calling <code>setLogin()</code> <em>fires</em> the observer so how the hell can we verify that <code>onChanged()</code> was never called when we specifically triggered it on the previous line!?</p>
",https://stackoverflow.com/questions/52173040/android-architecture-sample-unit-testing-live-data,"['android', 'kotlin', 'android-testing', 'android-architecture-components', 'android-livedata']",1505,TRUE,1,1
Jasmine Unit testing HttpInterceptor validating method argument,"<p>I have an Angular (6) HttpInterceptor like with this intercept method:</p>

<pre><code>intercept(req: HttpRequest&lt;any&gt;,next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {

    if (this.translationService.currentLang) {
      req = req.clone({
        setHeaders: {
          'Accept-Language': this.translationService.currentLang
        }
      });
    }

    return next.handle(req);
  }
</code></pre>

<p>How can I get this to unit test with jasmine and check that the returned request contains the new header? I know I can get the parameter with </p>

<pre><code>let next = jasmine.createSpyObj('httpHandler', ['handle']);
next.handle.calls.mostRecent();
</code></pre>

<p>But how can I validate that the header is set?</p>
",https://stackoverflow.com/questions/52663652/jasmine-unit-testing-httpinterceptor-validating-method-argument,"['angular', 'typescript', 'unit-testing', 'jasmine']",3067,TRUE,1,1
Angular 6 Unit testing : Empty test suite,"<p>Under my Angular 6 app i'm using karma for unit testing , this is my config :</p>

<pre><code>// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma')
    ],
    client:{
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    mime: {
      'text/x-typescript': ['ts','tsx']
    },
    coverageIstanbulReporter: {
      dir: require('path').join(__dirname, 'coverage'),
      reports: [ 'html', 'lcovonly' ],
      fixWebpackSourcePaths: true
    },

    reporters: config.angularCli &amp;&amp; config.angularCli.codeCoverage
      ? ['progress', 'coverage-istanbul']
      : ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    browserDisconnectTimeout: 10000,
    browserDisconnectTolerance: 3,
    browserNoActivityTimeout: 60000,
    flags: [
      '--disable-web-security',
      '--disable-gpu',
      '--no-sandbox'
    ],
    singleRun: true,
    concurrency: Infinity
  });
};
</code></pre>

<p><strong>and here is my test file :</strong> </p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { AdvancedSearchCrmdFormComponent } from './advanced-search-crmd-form.component';
import {ActivatedRoute} from '@angular/router';
import {AdvancedSearchCrmdActionsService} from '../../advanced-search-crmd-services/advanced-search-crmd-actions.service';

describe('AdvancedSearchCrmdFormComponent', () =&gt; {
  let comp: AdvancedSearchCrmdFormComponent;
  let fixture: ComponentFixture&lt;AdvancedSearchCrmdFormComponent&gt;;

  // Test Suite of Component compiling
  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ AdvancedSearchCrmdFormComponent ],
      providers: [ActivatedRoute , AdvancedSearchCrmdActionsService]
    })
    .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(AdvancedSearchCrmdFormComponent);
    comp = fixture.componentInstance;
    // fixture.detectChanges();
  });

  // Test case of component compilation
  it('AdvancedSearchCrmdFormComponent should be defined', () =&gt; {
    expect(comp).toBeDefined();
  });
});
</code></pre>

<p>And as you can see i ve one test case to run , but i obtain this: </p>

<pre><code>/usr/local/bin/node /home/khalidvm/Desktop/WebStorm-181.5281.31/plugins/js-karma/js_reporter/karma-intellij/lib/intellijRunner.js --karmaPackageDir=/media/khalidvm/SecondDisk/SOCLE_RCD/Front/Frontend_v3_crmd/node_modules/@angular/cli --serverPort=9876 --protocol=http: --urlRoot=/ ""--testName=AdvancedSearchCrmdFormComponent ""
Empty test suite.

Process finished with exit code 0
</code></pre>

<p>Suggestions ? </p>
",https://stackoverflow.com/questions/52778034/angular-6-unit-testing-empty-test-suite,"['javascript', 'angular', 'karma-jasmine', 'karma-runner', 'karma-webpack']",1416,FALSE,1,0
.NET Core 2.0 User Secrets and Unit Testing,"<p>I'm currently working on a .net core solution (multiple projects) that uses <a href=""https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets?tabs=visual-studio-code"" rel=""noreferrer"">Microsoft's app secrets management</a>. I can pull secrets back in my runtime project (e.g. Console app), but when it comes to leveraging user secrets for integration tests in a separate project (e.g. Model.Test project), what's the right approach? </p>

<p>I can think of a few options:</p>

<ol>
<li><p>Give each project the same <code>UserSecretsId</code>: This seems like it'd made sense for test projects that may leverage the same secrets that the runtime project uses.</p></li>
<li><p>Let each project have unique <code>UserSecretsId</code>: This would require that the secrets be manually kept in sync on the development machine</p></li>
</ol>

<p>It seems like even between .net core 1.0 and 2.0 user secrets has changed somewhat and I don't have a lot of familiarity with this system in general. Thanks!</p>
",https://stackoverflow.com/questions/48779631/net-core-2-0-user-secrets-and-unit-testing,"['unit-testing', 'security', '.net-core']",2765,TRUE,7,2
Using Mocking for unit testing in python,"<p>I have two functions in a <code>python</code> file. I want to do some unit tests for these functions using <code>Mock</code>.</p>

<pre><code>def col_rename(col_name):
    reps = ((' ', '_&amp;'), ('(', '*_'), (')', '_*'), ('{', '#_'), ('}', '_#'))
    new_cols = reduce(lambda a, kv: a.replace(*kv), reps, col_name)
    return new_cols

def rename_characters(df):
    df_cols = df.schema.names
    for x in df_cols:
        df = df.withColumnRenamed(x, col_rename(x))
    return df
</code></pre>

<p>In the above function <code>withColumnRenamed</code> is a function in <code>pyspark</code> that will return a column after is renames the column name. 
<code>df</code> is a <code>pyspark</code> data frame. </p>

<p>I am able to do <code>unit testing</code> to the <code>col_rename</code> function. </p>

<p>I am able to do <code>unit testing</code> to the <code>rename_characters</code> function by creating data frames manually in pyspark.</p>

<p>Now I want to do the <code>unit testing</code> using <code>Mock</code> in <code>python</code>.</p>

<p>I have tried something like this below. I am not sure if this is correct or What I am doing is completely wrong</p>

<pre><code>import unittest
from mock import patch

class Test(unittest.TestCase):
    @patch('mymodule.rename_characters')
    def test_func(self, rename_characters_mock):
        rename_characters_mock.return_value = 'mocked values'
        self.assertEqual(return_value, 'mocked_values'))
</code></pre>

<p>How can I do <code>Mocking</code> for the <code>unit testing</code> as in the above scenario</p>
",https://stackoverflow.com/questions/49290594/using-mocking-for-unit-testing-in-python,"['python', 'unit-testing', 'mocking']",343,TRUE,1,1
Error while unit testing spring integration dsl,"<p>I am seeing following error while running the unit testing my spring integration code. And also i was not sure how to mock my service and other dependencies while using mockIntegrationContext.</p>

<pre><code>org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'orderInputEndPoint' available

    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:686)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1210)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:204)
</code></pre>

<p>Main program code</p>

<pre><code>@EnableIntegration
public class OrderPersistFlow {

    @Autowired
    private ActiveMQConnectionFactory activeMQConnectionFactory;

    @Autowired
    private OrderTransformer orderTransformer;

    @Autowired
    private OrderService orderService;


    @Bean
    public IntegrationFlow persistFlow() {
        return IntegrationFlows
                .from(Jms.messageDrivenChannelAdapter(activeMQConnectionFactory)
                        .id(""orderInputEndPoint"")
                        .destination(""order.queue"")
                        .jmsMessageConverter(new MarshallingMessageConverter(jaxbMarshaller())))
                .filter(OrderVO.class, p -&gt; p.getOrderStatus().equals(""OPEN"")
                .transform(orderTransformer)
                .handle(orderService, ""save"")
                .get();
    }
}
</code></pre>

<p>Test code</p>

<pre><code>RunWith(SpringRunner.class)
@SpringIntegrationTest(noAutoStartup = ""orderInputEndPoint"")
public class OrderPersistFlowTest {

    @Autowired
    private MockIntegrationContext mockIntegrationContext;

    @Test
    public void persistFlowTest(){
        OrderVO orderVO = new OrderVO();
        orderVO.setId(""1234"");
        orderVO.setName(""TestOrder"");
        orderVO.setDescription(""order desc"");

        MessageSource&lt;OrderVO&gt; messageSource = () -&gt; new GenericMessage&lt;&gt;(orderVO);

        this.mockIntegrationContext.substituteMessageSourceFor(""orderInputEndPoint"", messageSource);

        Message&lt;?&gt; receive = messageSource.receive();
    }
}
</code></pre>
",https://stackoverflow.com/questions/50758782/error-while-unit-testing-spring-integration-dsl,"['spring-integration', 'spring-integration-dsl']",369,TRUE,0,1
Service Undefined in Angular Component Unit Testing,"<p>I'm piping an observable into a component with async, but when I include that component in the parent component unit test, it breaks and says the service is undefined. Or more precisely <code>TypeError: Cannot read property 'subscribe' of undefined</code>. Could someone with more experience in unit tests please loo at this for me? Thanks!</p>

<p>I'm wondering if it has something to do with my renaming DataService to data, but that doesn't make sense to me.</p>

<p>Here is my spec:</p>

<pre><code>describe('SidenavComponent', () =&gt; {
  let component: SidenavComponent;
  let fixture: ComponentFixture&lt;SidenavComponent&gt;;

  const dataServiceStub = {
    partners$: Observable.of(['white-label']),
  };

  beforeEach(
    async(() =&gt; {
      TestBed.configureTestingModule({
        imports: [SharedModule, MatSidenavModule],
        declarations: [
          SidenavComponent,
          Component({
            template: '',
            selector: 'app-partner-select',
            inputs: ['partners', 'selectedPartner', 'opened'],
            outputs: ['openedChange'],
          })(class PartnerSelectComponent {}),
        ],
        providers: [{ provide: DataService, useValue: dataServiceStub }],
      }).compileComponents();
    }),
  );

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(SidenavComponent);
    console.log('breaks before this', fixture);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('exists!', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>

<p>the relevant javascript in the component class:</p>

<pre><code>  constructor(private data: DataService) {}

  get partners$() {
    return this.data.partners$;
  }
</code></pre>

<p>and the relevant html</p>

<pre><code>&lt;app-partner-select
  [partners]=""partners$ | async""
  [selectedPartner]=""'white-label'""
  [(opened)]=""partnerSelectOpen""
&gt;&lt;/app-partner-select&gt;
</code></pre>
",https://stackoverflow.com/questions/49454374/service-undefined-in-angular-component-unit-testing,"['angular', 'unit-testing', 'karma-jasmine', 'angular-services']",743,FALSE,-1,1
Laravel unit testing class not found error,"<p>I'm trying to do unit tests with laravel but get the following error.  I've not got to testing the function.  In my editor, I see the reference to the class correctly, however phpunit can't find it.</p>

<pre><code> Error: Class 'GoCardlessCheck' not found
</code></pre>

<p>my test looks like this </p>

<pre><code>  use Illuminate\Foundation\Testing\WithoutMiddleware;
  use Illuminate\Foundation\Testing\DatabaseMigrations;
  use Illuminate\Foundation\Testing\DatabaseTransactions;
  use PHPUnit\Framework\TestCase;



class GoCardlessTest extends TestCase
{
/**
 * A basic test example.
 *
 * @return void
 */
 public function testExample()
 {
    $acc = new GoCardlessCheck();

    $acc-&gt;CheckAccount('bob','mould','909090','57-77-90');

 }
</code></pre>

<p>}</p>
",https://stackoverflow.com/questions/48985691/laravel-unit-testing-class-not-found-error,"['laravel', 'phpunit']",1757,TRUE,0,1
Unit testing middleware with NUnit and NSubstitute,"<p>I've written a bit of middleware in an ASP.NET Core site and I'm trying to unit test it, mainly by following <a href=""http://www.sulhome.com/blog/15/unit-test-asp-net-core-middleware"" rel=""nofollow noreferrer"">this guide</a> that uses <a href=""https://en.wikipedia.org/wiki/Moq"" rel=""nofollow noreferrer"">Moq</a>.</p>

<p>My problem is finding an NUnit/NSubstitute equivalent for <code>new DefaultHttpContext()</code>. Substituting HttpContext will trigger the middleware, but it passes the <code>try</code>. I presume this is because of the issue quoted below. Does NUnit have a function to create a real HttpContext, or am I looking at a lot more infrastructure to achieve this?</p>

<blockquote>
  <p>I am sending an instance of DefaultHttpContext to the Invoke method. I can't use a mocked HttpContext in this scenario because the first middleware (the lambda function that we passed to the constructor) will need to write to the response. Hence the HttpResponse needs to be a real object not mocked.</p>
</blockquote>

<p>Here is the code for my Test</p>

<pre><code>[TestFixture]
public class ExceptionHelperTests
{
    private IErrorRepository errorRepository;
    private ExceptionHandler handler;

    [SetUp]
    public void Setup()
    {
        errorRepository = Substitute.For&lt;IErrorRepository&gt;();
    }

    [Test]
    public async void Given_AnExceptionHappens_Then_ItShouldBeLogged()
    {
        // Arrange
        const string username = ""aUser"";
        var user = Substitute.For&lt;ClaimsPrincipal&gt;();
        user.Identity.Name.Returns(username);

        handler = new ExceptionHandler(
            next: async (innerHttpContext) =&gt;
            {
                innerHttpContext.User = user;
            },
            repository: errorRepository);

        // Act
        await handler.Invoke(new DefaultHttpContext());

        // Assert
        errorRepository.Received().LogException(Arg.Any&lt;string&gt;(), Arg.Any&lt;Exception&gt;(), Arg.Is(username));
    }
}
</code></pre>

<p>Here is the IErrorRepository</p>

<pre><code>public interface IErrorRepository
{
    Exception LogException(string message, Exception ex, string userId);
    void LogMessage(string message, string errorDetail, string userId);
}
</code></pre>

<p>And here is the middleware (with a simplified HandleException):</p>

<pre><code>public sealed class ExceptionHandler
{
    private readonly RequestDelegate _next;
    private readonly IErrorRepository repository;

    public ExceptionHandler(RequestDelegate next, IErrorRepository repository)
    {
        _next = next;
        this.repository = repository;
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception ex)
        {
            HandleException(ex, context.User.Identity.Name);
        }
    }

    public void HandleException(Exception ex, string userId)
    {
        repository.LogException(""An unhandled exception has occurred."", ex, userId);
    }
}
</code></pre>
",https://stackoverflow.com/questions/50276964/unit-testing-middleware-with-nunit-and-nsubstitute,"['unit-testing', 'asp.net-core', 'nunit', 'middleware', 'nsubstitute']",2776,FALSE,0,1
angular unit testing async vs sync problems,"<p>I am very new to unit testing in angular and jasmine so I have been struggling to get it right. I am trying to write a simple unit test for a login page. The following is my code</p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { LoginComponent } from './login.component';
import {BrowserModule, By} from '@angular/platform-browser';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {Component, DebugElement, Input} from '@angular/core';
import {RouterTestingModule} from '@angular/router/testing';
import {LoaderService} from '@shared/services/loader.service';
import {AuthenticationService} from '@shared/services/authentication.service';
import {HttpClientModule} from '@angular/common/http';
import {CommonService} from '@shared/services/common.service';
import {ExploreService} from '@shared/services/explore.service';
import {TitleService} from '@shared/services/title.service';
import {AppConfig} from '../../app-config.service';
import {ThemeService} from '@shared/services/theme.service';
import {MatDialog, MatFormFieldModule, MatIconModule} from '@angular/material';
import {throwError} from 'rxjs';

@Component({
  selector: 'show-errors',
  template: '&lt;p&gt;Mock Product Settings Component&lt;/p&gt;'
})
class MockShowErrorsComponent {
  @Input() public control;
}
describe('LoginComponent', () =&gt; {
  let component: LoginComponent;
  let fixture: ComponentFixture&lt;LoginComponent&gt;;
  let authService: any;
  let common: any;
  let explore: any;
  let title: any;
  let config: any;
  let theme: any;
  let dialog: any;
  let debugElement: DebugElement;
  let element: HTMLElement;
  let submitSpy: any;
  beforeEach(async(() =&gt; {
    authService = jasmine.createSpyObj('AuthenticationService', [
      'login',
      'logout'
    ]);
    common = jasmine.createSpyObj('commonService', [
      'updateCurrentUrl',
      'isMobile',
    ]);
    explore = jasmine.createSpyObj('exploreService', [
      'slowCalcMessage',
      'cancelSlowMessage',
      'getInventoryTotalSummary',
      'handleError',
      'getMarketData'
    ]);
    title = jasmine.createSpyObj('titleService', [
      'getTitle',
      'setTitle',
      'updateTitle',
      'updateSiteName'
    ]);
    config = jasmine.createSpyObj('AppConfigService', [
      'load',
      'API_ENDPOINT'
    ]);
    theme = jasmine.createSpyObj('ThemeService', [
      'getThemeSettings',
      'generateColorTheme',
    ]);
    dialog = jasmine.createSpyObj('dialog', [
      'open'
      ]);
    TestBed.configureTestingModule({
      imports: [
        BrowserModule,
        FormsModule,
        ReactiveFormsModule,
        RouterTestingModule.withRoutes([]),
        HttpClientModule,
        MatIconModule,
        MatFormFieldModule,
      ],
      declarations: [
        LoginComponent,
      MockShowErrorsComponent
      ],
      providers: [
        LoaderService,
        {provide: AuthenticationService, useValue: authService},
        {provide: CommonService, useValue: common},
        {provide: ExploreService, useValue: explore},
        {provide: TitleService, useValue: title},
        {provide: AppConfig, useValue: config},
        {provide: ThemeService, useValue: theme},
        {provide: MatDialog, useValue: dialog},
      ]
    })
    .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
    debugElement = fixture.debugElement;
    element = debugElement.nativeElement;
    fixture.detectChanges();
  });

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
  it('should fail on wrong credentials', () =&gt; {
    const email = element.querySelector('#defaultForm-email') as HTMLInputElement;
    email.value = 'vigneshm@intermx.com';
    email.dispatchEvent(new Event('input'));
    const password = element.querySelector('#defaultForm-pass') as HTMLInputElement;
    password.value = 'agira123';
    password.dispatchEvent(new Event('input'));
    fixture.detectChanges();
    const service = debugElement.injector.get(AuthenticationService);
    submitSpy = spyOn(service, 'logout');
    debugElement.query(By.css('button.login-btn'))
      .triggerEventHandler('click', null);
    fixture.detectChanges();
    expect(submitSpy).toHaveBeenCalled();
  });
});
</code></pre>

<p>The above code is my specs and mocks for the login screen, I realized that the login page has too many dependencies which need to be simplified when starting to mock them.</p>

<p>The real problem is whenever I run this, the second test fails with <code>TypeError: Cannot set property 'value' of null</code>.</p>

<p>I am not sure why the DOM is not available at the time of testing, I should wait for DOM or angular to be ready? or is it something else?</p>
",https://stackoverflow.com/questions/53445205/angular-unit-testing-async-vs-sync-problems,"['angular', 'unit-testing', 'testing', 'jasmine', 'karma-jasmine']",1939,TRUE,0,4
Python programmation project structure with unit testing,"<p>I have been programming for a while, but never really got deep into it. Now I'm working in a reasearch center and I need to make my stuff coherent and compatible. My coworkers proposed to me a ""Standard"" method of organizing my project:</p>

<pre><code>Project
  |_ LICENCE.txt
  |_ README.txt

  |_ code
     |_ main.py
     |_ __init__.py

  |_ tests
     |_ context.py
     |_ test_main.py
</code></pre>

<p>That way they say it will be easier to do unit testing and all.</p>

<p>I have visited tens of websites that do exactly the same thing, so I figured it wouldn,t be that bad: wrong. I have been trying for the whole weekend now to make this work and I feel like I'm just getting colder.</p>

<p>Here is what I have:
<a href=""https://i.stack.imgur.com/0LWpu.png"" rel=""nofollow noreferrer"">IDE image with project structure with context.py open in the window</a></p>

<p>From what I have read in the past few days, This is the correct method, my problem is, no matter how I write it, the code won't recognize bidon.py, nor the funcitons defined in it. </p>

<p>bidon.py is just a file containing </p>

<pre><code>def add(x, y):
    return x+y


def sub(x, y):
    return x-y
</code></pre>

<p>in context it is not possible to use the function add, but when the test file and the .py are in the same folder, it seems to work... </p>

<p>But why doesn't it work even though I have added the path? I tried (in the context.py):</p>

<pre><code>import code

import code
import bidon

from code import bidion

from code import *

from code import bidon
from bidon import *

from code import bidon
from bidon import add
</code></pre>

<p>none of these worked.</p>

<p>It gets worse when I try to use the context.py in a test file.
For example in test_bidon.py, I have</p>

<pre><code>import unittest
from .context import code

class TestBidon(unittest.TestCase):
    def test_add(self):
        result = add(10, 5)
        self.assertEqual(result, 15)


if __name__ == ""__main___"":
    unittest.main()
</code></pre>

<p>This creates an error telling me that test_bidon.py is not a package?
Again, I tried multiple combinaisons, none worked. Please help me figure this out! I'm out of options and I don't want to spend another day looking for nothing.</p>
",https://stackoverflow.com/questions/50322835/python-programmation-project-structure-with-unit-testing,"['unit-testing', 'data-structures', 'project', 'code-organization']",36,TRUE,0,1
Dynamically create arbitrary objects for unit testing,"<p>Our codebase is filled with domain objects with large numbers of numeric and string fields.  In my unit tests, I find myself manually creating instances of these different objects like so:</p>

<pre><code>var car1 = new Car();
car1.Make = ""Make1"";
car1.Model = ""Model1"";
car1.Year = 1;

var car2 = new Car();
car2.Make = ""Make2"";
car2.Model = ""Model2"";
car2.Year = 2;
</code></pre>

<p>etc..</p>

<p>What's the cleanest way to generically build objects of any type automatically with only a single function call?  </p>

<p>Keep in mind I don't want the fields to be generated with random values.  Arbitrary repeatable values (like the 1 and 2 above) are what I'm going for.</p>
",https://stackoverflow.com/questions/51846143/dynamically-create-arbitrary-objects-for-unit-testing,"['c#', 'unit-testing']",441,FALSE,0,2
Unit Testing linked to a binary framework,"<p>I am trying to build an application using 2 frameworks : 1 is already compiled, and the other is a normal target of my project. I can make the application run but I am struggling to run Unit Tests. I created a dummy project with 3 elements to simplify things:</p>

<p>Framework 1 containing only one class:</p>

<pre><code>public class DummyClassFramework1{
    public static func helloWorld()-&gt; String {
        return ""Hello from Framework 1""
    }
}
</code></pre>

<p>Framework 2 containing only one class:</p>

<pre><code>import Framework1
public class DummyClassFramework2{
    public static func helloWorld()-&gt; String {
        return DummyClassFramework1.helloWorld() //Calling a class from framework1
    }
}
</code></pre>

<p>The demo App using this view controller:</p>

<pre><code>import Framework2
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        print(DummyClassFramework2.helloWorld())
    }
}
</code></pre>

<p>When I put everything in the same project, everything work: testing framework1, testing framework2, testing the app. However when I generate a fat framework1 with lipo, copy the .framework file in a new project that contains framework2 and demo App: I can not test framework 2 nor the demo App. However I can run the app normally.</p>

<p>The error that i get when launching tests is :</p>

<p>2018-09-13 11:51:04.645977+0200 xctest[34017:587268] The bundle “Framework1” couldn’t be loaded because it is damaged or missing necessary resources. Try reinstalling the bundle.</p>
",https://stackoverflow.com/questions/52311172/unit-testing-linked-to-a-binary-framework,"['swift', 'xcode', 'unit-testing']",325,TRUE,0,1
Unit testing a function without any response,"<p>I have the following function written in an Ember route</p>

<pre><code>  delete(line) {
    line.destroyRecord().then(() =&gt; {
      this.store.unloadRecord(line);
      this.controller.get('deliveryLines').removeObject(line);
    });
  },
</code></pre>

<p>My question is, should I write unit tests to cover it ?</p>

<p>After all, the function does not return anything, and does not have any side effects. Should I write unit tests to cover that the function is calling e.g. <code>destroyRecord</code> or <code>unloadRecord</code> ? </p>
",https://stackoverflow.com/questions/49176320/unit-testing-a-function-without-any-response,"['javascript', 'unit-testing', 'ember.js', 'ember-data']",31,TRUE,0,1
Unit testing an AuthorizeAttribute on an ASP.NET Core MVC API controller,"<p>I have a ASP.NET Core MVC API with controllers that need to be unit tested. </p>

<p><strong>Controller:</strong></p>

<pre><code>using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;

namespace TransitApi.Api.Controllers
{
    [Route(""api/foo"")]
    public class FooController : Controller
    {
        private IFooRepository FooRepository { get; }

        public FooController(IFooRepository fooRepository)
        {
            FooRepository = fooRepository;
        }

        [HttpGet]
        [Authorize(""scopes:getfoos"")]
        public async Task&lt;IActionResult&gt; GetAsync()
        {
            var foos = await FooRepository.GetAsync();
            return Json(foos);
        }
    }
}
</code></pre>

<p>It is essential that I am able to unit test the effectiveness of the <code>AuthorizeAttribute</code>. We have had issues in our code base with missing attributes and incorrect scopes. <a href=""https://stackoverflow.com/a/5255237"">This answer</a> is exactly what I am looking for, but not having a <code>ActionInvoker</code> method in <code>Microsoft.AspNetCore.Mvc.Controller</code> means I am not able to do it this way. </p>

<p><strong>Unit Test:</strong></p>

<pre><code>[Fact]
public void GetAsync_InvalidScope_ReturnsUnauthorizedResult()
{
    // Arrange
    var fooRepository = new StubFooRepository();
    var controller = new FooController(fooRepository)
    {
        ControllerContext = new ControllerContext
        {
            HttpContext = new FakeHttpContext()
            // User unfortunately not available in HttpContext
            //,User = new User() { Scopes = ""none"" }
        }
    };

    // Act
    var result = controller.GetAsync().Result;

    // Assert
    Assert.IsType&lt;UnauthorizedResult&gt;(result);
}
</code></pre>

<p><strong>How can I unit test that users without the correct scopes are denied access to my controller method?</strong></p>

<p>Currently I have settled for testing merely the presence of an <code>AuthorizeAttribute</code> as follows, but this is really not good enough:</p>

<pre><code>    [Fact]
    public void GetAsync_Analysis_HasAuthorizeAttribute()
    {
        // Arrange
        var fooRepository = new StubFooRepository();
        var controller = new FooController(fooRepository)
        {
            ControllerContext = new ControllerContext
            {
                HttpContext = new FakeHttpContext()
            }
        };

        // Act
        var type = controller.GetType();
        var methodInfo = type.GetMethod(""GetAsync"", new Type[] { });
        var attributes = methodInfo.GetCustomAttributes(typeof(AuthorizeAttribute), true);

        // Assert
        Assert.True(attributes.Any());
    }
</code></pre>
",https://stackoverflow.com/questions/48562403/unit-testing-an-authorizeattribute-on-an-asp-net-core-mvc-api-controller,"['c#', 'unit-testing', '.net-core', 'asp.net-core-mvc', 'xunit']",18625,TRUE,27,3
Angular unit-testing spyOn service from component,"<p>I've got a login component and I want to test it whether it calls the service's method with proper values, however I don't know how to spy on that service from the component.</p>

<p>I've tried</p>

<pre><code>beforeEach(() =&gt; {
...
authService = TestBed.get(AuthService);
});
</code></pre>

<p>And this is not working</p>

<pre><code>it('should pass proper values', () =&gt; {
    const submitSpy = spyOn(authService, 'signInByLogin');
    const loginSpy = spyOn(component, 'signIn').and.callThrough();

    const username = fixture.debugElement.query(By.css('#username'));
    const password = fixture.debugElement.query(By.css('#password'));
    const submitBtn = fixture.debugElement.query(By.css('[type=""submit""]'));

    username.nativeElement.value = 'test';
    password.nativeElement.value = 'password';

    fixture.detectChanges();

    expect(username.nativeElement.value).toBe('test');
    expect(password.nativeElement.value).toBe('password');
    expect(submitBtn).toBeTruthy();

    fixture.detectChanges();

    submitBtn.triggerEventHandler('click', null);

    fixture.whenStable().then(() =&gt; {
        expect(loginSpy).toHaveBeenCalled();
        expect(submitSpy).toHaveBeenCalledWith('test', 'password');
    });
});
</code></pre>

<p>It says</p>

<blockquote>
  <p>An error was thrown in afterAll
  Expected spy signInByLogin to have been called with [ 'test', 'password' ] but actual calls were [ '', '' ].</p>
</blockquote>

<p>The service's method is called from the private function in login component.
And the call is</p>

<pre><code>this.authService
            .signInByLogin(this.form.controls['login'].value, this.form.controls['password'].value).subscribe(...)
</code></pre>
",https://stackoverflow.com/questions/53477888/angular-unit-testing-spyon-service-from-component,"['angular', 'unit-testing', 'karma-runner']",1326,TRUE,0,1
Mock an Admin Controller for Unit Testing,"<p>I am working with ASP.NET Core 2.0, using xUnit and Moq to create unit tests for administrative functions. I have an AdminController.cs that uses dependency injection for the following within its constructor</p>

<pre><code>private UserManager&lt;AppUser&gt; userManager;
private IUserValidator&lt;AppUser&gt; userValidator;
private IPasswordValidator&lt;AppUser&gt; passwordValidator;
private IPasswordHasher&lt;AppUser&gt; passwordHasher;
private RoleManager&lt;IdentityRole&gt; roleManager;
private SignInManager&lt;AppUser&gt; signInManager;
</code></pre>

<p>I try to arrange them in the following manner in my unit test</p>

<pre><code>// Arrange
Mock&lt;EFRepository&gt; mockRepo = new Mock&lt;EFRepository&gt;();
var userStoreMock = new Mock&lt;IUserRoleStore&lt;AppUser&gt;&gt;();
var userManager = new UserManager&lt;AppUser&gt;(userStoreMock.Object, null, null, null, null, null, null, null, null);
AppUser user = new AppUser();

var roleStoreMock = new Mock&lt;IRoleStore&lt;IdentityRole&gt;&gt;();
var userValidator = new Mock&lt;IUserValidator&lt;AppUser&gt;&gt;();
var passwordValidator = new Mock&lt;IPasswordValidator&lt;AppUser&gt;&gt;();
var passwordHasher = new Mock&lt;IPasswordHasher&lt;AppUser&gt;&gt;();
var roleManager = new RoleManager&lt;IdentityRole&gt;(roleStoreMock.Object, null, null, null, null, null);
var signInManager = new Mock&lt;SignInManager&lt;AppUser&gt;&gt;();

//THIS LINE CAUSES THE ERROR
AdminController controller = new AdminController(userManager, userValidator.Object, passwordValidator.Object, passwordHasher.Object, roleManager, signInManager.Object);
</code></pre>

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

<p><code>Can not instantiate proxy of class: Microsoft.AspNetCore.Identity.SignInManager 
Could not find a parameterless constructor.</code></p>

<p>I have not yet been able to find a proper way of mocking a <code>SignInManager</code> that works</p>

<p>I've been trying to work with the method below without success:</p>

<pre><code>private Mock&lt;SignInManager&lt;AppUser&gt;&gt; GetMockSignInManager()
{
    var mockUsrMgr = GetMockUserManager();
    var mockAuthMgr = new Mock&lt;AuthenticationManager&gt;();
    var mockContextAssosor = new Mock&lt;IHttpContextAccessor&gt;();
    var mockClaimsFactory = new Mock&lt;IUserClaimsPrincipalFactory&lt;AppUser&gt;&gt;();
    //i am unclear on how to mock the options
    var opts = new Mock&lt;IOptions&lt;&gt;&gt;();
    var mockLogger = new Mock&lt;ILogger&lt;SignInManager&lt;AppUser&gt;&gt;&gt;();
    //namespace for IAuthenicationSchemeProvider is not recognized
    var scheme = new Mock&lt;IAuthenticationSchemeProvider&gt;();
    //return new Mock&lt;SignInManager&lt;AppUser&gt;&gt;(mockUsrMgr.Object, mockAuthMgr.Object...and so on);
}
</code></pre>
",https://stackoverflow.com/questions/50889835/mock-an-admin-controller-for-unit-testing,"['c#', 'unit-testing', 'moq', 'xunit']",1241,TRUE,0,1
Angular Unit Testing - Cannot Find Name &#39;xyzDirective&#39;,"<p>I have a component that uses a module loader and when I import it to my spec file I can't seem to test a specific directive because it can't be found. I an getting </p>

<pre><code>Cannot find name 'AwesomeHelperDirective'
</code></pre>

<p>and the Jasmine output says:</p>

<pre><code>ReferenceError: AwesomeHelperDirective is not defined
</code></pre>

<p><strong>My module looks like this...</strong></p>

<pre><code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import {
  AwesomeComponent,
} from './awesome.component';

@NgModule({
  declarations: [
      AwesomeComponent,
      AwesomeHelperDirective,
  ],
  imports: [CommonModule],
  exports: [
      AwesomeComponent,
      AwesomeHelperDirective,
  ]
})
export class AwesomeModule { }
</code></pre>

<p><strong>In my spec file I have this:</strong></p>

<pre><code>import { AwesomeModule } from './awesome.module';

describe('AwesomeComponent', () =&gt; {

   const html =  `&lt;app-template&gt;&lt;/app-template&gt;`;

   beforeEach(() =&gt; {
      TestBed.configureTestingModule({
        imports: [AwesomeModule],
        declarations: [TestComponent],
      }).overrideComponent(TestComponent, {
          set: {template: html},
        }).compileComponents();
    });

    it('should ...', () =&gt; {
      const fixture = TestBed.createComponent(TestComponent);
      fixture.detectChanges();

      const clickMock = spyOn(AwesomeHelperDirective, 'onClick');
      fixture.debugElement.query(By.css('awesome-helper')).triggerEventHandler('click', null);
      expect(clickMock).toHaveBeenCalled();
    });

});
</code></pre>
",https://stackoverflow.com/questions/50606576/angular-unit-testing-cannot-find-name-xyzdirective,"['angular', 'unit-testing', 'angular5', 'karma-jasmine']",211,FALSE,0,0
Missing required parameters for [Route] unit testing,"<p>I have this piece of code for feature test for controller store method </p>

<pre><code>$response= $this-&gt;post(route('contact.store'),[$client-&gt;value])
</code></pre>

<p>but I got this error </p>

<pre><code>Missing required parameters for [Route: contact.store] [URI: client/{clientValue}/contact].
</code></pre>

<p>How  I can fix this ?</p>
",https://stackoverflow.com/questions/49004065/missing-required-parameters-for-route-unit-testing,"['php', 'unit-testing', 'testing', 'laravel-5', 'laravel-5.5']",912,FALSE,0,1
Unit testing directive with controllerAs using Jasmine,"<p>I am new to Jasmine unit testing and this is the first time I am trying to test a directive with controller. The structure of my directive and controller is little different which I didn't see in any of the blogs or stackoverflow questions. I am struggling a bit to access the function _testSampleFunction() to test in my test cases. The downfall here is that I cannot change the architecture of directive and I want to write test cases accordingly. Any help would be appreciated!</p>

<p>Below is how my controller is defined :</p>

<pre><code>(function () {
'use strict';

angular.module('myApp',[])
        .directive('myDirective', myDirective);

function myDirective()
{
        var directive ={
        template : '&lt;div&gt;&lt;/div&gt;',
        controller : myController,
        controllerAs : 'vm',
        scope: {},
        };

        myController.$inject =['$scope'];
        return directive;

    function myController($scope)
    {
        var vm = this;
        init();

        function init()
        {
            vm.TestSampleFunction = _testSampleFunction;
        }

        function _testSampleFunction()
        {
            return 'my directive';
        }

    }

}})(window.angular);    
</code></pre>

<p>Here is the plunker (spec.js is included): <a href=""http://next.plnkr.co/edit/NfyscZUnpyLvslvH?preview"" rel=""nofollow noreferrer"">Demo Plunker</a> </p>

<p>Thanks in Advance!</p>
",https://stackoverflow.com/questions/51025201/unit-testing-directive-with-controlleras-using-jasmine,"['angularjs', 'unit-testing', 'jasmine']",72,TRUE,0,1
Adding UI Tests in Unit testing target,"<p>I don't want to pollute/mix the unit test cases(written using QuickSpec) which I have written in <strong>UNIT TESTING TARGET</strong> with UI tests from EarlGrey.</p>

<p>Is there any alternative that I can have EarlGrey tests to be added to <strong>UI TESTING TARGET</strong>?</p>
",https://stackoverflow.com/questions/51189769/adding-ui-tests-in-unit-testing-target,['earlgrey'],92,FALSE,0,1
Unit Testing of RecyclerView items with counts,"<p>Here I'm trying to write some basic unit test cases and I have written 2 test cases as</p>

<pre><code>@Rule
public ActivityTestRule&lt;MainActivity&gt; main = new ActivityTestRule&lt;MainActivity&gt;(MainActivity.class);


@Test
public void testShouldLaunchTheMainActivityAndFindItemsInTheList() throws Exception {
    RecyclerView recyclerView = (RecyclerView) main.getActivity().findViewById(R.id.recyclerView);
    assertThat(recyclerView.getScrollBarSize(), is(11));
}

@Before
public void init() {
    main.getActivity()
            .getSupportFragmentManager().beginTransaction();
}

@Test
public void testShouldTestTheItemNameInTheList() throws Exception {
    RecyclerView recyclerView = (RecyclerView) main.getActivity().findViewById(R.id.recyclerView);

    if (recyclerView.getScrollBarSize() &gt; 0) {
        for (int i = 0; i &lt; recyclerView.getScrollBarSize(); i++) {
            if (i == 1) {
                onView(withId(R.id.recyclerView)).perform(RecyclerViewActions.actionOnItemAtPosition
                        (1, typeTextIntoFocusedView(""Flag"")));
            }
        }
    }
}
</code></pre>

<p>Sometimes both the test cases get passed successfully but sometimes second case gets failed and when I test on another device first one also gets failed. Anyone can help me out of this ?</p>
",https://stackoverflow.com/questions/51852252/unit-testing-of-recyclerview-items-with-counts,"['android', 'unit-testing', 'junit']",214,FALSE,0,1
Unit Testing Assert Equal: Alternate Expected Result,"<p>Is there a way to use assertEqual, but with an alternate expected result?
That is, if the test failed for one expected result it will test again with the alternate result. </p>
",https://stackoverflow.com/questions/48506061/unit-testing-assert-equal-alternate-expected-result,"['python', 'unit-testing']",94,TRUE,-1,1
Unit testing not working in new gem,"<p>Hi i have created a new gem in which there is a method which reads a json file and prints the data of json file on console. now i want to write unit test for this gem. so i have created a file mivi_test.rb inside test/unit/ directory.</p>

<pre><code>mivi_test.rb
require 'active_support'
class MiviTest &lt; ActiveSupport::TestCase

  def test_mivi
     assert_equal ""test"",""test""
  end
end
</code></pre>

<p>i want to check if the input and outpur is same. soi run this file with <code>ruby test/unit/mivi_test.rb</code> it doesnot throw any error but the output is blank. i am expecting it will print on console like <code>1 tests, 1 assertions, 0 failures, 0 errors</code> 
but my output is blank. please help me to fix it. Thanks in advance.</p>
",https://stackoverflow.com/questions/49359154/unit-testing-not-working-in-new-gem,"['ruby-on-rails', 'rubygems']",31,FALSE,0,1
Angular 2+ Unit testing : disable console logs,"<p>When I run <code>ng test</code> and some of my tests do not work, I have an issue : the logs are displayed in my console. Here is an example : </p>

<pre><code>× should be created
Chrome 63.0.3239 (Windows 10 0.0.0) ConfirmationDialogService should be created FAILED
        Error: StaticInjectorError[MatDialog]:
          StaticInjectorError[MatDialog]:
            NullInjectorError: No provider for MatDialog!
            at _NullInjector.webpackJsonp.../../../core/esm5/core.js._NullInjector.get C:/Users/MT4E45CN/Documents/Projects/POC/node_modules/@angular/core/esm5/core.js:993:1)
            at resolveToken C:/Users/MT4E45CN/Documents/Projects/POC/node_modules/@angular/core/esm5/core.js:1281:1)
            at tryResolveToken C:/Users/MT4E45CN/Documents/Projects/POC/node_modules/@angular/core/esm5/core.js:1223:1)
            at StaticInjector.webpackJsonp.../../../core/esm5/core.js.StaticInjector.get C:/Users/MT4E45CN/Documents/Projects/POC/node_modules/@angular/core/esm5/core.js:1094:1)
            at resolveToken C:/Users/MT4E45CN/Documents/Projects/POC/node_modules/@angular/core/esm5/core.js:1281:1)
            at tryResolveToken C:/Users/MT4E45CN/Documents/Projects/POC/node_modules/@angular/core/esm5/core.js:1223:1)
            at StaticInjector.webpackJsonp.../../../core/esm5/core.js.StaticInjector.get C:/Users/MT4E45CN/Documents/Projects/POC/node_modules/@angular/core/esm5/core.js:1094:1)
            at resolveNgModuleDep C:/Users/MT4E45CN/Documents/Projects/POC/node_modules/@angular/core/esm5/core.js:10878:1)
            at _createClass C:/Users/MT4E45CN/Documents/Projects/POC/node_modules/@angular/core/esm5/core.js:10915:1)
            at _createProviderInstance$1 C:/Users/MT4E45CN/Documents/Projects/POC/node_modules/@angular/core/esm5/core.js:10889:1)
</code></pre>

<p>I would like to delete this trace from my console, since I don't need it : I have set up my reporter to give me only the first lines of an error. </p>

<p>Is there a way to disable those logs ? (I assume they come from chrome console but I might be wrong by the way). </p>

<p>PS : I have tried to disable them with </p>

<pre><code>client: {
  captureConsole: false
},
</code></pre>

<p>In my karma configuration, but it doesn't work. </p>
",https://stackoverflow.com/questions/48172271/angular-2-unit-testing-disable-console-logs,"['angular', 'mocha.js', 'karma-runner']",438,FALSE,0,0
Unit testing a SharedPreferences wrapper with Mockito,"<p>I've got a utility wrapper around <code>SharedPreferences</code> in Android. I want to unit test this wrapper, so I am mocking the parts that I am not testing:</p>

<pre><code>@Before
public void setup() {
    context = Mockito.mock(Context.class);
    prefs = Mockito.mock(SharedPreferences.class);
    editor = Mockito.mock(SharedPreferences.Editor.class);

    when(context.getSharedPreferences(anyString(), anyInt())).thenReturn(prefs);
    when(prefs.edit()).thenReturn(editor);
    when(editor.commit()).thenReturn(true);
}
</code></pre>

<p>My test, however, hits an NPE at the line where I get the <code>Editor</code>:</p>

<pre><code>SharedPreferences.Editor editor = prefs.edit();
</code></pre>

<p>What am I missing to make this mock work? I've seen a number of other SO answers recommending using various tools, but I would strongly prefer to avoid those for a simple set of tests if possible. If I do need to use another tool, what should I look at and how does that tool address the issue?</p>
",https://stackoverflow.com/questions/48652816/unit-testing-a-sharedpreferences-wrapper-with-mockito,"['java', 'android', 'junit', 'mockito', 'sharedpreferences']",3085,TRUE,0,1
Python Unit Testing - Mock Patch at Runtime?,"<p>I am writing unit tests in python.</p>

<p>My code uses <code>redis</code> frequently and I want to mock this. I'd like to do this globally and not worry about mocking it in each test, but I don't think this is possible using the <code>@patch</code> decorator.</p>

<p>Example of working test-</p>

<pre><code>class ExamplesTests(AbstractTestCase, unittest.TestCase):

    @patch('main.redis')
    def test_the_thing(self, redis: MagicMock):
        redis.set = self._my_mock_set # method that sets a dict val
        redis.get = self._my_mock_get # method that gets a dict val

        result = main.do_the_thing()

        self.assertTrue(result)
</code></pre>

<p>I don't actually need what's in the mock cache, i'm just trying to prevent the need to cleanup the actual redis cache that's being used by other processes. I tried doing this in the <code>setUp</code>-</p>

<pre><code>class AbstractTestCase(ABC):

    @patch('main.redis')
    def setUp(self, redis: MagicMock):
        redis.set = self._my_mock_set # method that sets a dict val
        redis.get = self._my_mock_get # method that gets a dict val
</code></pre>

<blockquote>
  <p>Error: setUp() takes 2 positional arguments but 3 were given</p>
</blockquote>

<p>Instead of patching every test, is it possible to use setup without the decorator? Something like this?-</p>

<pre><code>class AbstractTestCase(ABC):

    def setUp(self):
        redis = patch('main.redis')
        redis.set = self._my_mock_set # method that sets a dict val
        redis.get = self._my_mock_get # method that gets a dict val
</code></pre>
",https://stackoverflow.com/questions/53546929/python-unit-testing-mock-patch-at-runtime,"['python', 'unit-testing', 'mocking', 'python-unittest', 'magicmock']",570,TRUE,0,1
wrapper.find() is throwing error in unit testing,"<p>I'm trying to do a unit test on a Vue component. I'm getting an error when wrapper.find() is used.</p>

<p>Component is as given below:
snackbar.vue</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>&lt;script&gt;
import { mapGetters } from ""vuex"";

export default {
  computed: {
    ...mapGetters({
      visibility: ""snackbar/visibility"",
      type: ""snackbar/type"",
      message: ""snackbar/message""
    })
  },
  watch: {
    visibility(value) {
      if (value) {
        $(""#snackbar"").addClass(""show "" + this.type);
        setTimeout(() =&gt; {
          $(""#snackbar"").removeClass(""show "" + this.type);
          this.$store.dispatch(""snackbar/close"");
        }, 3000);
      }
    }
  }
};
&lt;/script&gt;</code></pre>
<pre class=""snippet-code-html lang-html prettyprint-override""><code>&lt;template&gt;
  &lt;div id=""snackbar""&gt;{{ message }}&lt;/div&gt;
&lt;/template&gt;</code></pre>
</div>
</div>
</p>

<p>In the testing I want to get a div having snackbar as id using wrapper.find().</p>

<p>It's spec file:
snackbar.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>import SnackBar from '../../../src/modules/Common/_components/snackbar.vue';

import { mount, createLocalVue } from '@vue/test-utils';
import Vue from 'vue'
import Vuex from 'vuex'

const localVue = createLocalVue()
localVue.use(Vuex)

describe('Snackbar component', () =&gt; {
  let store
  beforeEach(() =&gt; {
    let state = {
      isVisible: false,
      message: '',
      type: ''
    }

    let getters = {
      'snackbar/visibility': (state) =&gt; state.isVisible,
      'snackbar/type': (state) =&gt; state.type,
      'snackbar/message': (state) =&gt; state.message
    }

    store = new Vuex.Store({
      modules: {
        snackbar: {
          state,
          getters
        }
      }
    })
  })

  it('renders the correct markup', () =&gt; {
    let wrapper = mount(SnackBar, { localVue, store })
    let snackbar = wrapper.find('#snackbar');
    
    // some test code related to snackbar
  })
})</code></pre>
</div>
</div>
</p>

<p>The log is as given below:  </p>

<p>cross-env BABEL_ENV=test karma start test/unit/karma.conf.js --single-run  </p>

<p>30 05 2018 18:18:57.847: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>  </p>

<p>30 05 2018 18:18:57.849:INFO [launcher]: Launching browser PhantomJS with unlimited concurrency  </p>

<p>30 05 2018 18:18:57.855:INFO [launcher]: Starting browser PhantomJS  </p>

<p>30 05 2018 18:18:58.293:INFO [PhantomJS 2.1.1 (Linux 0.0.0)]: Connected on socket UwfYAt7yHauyEGfNAAAA with id 26585183  </p>

<p>Snackbar component<br>
    ✗ renders the correct markup<br>
        undefined is not a function (evaluating 'vNodes.findIndex(function (node) { return vNode.elm === node.elm; })')  </p>

<pre><code>    webpack:///node_modules/@vue/test-utils/dist/vue-test-utils.js:2887:48 &lt;- index.js:145115:83  
    filter@[native code] 

    removeDuplicateNodes@webpack:///node_modules/@vue/test-utils/dist/vue-test-utils.js:2887:0 &lt;- index.js:145115:23  

    findVNodesBySelector@webpack:///node_modules/@vue/test-utils/dist/vue-test-utils.js:2917:0 &lt;- index.js:145145:30  

    findVnodes@webpack:///node_modules/@vue/test-utils/dist/vue-test-utils.js:2934:0 &lt;- index.js:145162:30  

    find@webpack:///node_modules/@vue/test-utils/dist/vue-test-utils.js:2982:0 &lt;- index.js:145210:27  

    find$$1@webpack:///node_modules/@vue/test-utils/dist/vue-test-utils.js:3272:0 &lt;- index.js:145500:19  

    webpack:///test/unit/specs/snackbar.spec.js:38:32 &lt;- index.js:142013:32  
</code></pre>

<p>PhantomJS 2.1.1 (Linux 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.622 secs / 0.009 secs)  </p>
",https://stackoverflow.com/questions/50605679/wrapper-find-is-throwing-error-in-unit-testing,"['unit-testing', 'vue.js']",1010,TRUE,0,1
Unit testing for component methods angular 7,"<p>My Component code -</p>

<pre><code>import { Component, EventEmitter, Input, OnInit, OnChanges, SimpleChanges,  Output } from '@angular/core';
import { CI, CiWithStatus } from '../ci-list.service';
import { ContextPanelApi } from '../../../../../../../../shared/shared-html/js/directives/oprContextPanel/oprContextPanel/oprContextPanelApi.service';

@Component({
  selector: 'opr-watchlist-cards',
  templateUrl: './watchlist-cards.component.html',
  styleUrls: ['./watchlist-cards.component.scss']
})
export class WatchlistCardsComponent implements OnInit, OnChanges {

  @Input() ciList: CiWithStatus[];
  @Input() itemWidth: number;
  @Input() itemHeight: number;
  @Input() zoomLevel: number;

  @Output() onSelectedCisChanged: EventEmitter&lt;CI[]&gt; = new EventEmitter&lt;CI[]&gt;();

  private _selectedItems: CI[] = [];

  constructor(private _oprContextPanelApiService: ContextPanelApi) {
  }

  ngOnInit() {
    console.debug('ciList', this.ciList);
  }

  ngOnChanges(changes: SimpleChanges): void {
    if(changes.zoomLevel) {
      this.zoomLevel = changes.zoomLevel.currentValue;
    }
  }

  onItemClick(event: MouseEvent, ci: CI) {
    if (event.ctrlKey) {
      if (this.isSelected(ci)) {
        this._selectedItems.splice(this._selectedItems.indexOf(ci), 1);
      } else {
        this._selectedItems.push(ci);
      }
    } else {
      this._selectedItems = [ci];
    }
    this.onSelectedCisChanged.emit(this._selectedItems);
  }

  onItemRightClick(event: MouseEvent, ci: CI) {
    const position = {left: event.clientX, top: event.clientY};
    const contextPanelConfig = {
      title: 'context menu dummy ' + ci.name,
      position
    };
    const contextPanelPages = [];
    this._oprContextPanelApiService.openContext(contextPanelConfig, contextPanelPages, () =&gt; {
    });
    return false; //prevent native browser context menu
  }

  isSelected(ci: CI) {
    return this._selectedItems.includes(ci);
  }
}
</code></pre>

<p>My Spec file code -</p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { SimpleChange } from '@angular/core';
import { WatchlistCardsComponent } from './watchlist-cards.component';
import { AppSharedModule } from '../../../../../app-shared/src/lib/app-shared.module';
import { WatchlistCardComponent } from './watchlist-card/watchlist-card.component';
import { ContextPanelApi } from 'shared/directives/oprContextPanel/oprContextPanel/oprContextPanelApi.service';

export class MockContextPanelApi {

}

describe('WatchlistCardsComponent', () =&gt; {
  let component: WatchlistCardsComponent;
  let fixture: ComponentFixture&lt;WatchlistCardsComponent&gt;;
  let params;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [AppSharedModule],
      declarations: [WatchlistCardComponent, WatchlistCardsComponent],
      providers: [{ provide: ContextPanelApi, useClass: MockContextPanelApi }]
    })
      .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(WatchlistCardsComponent);
    component = fixture.componentInstance;
    params = {
      ci: {
        global_id: ""9e76bafea39c49e786360baeb2551fd7"",
        icon: ""/odb/icons/unix/unix_32.svg"",
        id: ""9e76bafea39c49e786360baeb2551fd7"",
        last_changed: 1540465938749,
        long_id: ""1;;9e76bafea39c49e786360baeb2551fd7"",
        name: ""srv0"",
        status: 0,
        type: ""unix"",
        type_label: ""Unix"",
        event: ""link""
      },
      event: {

      }
    };
    fixture.detectChanges();
  });

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });

  it('should call ngOnChanges', () =&gt; {
    component.zoomLevel = 3;
    component.ngOnChanges({
      zoomLevel: new SimpleChange(null, component.zoomLevel, true)
    });
    fixture.detectChanges();
  })

  it('should call the onItemClick method', async(() =&gt; {
    spyOn(component, 'onItemClick');
    component.onItemClick(params.event, params.ci);
    fixture.whenStable().then(() =&gt; {
      expect(component.onItemClick).toHaveBeenCalled();
    });
  }));

  it('should call the onItemRightClick method', async(() =&gt; {
    spyOn(component, 'onItemRightClick');
    component.onItemRightClick(params.event, params.ci);
    expect(component.onItemRightClick).toHaveBeenCalled();
  }));

  it('should call the isSelected method', async(() =&gt; {
    spyOn(component, 'isSelected');
    component.isSelected(params.ci);
    expect(component.isSelected).toHaveBeenCalled();
  }));

});
</code></pre>

<p>I wanted to cover the functions, I tried doing this in spec but still it says functions not covered.</p>

<p>Please guide me how i can cover the functions and statement for isSelected, onItemRightClick, onItemClick  methods</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/53778420/unit-testing-for-component-methods-angular-7,"['angular', 'unit-testing', 'karma-jasmine', 'angular7']",8576,TRUE,0,1
Unit Testing Password Validators in ASP.NET Core,"<p>I have a CustomPasswordValidator.cs </p>

<pre><code> public class CustomPasswordValidator
{
    public int MinLength { get; set; }
    public int MaxLength { get; set; }


    public Task&lt;IdentityResult&gt; ValidateAsync(string item)

    {
        IdentityError errors = new IdentityError();
        MinLength = 8;
        MaxLength = 16;
        if (String.IsNullOrEmpty(item) || item.Length &lt; MinLength || item.Length &gt; MaxLength)

        {

            errors.Description = ""password must be of minimum 8 characters "";
            return Task.FromResult(IdentityResult.Failed(errors));
        }
        //Minimum eight charachters and maximum 16 characters, at least one uppercase letter, one number and no spaces
        string pattern = @""^(?=.*\d+)(?=.*[a-zA-Z])[0-9a-zA-Z@#$%^&amp;*-_+={}|:‘,.?`~]{8,16}$"";
        //@""^(?=.*[a-z])(?=.*\d)[A-Za-z\d$@$!%*?&amp;]{8,16}"";
        if (!Regex.IsMatch(item, pattern))

        {
            errors.Description = ""password must at least have one uppercase letter, one number and no spaces "";
            return Task.FromResult(IdentityResult.Failed(errors));
        }

        return Task.FromResult(IdentityResult.Success);
    }
}
</code></pre>

<p>And a controller which calls the validator class :</p>

<pre><code>   public class ValidatePasswordController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public JsonResult ChangePassword(ChangePasswordRequest user)
    {
        //get user data 
        string Password = user.Password;
        CustomPasswordValidator CheckPWD = new CustomPasswordValidator();
        var result = CheckPWD.ValidateAsync(Password);
        var errors = result.Result.Errors.ToArray();
        string Description = errors[0].Description;
        return Json(Description);
    }
}
</code></pre>

<p>I'm new to using  unit testing with TestTools.UnitTesting. I want to create a unit test class that ensures that the right result is being returned. How can I approach that</p>

<pre><code>  class PasswordValidatorTest
{

    [TestMethod]
    public void TestPWDValidation()
    {
        var password = ""Thi$user12345"";
        var w = new ValidatePasswordController() { }; //arrange
        //act


    }
}
</code></pre>
",https://stackoverflow.com/questions/51558514/unit-testing-password-validators-in-asp-net-core,"['c#', 'unit-testing', 'asp.net-core', 'change-password']",36,FALSE,0,0
Unit testing Realm wrapped LiveData with Mockito,"<p>I am trying out Realm along with Android architecture components including LiveData.</p>

<p>I have been following Google's Guide to Application Architecture:</p>

<p><a href=""https://developer.android.com/topic/libraries/architecture/guide.html"" rel=""nofollow noreferrer"">https://developer.android.com/topic/libraries/architecture/guide.html</a></p>

<p>...substituting Room with Realm.</p>

<p>I have everything working from an implementation perspective but have run into an issue with Mockito I cannot yet resolve when trying to write unit tests.</p>

<p>I have shown my test below with some commented out lines along with explanations of what I have tried so far and the result:</p>

<pre><code>@Test
public void loadCustomModelObjectsFromNetwork() throws IOException {

    // Prepare DAO
    MutableLiveData&lt;List&lt;CustomModelObject&gt;&gt; dbData = new MutableLiveData&lt;&gt;();

    // Compilation error
    //when(dao.getCustomModelObjects()).thenReturn(dbData);

    // Runtime exc.
    //doReturn(dbData).when(dao).getCustomModelObjects();

    // Runtime exc.
    //java.lang.ClassCastException: 
    //android.arch.lifecycle.MutableLiveData cannot be cast to LiveRealmResults
    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock i) throws Throwable {
            // Made various attempts to convert to LiveRealmResults here 
            return dbData;
        }
    }).when(dao).getCustomModelObjects();

/*
org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
MutableLiveData cannot be returned by getCustomModelObjectss()
getCustomModelObjects() should return LiveRealmResults
*/

    // Prepare REST service response
    List&lt;CustomModelObject&gt; customModelObjects = new ArrayList&lt;&gt;();
    CustomModelObject repo = new CustomModelObject();
    repo.setDescription(""Desc1"");
    customModelObjects.add(repo);

    CustomModelObjectsResponse response = new CustomModelObjectsResponse();
    response.setCustomModelObjects(customModelObjects);

    DocumentWrapper&lt;CustomModelObjectsResponse&gt; items = new DocumentWrapper&lt;&gt;();
    items.setBody(response);

    LiveData&lt;ApiResponse&lt;DocumentWrapper&lt;CustomModelObjectsResponse&gt;&gt;&gt; call = successCall(items);
    when(retrofitService.getCustomModelObjects()).thenReturn(call);
    when(service.getService()).thenReturn(retrofitService);

    // Item under test
    LiveData&lt;Resource&lt;List&lt;CustomModelObject&gt;&gt;&gt; data = repository.getCustomModelObjects();

    // Assertions
    verify(dao).getCustomModelObjects();

    verifyNoMoreInteractions(service);

    Observer observer = mock(Observer.class);
    data.observeForever(observer);
    verifyNoMoreInteractions(service);
    verify(observer).onChanged(Resource.loading(null));

    MutableLiveData&lt;List&lt;CustomModelObject&gt;&gt; updatedDbData = new MutableLiveData&lt;&gt;();
    //when(dao.getCustomModelObjects()).thenReturn(updatedDbData);
    doReturn(updatedDbData).when(dao).getCustomModelObjects();

    dbData.postValue(null);
    verify(retrofitService).getCustomModelObjects();
    verify(dao).save(customModelObjects);

    updatedDbData.postValue(customModelObjects);
    verify(observer).onChanged(Resource.success(repo));
}
</code></pre>

<p>Even though in my implementation it works fine and <code>LiveData&lt;List&lt;CustomModelObject&gt;&gt;</code> can be derived from <code>LiveRealmResults&lt;CustomModelObject&gt;</code> in the unit test I cannot seem to get this to work with Mockito.</p>

<p>More implementation details about my setup can be found here:</p>

<p><a href=""https://stackoverflow.com/questions/49654211/using-realm-and-livedata-converting-livedatarealmresultscustommodelobject-t"">Using Realm and LiveData. Converting LiveData&lt;RealmResults&lt;CustomModelObject&gt;&gt; to LiveData&lt;List&lt;CustomModelObject&gt;&gt;</a></p>

<p>Thanks,
Paul.</p>

<p><strong>UPDATE</strong></p>

<pre><code>when(dao.getCustomModelObjects()).thenReturn(dbData);

has the following compilation error:

error: no suitable method found for 

thenReturn(MutableLiveData&lt;List&lt;CustomModelObject&gt;&gt;)
method OngoingStubbing.thenReturn(LiveRealmResults&lt;CustomModelObject&gt;) is not applicable
(argument mismatch; MutableLiveData&lt;List&lt;CustomModelObject&gt;&gt; cannot be converted to LiveRealmResults&lt;CustomModelObject&gt;)
method OngoingStubbing.thenReturn(LiveRealmResults&lt;CustomModelObject&gt;,LiveRealmResults&lt;CustomModelObject&gt;...) is not applicable
(argument mismatch; MutableLiveData&lt;List&lt;CustomModelObject&gt;&gt; cannot be converted to LiveRealmResults&lt;CustomModelObject&gt;)
</code></pre>
",https://stackoverflow.com/questions/49687805/unit-testing-realm-wrapped-livedata-with-mockito,"['android', 'realm', 'mockito', 'android-livedata']",1068,TRUE,0,1
Unit testing for IDomainService with ASP.NET Boilerplate,"<p>I am unit testing ABP, but I got error below:</p>

<blockquote>
  <p>Cannot access a disposed object. A common cause of this error is
  disposing a context that was resolved from dependency injection and
  then later trying to use the same context instance elsewhere in your
  application. This may occur if you are calling Dispose() on the
  context, or wrapping the context in a using statement. If you are
  using dependency injection, you should let the dependency injection
  container take care of disposing context instances. Object name:
  'XXXDbContext'.</p>
</blockquote>

<p>Here are my detailed steps:</p>

<ol>
<li><p>AppService</p>

<pre><code>public async Task&lt;ProductDto&gt; CreateProduct(CreateProductInput input)
{
    var existing = // await _productManager.ProductRepository.FirstOrDefaultAsync(p =&gt; p.Name == input.Name);
                      await _productManager.Products.Where(p =&gt; p.Name == input.Name).FirstOrDefaultAsync();
    if (existing != null) throw new UserFriendlyException(L(""ExistedRepeatedAd""));

    var newAdEntity = ObjectMapper.Map&lt;Product&gt;(input);
    // Rest of the code
}
</code></pre></li>
<li><p>ProductManager</p>

<pre><code>public class ProductManager : IDomainService
{
    private readonly IRepository&lt;Product, long&gt; _ProductRepository;
    private readonly IUnitOfWorkManager _unitOfWorkManager;

    public ProductsManager(
        IRepository&lt;Product, long&gt; ProductRepository,
        IUnitOfWorkManager unitOfWorkManager)
    {
        _ProductRepository = ProductRepository;
        _unitOfWorkManager = unitOfWorkManager;
    }

    #region Products

    public IRepository&lt;Product, long&gt; ProductRepository
    {
        get { return _ProductRepository; }
    }

    public IQueryable&lt;Product&gt; Products
    {
        get { return _ProductRepository.GetAll(); }
    }

    public async Task&lt;Product&gt; CreateProduct(Product input)
    {
        var result = await _ProductRepository.InsertAsync(input);
        await _unitOfWorkManager.Current.SaveChangesAsync();
        return result;
    }

    #endregion
}
</code></pre></li>
</ol>

<p>It will throw error this line:</p>

<pre><code>await _adManager.Ads.Where(p =&gt; p.Name == input.Name).FirstOrDefaultAsync();
</code></pre>

<p>But if I use this instead, it will work:</p>

<pre><code>await _adManager.AdRepository.FirstOrDefaultAsync(p =&gt; p.Name == input.Name);
</code></pre>

<p>In addition, I get <code>_unitOfWorkManager.Current</code> as <code>null</code> in the above code.<br>
Is there any suggestion?</p>
",https://stackoverflow.com/questions/49822204/unit-testing-for-idomainservice-with-asp-net-boilerplate,"['c#', 'dbcontext', 'unit-of-work', 'aspnetboilerplate', 'objectdisposedexception']",1651,TRUE,0,2
Unit testing http requests to rest api,"<p>I have a C# library that gets data from public api.
trying to get into TDD and was wondering how to unit test a library that the main focus of it is to get data from the server and convert the json to .net objects. (Basically handling the http requests along with limiting and error handling and some configuration settings)<br>
I know you should mock some sort of database but not sure how exactly. And i've read that the tests should run all the time even with internet connection off.</p>
",https://stackoverflow.com/questions/52197284/unit-testing-http-requests-to-rest-api,"['c#', 'unit-testing', 'http']",202,FALSE,0,1
"problem with Unit Testing : promises , apollo server","<p>I have a problem with unit testing promises, I'm using apollo server and MongoDB as database 
this is an example of tests.</p>

<pre class=""lang-js prettyprint-override""><code>it('Should return ""Yacine"" as user', done =&gt; {
  User.getUserByUserName({ username: 'Yacine' }).then(function(result) {
    expect(result).to.equal(User.findOne({ username: 'Yacine' }));
  });
  done();
});
</code></pre>

<p>that returns</p>

<pre><code> TypeError: Cannot read property 'username' of undefined

  36 | };
  37 |
&gt; 38 | module.exports.getUserByUserName = (root, {username}) =&gt; {
     |                                            ^
  39 |      //  console.log(username)
  40 |      return new Promise((resolve, reject) =&gt; {
  41 |              user`.
</code></pre>

<p>and this is the function that I want to test </p>

<pre class=""lang-js prettyprint-override""><code>module.exports.getUserByUserName = (root, { username }) =&gt; {
  //  console.log(username)
  return new Promise((resolve, reject) =&gt; {
    user.findOne({ username }).exec((err, res) =&gt; {
      err ? reject(err) : resolve(res);
    });
  });
};
</code></pre>
",https://stackoverflow.com/questions/52738338/problem-with-unit-testing-promises-apollo-server,"['node.js', 'mongoose', 'promise', 'jestjs', 'apollo-server']",156,FALSE,0,0
CMake file for integrated Visual Studio unit testing,"<p>Visual Studio 2017 has integrated C++ unit testing (native, google test, ctest, etc.). How can I create a CMakeLists.txt file that will create a project like this that will use the integrated IDE testing, for example using either google test or the native microsoft unit testing framework? All of Microsoft's examples unfortunately just create the project in Visual Studio, rather than starting from a CMake file. </p>

<p>Any help is appreciated, thanks!</p>
",https://stackoverflow.com/questions/53583286/cmake-file-for-integrated-visual-studio-unit-testing,"['c++', 'visual-studio', 'unit-testing', 'cmake']",6486,TRUE,7,2
Unit testing custom tableviewcell in xib file,"<p>I have a view controller class with a tableview in storyboard. In another separate xib file I have a custom table view cell with some attributes like image view, labels..etc in custom tableview cell class.</p>

<p>Now I have to write unit test case to test this custom cell and its attributes. I have tried the following,</p>

<pre><code>import XCTest
@testable import Citizens_Bank

class InvestmentTableViewCellTests: XCTestCase {

    var newsVC: NewsViewController!

    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the  invocation of each test method in the class.

    }

   func testCustomViewContainsAView() {
    let bundle = Bundle(for: NewsDetailsTableViewCell.self)
    guard let _ = bundle.loadNibNamed(""NewsDetailsTableViewCell"", owner: nil)?.first as? UIView else {
        return XCTFail(""CustomView nib did not contain a UIView"")
     }
  }

  func testCustomCell() {
     let customCell: NewsDetailsTableViewCell = accountsVC.myTableView.dequeueReusableCell(withIdentifier: ""newsDetailsCell"") as! NewsDetailsTableViewCell
    XCTAssertNotNil(customCell, ""No Custom Cell Available"")
  }
}
</code></pre>

<p>testCustomcell test case function is getting crashed with this error in console log ""fatal error: unexpectedly found nil while unwrapping an Optional value"". How can I test my custom tableview cell and its attributes? Thanks in advance. </p>
",https://stackoverflow.com/questions/51058718/unit-testing-custom-tableviewcell-in-xib-file,"['swift', 'unit-testing', 'uitableview']",1115,TRUE,0,1
Spring unit testing - Failed to load ApplicationContext,"<p>hi i'm new with unit testing and when u tried to test my spring application, i can't resolve this probleme  Failed to load application context. Can not find the path [which I specified in @ContextConfiguration]
 here my code : 
-Application context : </p>

<pre><code>@Configuration
@EnableWebMvc
@ComponentScan(""com.RealEstate"")
@Import(ApplicationContext.class)
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(final ResourceHandlerRegistry registry) {
        registry.addResourceHandler(""/images/**"")
                .addResourceLocations(""classpath:/images/"").setCachePeriod(31556926);
        registry.addResourceHandler(""/Resources/**"")
                .addResourceLocations(""/Resources/"").setCachePeriod(31556926);
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer){
        configurer.enable();
    }

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry){
        InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
        internalResourceViewResolver.setViewClass(JstlView.class);
        internalResourceViewResolver.setPrefix(""/WEB-INF/views/"");
        internalResourceViewResolver.setSuffix("".jsp"");
        registry.viewResolver(internalResourceViewResolver);
    }

}
</code></pre>

<p>and here's my test class : </p>

<pre><code>@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration(classes = { WebConfig.class})
public class CustomerDaoImplTest {

    @Autowired
    CustomerDao customerDao;

    @BeforeClass
    public static void setUp(){
        // MockitoAnnotations.initMocks(customerDao);
    }

    @Test
    public void findById(){
        //Assert.assertNotNull(adminDao.readAdminById(1));
        //Assert.assertNull(adminDao.readAdminById(3));
        Assert.assertNull(null);
    }

    @Test
    public void saveCustomer(){
        //customerDao.storeCustomer(getSampleCustomer());
        //Assert.assertEquals(customerDao.getCustomersList().size(), 7);
        Assert.assertEquals(5+2, 7);
    }

    @Test
    public void deleteCustomer(){
        customerDao.deleteCustomer(""customer1"");
        Assert.assertEquals(customerDao.getCustomersList().size(), 5);
    }

    @Test
    public void deleteEmployeeByInvalidSsn(){
        customerDao.deleteCustomer(""23423"");
        Assert.assertEquals(customerDao.getCustomersList().size(), 6);
    }

    @Test
    public void findAllEmployees(){
        Assert.assertEquals(customerDao.getCustomersList().size(), 6);
    }

    @Test
    public void findEmployeeByUsername(){
        Assert.assertNotNull(customerDao.readCustomerByUsername(""overflow""));
        Assert.assertNull(customerDao.readCustomerByUsername(""paul""));
    }

    public Customer getSampleCustomer(){
        Customer customer = new Customer();
        customer.setId(7);
        customer.setName(""ihab"");
        customer.setLastName(""benamer"");
        customer.setEmail(""benamer@gmail.com"");
        customer.setUsername(""ihab"");
        try{
            customer.setBirthday(new java.sql.Date(new SimpleDateFormat(""yyyy-MM-dd"").parse(""1996-11-10"").getTime()));
        } catch (java.text.ParseException e){
            ;
        }
        customer.setIdNumber(""987521"");
        customer.setAddress(""consantine, algérie"");
        customer.setPassword(""123"");
        customer.setPhone(""+213557665392"");
        customer.setSex(""male"");
        return customer;
    }

}
</code></pre>

<p>I have a structure like this:
java
  |com.RealEstate
     |config
     |dao
     |model
     |service
     |controller
test
  |com.RealEstate
     |config
     |dao</p>

<pre><code>here's the error slack 
    saveAdmin(com.RealEstate.dao.AdminDaoImplTest)  Time elapsed: 0 sec  &lt;&lt;&lt; ERROR!
java.lang.NullPointerException
    at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.detectHandlerMethods(AbstractHandlerMethodMapping.java:227)
    at org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder$StaticRequestMappingHandlerMapping.registerHandlers(StandaloneMockMvcBuilder.java:480)
    at org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder.registerMvcSingletons(StandaloneMockMvcBuilder.java:346)
    at org.springframework.test.web.servlet.setup.StandaloneMockMvcBuilder.initWebAppContext(StandaloneMockMvcBuilder.java:331)
    at org.springframework.test.web.servlet.setup.AbstractMockMvcBuilder.build(AbstractMockMvcBuilder.java:127)
    at com.RealEstate.dao.AdminDaoImplTest.setUp(AdminDaoImplTest.java:66)
    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)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    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.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
    at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
    at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
    at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
</code></pre>
",https://stackoverflow.com/questions/50317565/spring-unit-testing-failed-to-load-applicationcontext,"['java', 'spring', 'junit']",218,FALSE,0,0
before each() error in enzyme unit testing,"<p>I'm writing a test using enzyme for react application. When I tried to write a test for a component under several layers, <code>before each()</code> error comes up.</p>

<p>In the terminal, it says <code>✖ ""before each"" hook for ""Tests Logout component rendering""</code></p>

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

<pre><code>import React from 'react'
import { shallow } from 'enzyme'
import Logout from 'components/Navbar/Logout'

describe('(Component) Logout', () =&gt; {
  let _wrapper

  const render = () =&gt; {
    _wrapper = shallow( &lt;Logout /&gt; )
  }

  beforeEach(() =&gt; {
    render()
  })

  it('Tests Logout component rendering', () =&gt; {
    expect(_wrapper.find('.logout').length).to.equal(1)
    expect(_wrapper.find('div').length).to.equal(1)
    expect(_wrapper.find('i').length).to.equal(1)
  })
})
</code></pre>

<p>I don't receive any error for another component which a single layers like <code>components/Input</code>. How can I fix this issue?</p>

<p>Thank you.</p>
",https://stackoverflow.com/questions/48260591/before-each-error-in-enzyme-unit-testing,"['reactjs', 'testing', 'enzyme']",542,FALSE,0,0
Unit-testing Web API IHttpActionResponse status codes,"<p>I am working on a unit test project to test Web API v2 with <code>IHttpActionResponse</code> as return type.</p>

<p>I am not able to find out a way to test all the status codes with <code>IHttpActionResponse</code> return type. Especially post need to test http status code created. Here I created some of the tests for <code>Get</code> and <code>GetById</code> also. Let me know how we can test all the status codes returning <code>IHttpActionResponse</code>.</p>

<p>API controller code</p>

<pre><code>public class StudentController : ApiController
{
    IRepository&lt;Student&gt; repository;
    ITransformers&lt;StudentModel, Student&gt; transformer;

    public StudentController(IRepository&lt;Student&gt; studentRepository, ITransformers&lt;StudentModel, Student&gt; studentTransformer)
    {
        repository = studentRepository;
        transformer = studentTransformer;
    }

    [HttpGet]
    public IHttpActionResult Get()
    {
        IEnumerable&lt;Student&gt; students = null;

        try
        {
            students = repository.Get();

            if (students.Count&lt;Student&gt;() &gt; 0)
            {
                return Ok(students);
            }
            else
            {
                return StatusCode(HttpStatusCode.NoContent);
                //return Content(HttpStatusCode.NoContent, students);
            }
        }
        catch (Exception ex)
        {
            return InternalServerError(ex);
        }
    }

    [HttpGet]
    public IHttpActionResult Get(int Id)
    {
        Student student = null;

        try
        {
            student = repository.GetById(Id);

            if (student != null)
            {
                return Ok(student);
            }
            else
            {
                return NotFound();
            }
        }
        catch (Exception ex)
        {
            return InternalServerError(ex);
        }
    }

    [HttpPost]
    public IHttpActionResult Post(StudentModel studentModel)
    {
        try
        {
            Student student = transformer.TransformModelToEntity(studentModel);
            int result = repository.Save(student);

            if (result &gt; 0)
            {
                student.Id = result;
                return Content(HttpStatusCode.Created, student);
            }
            else
            {
                return InternalServerError();
            }
        }
        catch (Exception ex)
        {
            return InternalServerError(ex);
        }
    }

    [HttpPut]
    public IHttpActionResult Put(StudentModel studentModel)
    {
        try
        {
            Student student = transformer.TransformModelToEntity(studentModel);

            if (repository.Update(student))
            {
                return Content(HttpStatusCode.Accepted, studentModel);
            }
            else
            {
                return NotFound();
            }
        }
        catch (Exception ex)
        {
            return InternalServerError(ex);
        }
    }

    [HttpDelete]
    public IHttpActionResult Delete(int Id)
    {
        try
        {
            if(repository.Delete(Id))
            {
                return Ok();
            }
            else
            {
                return NotFound();
            }
        }
        catch (Exception ex)
        {
            return InternalServerError(ex);
        }
    }
}
</code></pre>

<p>My test class code</p>

<pre><code>[TestClass]
public class StudentServiceTest
{
    static Mock&lt;ITransformers&lt;StudentModel, Student&gt;&gt; mockTransformer;
    static Mock&lt;IRepository&lt;Student&gt;&gt; mockRepository;

    [ClassInitialize]
    public static void ClassInit(TestContext context)
    {
        mockTransformer = new Mock&lt;ITransformers&lt;StudentModel, Student&gt;&gt;();
        mockRepository = new Mock&lt;IRepository&lt;Student&gt;&gt;();
    }

    //GetAll Tests
    [TestMethod]
    public void GetReturnsAllStudents()
    {
        // Arrange
        IEnumerable&lt;Student&gt; fakeStudents = GetFakeStudents();
        mockRepository.Setup(x =&gt; x.Get()).Returns(fakeStudents);
        var controller = new StudentController(mockRepository.Object, mockTransformer.Object);

        // Act
        IHttpActionResult actionResult = controller.Get();
        var contentResult = actionResult as OkNegotiatedContentResult&lt;IEnumerable&lt;Student&gt;&gt;;

        // Assert
        Assert.IsNotNull(contentResult);
        Assert.IsNotNull(contentResult.Content);
        Assert.IsInstanceOfType(contentResult, typeof(OkResult));
        Assert.AreEqual(3, contentResult.Content.Count());
    }

    [TestMethod]
    public void GetReturnsNoContent()
    {
        // Arrange
        var controller = new StudentController(mockRepository.Object, mockTransformer.Object);

        // Act
        IHttpActionResult actionResult = controller.Get();
        StatusCodeResult statusCodeResult = actionResult as StatusCodeResult;

        //Assert
        Assert.IsNotNull(statusCodeResult);
        Assert.AreEqual&lt;HttpStatusCode&gt;(HttpStatusCode.NoContent, statusCodeResult.StatusCode);
    }

    [TestMethod]
    public void GetReturnsException()
    {
        // Arrange
        mockRepository.Setup(x =&gt; x.Get()).Throws&lt;Exception&gt;();
        var controller = new StudentController(mockRepository.Object, mockTransformer.Object);

        // Act
        IHttpActionResult actionResult = controller.Get();

        //Assert
        Assert.IsNotNull(actionResult);
        Assert.IsInstanceOfType(actionResult, typeof(ExceptionResult));
    }
    //End of tests GetAll

    //GetById Tests
    [TestMethod]
    public void GetByIdReturnsStudent()
    {
        // Arrange
        IEnumerable&lt;Student&gt; fakeStudents = GetFakeStudents();
        mockRepository.Setup(x =&gt; x.GetById(It.IsAny&lt;int&gt;())).Returns(fakeStudents.FirstOrDefault());
        var controller = new StudentController(mockRepository.Object, mockTransformer.Object);

        // Act
        IHttpActionResult actionResult = controller.Get(It.IsAny&lt;int&gt;());
        var contentResult = actionResult as OkNegotiatedContentResult&lt;Student&gt;;

        // Assert
        Assert.IsNotNull(contentResult);
        Assert.IsNotNull(contentResult.Content);
        Assert.AreEqual(1, contentResult.Content.Id);
    }

    [TestMethod]
    public void GetByIdReturnsNotFound()
    {
        // Arrange
        Student student = null;
        mockRepository.Setup(x =&gt; x.GetById(It.IsAny&lt;int&gt;())).Returns(student);
        var controller = new StudentController(mockRepository.Object, mockTransformer.Object);

        // Act
        IHttpActionResult actionResult = controller.Get(It.IsAny&lt;int&gt;());

        // Assert
        Assert.IsNotNull(actionResult);
        Assert.IsInstanceOfType(actionResult, typeof(NotFoundResult));
    }

    [TestMethod]
    public void GetByIdReturnsException()
    {
        // Arrange
        mockRepository.Setup(x =&gt; x.Get()).Throws&lt;Exception&gt;();
        var controller = new StudentController(mockRepository.Object, mockTransformer.Object);

        // Act
        IHttpActionResult actionResult = controller.Get(It.IsAny&lt;int&gt;());

        //Assert
        Assert.IsNotNull(actionResult);
        Assert.IsInstanceOfType(actionResult, typeof(ExceptionResult));
    }
    //End of GetById tests
}
</code></pre>

<p>Testing post for checking status code 201</p>

<pre><code>[TestMethod]     
public void PostReturnsSuccess()
{
        // Arrange
        mockRepository.Setup(x =&gt; x.Save(It.IsAny&lt;Student&gt;())).Returns(1);
        mockTransformer.Setup(x =&gt; x.TransformModelToEntity(It.IsAny&lt;StudentModel&gt;())).Returns(GetFakeStudents().FirstOrDefault());
        var controller = new StudentController(mockRepository.Object, mockTransformer.Object);

        // Act
        IHttpActionResult actionResult = controller.Post(It.IsAny&lt;StudentModel&gt;());
        var createdResult = actionResult as CreatedNegotiatedContentResult&lt;Student&gt;;
        //var createdResult = actionResult as CreatedAtRouteNegotiatedContentResult&lt;Student&gt;;

        //Assert
        Assert.IsNotNull(actionResult);
        Assert.IsNotNull(createdResult.Content);
        Assert.AreEqual(1, createdResult.Content.Id);
}
</code></pre>

<p>Tried to use <code>CreatedNegotiatedContentResult</code> and <code>CreatedAtRouteNegotiatedContentResult</code> and compare the status codes but my <code>actionResult</code> has exceptions for Formatters, ContentNegotiation and Request Properties and gets a null object in <code>createdResult</code>.</p>

<p>Let me know how to check for the status code 201?</p>

<p>Updated for mocking BadRequest from CustomFilter</p>

<p>Modelstatevalidationfilter </p>

<pre><code>   public class ModelStateValidationFilter : ActionFilterAttribute
        {
            public override void OnActionExecuting(HttpActionContext actionContext)
            {
                if (!actionContext.ModelState.IsValid)
                {
                    actionContext.Response = actionContext.Request.CreateErrorResponse(
                        HttpStatusCode.BadRequest, actionContext.ModelState);
                }
            }
        }
</code></pre>

<p>Test Method for BadRequest</p>

<pre><code>[TestMethod]
        public void PostReturnsBadRequest()
        {
            // Arrange
            //var mockFilter = new Mock&lt;ModelStateValidationFilter&gt;().Setup(x=&gt;x.OnActionExecuting(It.IsAny&lt;HttpActionContext&gt;()))
            var controller = new StudentController(mockRepository.Object, mockTransformer.Object);

            // Act
            IHttpActionResult actionResult = controller.Post(new StudentModel { Id = 0, FirstName = ""Raju"", LastName = """", CourseId = 0 });
            var badResult = actionResult as NegotiatedContentResult&lt;Student&gt;;

            //Assert
            Assert.IsNotNull(actionResult);
            Assert.IsInstanceOfType(actionResult, typeof(BadRequestErrorMessageResult));
            //TODO: Check for status code bad request and 
            Assert.IsNotNull(badResult.Content);
            Assert.AreEqual(HttpStatusCode.Created, badResult.StatusCode);
        }
</code></pre>

<p>where in model lastname is required so API is returning BadRequest. But how to mock this behaviour in unit test?</p>
",https://stackoverflow.com/questions/50313151/unit-testing-web-api-ihttpactionresponse-status-codes,"['c#', 'unit-testing', 'asp.net-web-api2', 'moq', 'mstest']",9143,TRUE,0,1
Unit testing: try statement in program.cs Main,"<p>I have my project that starts like below. I want to create a unit test to validate what happens when either <code>appsetting.Environment.json</code> doesn't exist or the <code>DataSource:JsonPath</code> file doesn't exist.  </p>

<p>I am using xUnit but just getting into it,</p>

<p>With this scenario it should throw a <code>FileNotFoundException</code> and exit.</p>

<pre><code>internal class Program
{
    private static int Main(string[] args)
    {
        public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile($""appsettings.{Environment.GetEnvironmentVariable(""ENVIRONMENT"") ?? ""Production""}.json"", optional: true)
            .Build();

        try
        {
            Log.Information($""{DateTime.Now.ToLongTimeString()} Starting..."");

            var jsonFileName = Configuration[""DataSource:JsonPath""];
            if (!File.Exists(jsonFileName)) throw new FileNotFoundException(jsonFileName);

            //code if file exist...
        }
        catch (Exception ex)
        {
            Log.Fatal(ex, ""Terminated unexpectedly"");
            return 1;
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/52483940/unit-testing-try-statement-in-program-cs-main,"['c#', 'testing', 'program-entry-point', 'xunit']",5344,TRUE,0,2
Unit Testing typescript-react with complicated props,"<p>I have a component with rather complicated Prop typing. All is good until I need to write unit tests, where it seems like I have to re-implement some of the most complicated logics just to pass the type checking. How should I write a simple mock? Is there a better way of handling typescript here? Thanks!</p>

<pre><code>type Updater = (params: UpdaterParams) =&gt; void;
interface Props {
  // 20 props here

  getFieldUpdater: (params: GetFieldUpdater) =&gt; Updater;
}

class MyComp extends React.Component&lt;Props&gt; {
  foo() {
    const bar = this.props.getFieldUpdater(abc);
    // ...
  }
}

// MyComp.test.tsx
const mockProps = {
  // 20 mock props here
  getFieldUpdater: ???
}
it('foobar', () =&gt; {
  const mockComp = enzyme.shallow(&lt;MyComp {...mockProps} /&gt;);  // Hard to pass the checks here
});
</code></pre>
",https://stackoverflow.com/questions/53477468/unit-testing-typescript-react-with-complicated-props,"['reactjs', 'typescript', 'unit-testing', 'enzyme']",379,FALSE,0,0
Unit testing Mock request object MVC .net,"<p>Unit testing on MVC vb.net project. One of the action method in my controller, I was getting an error on <code>Request.Params[""FieldName""]</code></p>

<p>In this case, how to mock: <code>Request.Params[""FieldName""]</code> in unit test method? Prefer VB.net, and c# is accepted too. </p>

<pre><code>    Dim httpRequest = New Mock(Of System.Web.HttpRequestBase)()
    Dim httpContext = New Mock(Of System.Web.HttpContextBase)()

    Dim parameters As New NameValueCollection()
    parameters(""YourField"") = ""testField""

    httpRequest.Setup(Function(x) x.Params).Returns(parameters)
    httpContext.Setup(Function(x) x.Request).Returns(httpRequest.[Object])
</code></pre>
",https://stackoverflow.com/questions/49966885/unit-testing-mock-request-object-mvc-net,"['asp.net-mvc', 'vb.net', 'unit-testing']",582,TRUE,-1,1
Unit testing with moq and ms test,"<p>I am new to this stuff and I read about test but I can't figure it out how to test this function : </p>

<pre><code>   [Authorize(Roles = ""admin"")]
    [Route(""user/byUsername/{username}"")]
    public async Task&lt;IHttpActionResult&gt; GetUserByName(string username)
    {
        var user = await this.AppUserManager.FindByNameAsync(username);

        if (user != null)
        {
            return Ok(this.TheModelFactory.Create(user));
        }

        return NotFound();

    }
</code></pre>

<p>I want to use Moq and MS Test.Thank you.</p>
",https://stackoverflow.com/questions/52183181/unit-testing-with-moq-and-ms-test,"['c#', 'unit-testing', 'moq', 'mstest']",217,FALSE,0,1
Is unit testing always white box testing?,"<p>I've recently seen several references that indicate or mention off-hand in an article that unit testing is always white box testing.</p>

<p>Since black-box testing is simply looking at the specification or requirements for that unit, and ensuring that it meets those, without any concern for <strong><em>how</em></strong> it does so, I would at least think that unit tests <strong><em>can be</em></strong> black box tests. In fact, if you aim for ""clean code"" and ""clean architecture"", then I would think your goal would be to create only black box tests at all levels of testing.</p>

<p>If there are internal structures that need to be tested beyond black box testing, then I would argue that the specification isn't complete. Another way of saying this would be that is that if you complete your black box testing, and confirm that your unit does everything you expect/want it to do, and you don't have 100% code coverage, and have to add white box tests to get 100% coverage, then I would be very concerned about that extra code either causing side effects that don't meet the spec (maybe in edge or corner cases), or just being unnecessary and adding unneeded complexity.</p>

<p>Am I misunderstanding the meaning of white box vs. black box testing?  Is it correct to say that by definition all unit tests are white box tests?</p>
",https://stackoverflow.com/questions/52007369/is-unit-testing-always-white-box-testing,"['unit-testing', 'black-box-testing', 'white-box-testing']",43,FALSE,0,0
Rails and Rspec Unit Testing Static Methods,"<p>I have a very simple static method in one of my models:</p>

<pre><code>def self.default
    self.find(1)
end
</code></pre>

<p>I'm trying to write a simple Rspec unit test for it that doesn't make any calls to the DB. How do I write a test that generates a few sample instances for the test to return? Feel free to complete this:</p>

<pre><code>describe "".default"" do
    context ""when testing the default static method"" do
        it ""should return the instance where id = 1"" do

        end
    end
end
</code></pre>

<p>The model file is as follows:</p>

<pre><code>  class Station &lt; ApplicationRecord
  acts_as_paranoid
  acts_as_list
  nilify_blanks

  belongs_to :color
  has_many :jobs
  has_many :station_stops
  has_many :logs, -&gt; { where(applicable_class: :Station) }, foreign_key: :applicable_id
  has_many :chattels, -&gt; { where(applicable_class: :Station) }, foreign_key: :applicable_id

  delegate :name, :hex, to: :color, prefix: true

  def name
    ""#{full_display} Station""
  end

  def small_display
    display_short || code.try(:titleize)
  end

  def full_display
    display_long || small_display
  end

  def average_time
    Time.at(station_stops.closed.average(:time_lapsed)).utc.strftime(""%-M:%S"")
  end

  def self.default
    # referencing migrate/create_stations.rb default for jobs
    self.find(1)
  end

  def self.first
    self.where(code: Constant.get('station_code_to_enter_lab')).first
  end
end
</code></pre>

<p>The spec file is as follows:</p>

<pre><code>require ""rails_helper""
describe Station do

  subject { described_class.new  }

  describe ""#name"" do
    context ""when testing the name method"" do
      it ""should return the capitalized code with spaces followed by 'Station'"" do
        newStation = Station.new(code: 'back_to_school')
        result = newStation.name
        expect(result).to eq 'Back To School Station'
      end
    end
  end

  describe ""#small_display"" do
    context ""when testing the small_display method"" do
      it ""should return the capitalized code with spaces"" do
        newStation = Station.new(code: 'back_to_school')
        result = newStation.small_display
        expect(result).to eq 'Back To School'
      end
    end
  end

  describe ""#full_display"" do
    context ""when testing the full_display method"" do
      it ""should return the capitalized code with spaces"" do
        newStation = Station.new(code: 'back_to_school')
        result = newStation.full_display
        expect(result).to eq 'Back To School'
      end
    end
  end

  describe "".default"" do
    context """" do
      it """" do

      end
    end
  end

end
</code></pre>
",https://stackoverflow.com/questions/52067091/rails-and-rspec-unit-testing-static-methods,"['ruby-on-rails', 'unit-testing', 'rspec', 'tdd', 'bdd']",1783,TRUE,0,1
Django Unit Testing That Needs OAuth Authentication,"<p>I have a Django project that uses Gmail API to send bulk emails. Users can create campaign emails and send them to multiple contacts. If a contact answer to any of the emails in a campaign then that contact should no longer receive emails from that campaign email.</p>

<p>I want to add unit tests for this feature and I don't know what approach to use because I need to authorize one Gmail account first and only after that use that account to send the campaign email. Also I would like to test the replies of that campaign, which means that I need to authorize a new Gmail account that will be used to send the reply.</p>

<p>So this is what I plan to do:<br>
1. Authorize two Gmail accounts manually.
2. Inside the tests I will search for the first two Gmail accounts from the database and use one of them to send the campaign email and another one to reply to an email.</p>

<p>The only problem is that I am not sure that this approach is the best, this is why I am asking here, maybe someone has a better idea.</p>

<p>Thank you!</p>
",https://stackoverflow.com/questions/51099129/django-unit-testing-that-needs-oauth-authentication,"['django', 'python-3.x', 'unit-testing', 'python-unittest', 'django-testing']",203,FALSE,0,1
unit testing &lt;input type=&quot;file &quot; accet=&quot;image/*&quot;/&gt;,"<p>how to unit test the following code</p>

<pre><code>&lt;input type=""file "" accet=""image/*""/&gt;
</code></pre>

<p>using jasmine and  enzyme</p>

<p>i have refereed this <a href=""https://stackoverflow.com/questions/41702911/how-can-i-test-a-change-handler-for-a-file-type-input-in-react-using-jest-enzyme"">link</a> 
but here they have a plain text file, i want to test image file
how to test image file,instead of simple text file as in the above link</p>

<p>in The above referenced link they created a text file, if anyone has a solution how create a image file using blob api then my problem would be solved </p>
",https://stackoverflow.com/questions/50209199/unit-testing-input-type-file-accet-image,"['javascript', 'reactjs', 'jasmine', 'filereader', 'enzyme']",52,FALSE,0,0
Jackson Unit Testing Using Junit and Mockito,"<p>I am trying to unit test the java class which uses Jackson to parse the JSON response from rest call and mapping it to the POJO. I can successfully get the response from the rest call. But when I do unit testing using Mockito and Junit, am getting nullpointer exception. Is it possible to unit test ObjectMapper? Whether mockito work with jackson. What exactly i should do make the unit testing work.</p>

<p>I am not creating any object with new instance. If I create new object, i can understand spring will throw null pointer instance as the object is not in spring container.</p>

<p>Also, I am getting this issue when I mock the object in test class.</p>

<pre><code>package com.imosadapter.srd.main;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.trafigura.titan.imosadapter.srd.constant.ApiRequestUtility;
import com.trafigura.titan.imosadapter.srd.constant.SrdApiConstant;
import com.trafigura.titan.imosadapter.srd.model.company.Company;
import com.trafigura.titan.imosadapter.srd.model.legalentity.LegalEntity;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;
import java.util.List;

import static org.slf4j.LoggerFactory.getLogger;

public class ImosSrdSample {

    @Autowired
    private ApiRequestUtility apiRequestUtility;
    @Value(""${imos.srd.filepath}"")
    private String imosFilepath;

    private static final Logger LOG = getLogger(ImosSrdMapper.class);

    ObjectMapper objectMapper = new ObjectMapper();
    String legalEntitiesOutput = null;

    public void getSrdDetails() throws IOException {
        LOG.info(""Getting Legal Entities For Company Roles"");
        String companyRoleOutput = apiRequestUtility.srdApiCall(SrdApiConstant.COMPANIES_URL, SrdApiConstant.COMPANIES_INPUT);
        //LOG.info(""Company Role Output "" + companyRoleOutput);
        try {
            List&lt;LegalEntity&gt; legalEntities = objectMapper.reader().forType(new TypeReference&lt;List&lt;LegalEntity&gt;&gt;() {
            }).readValue(companyRoleOutput);
            for (LegalEntity legalEntity : legalEntities) {
                LOG.info(""Getting Legal Entities Information"");
                legalEntitiesOutput = apiRequestUtility.srdApiCall(SrdApiConstant.LEGALENTITIES_URL,
                        apiRequestUtility.jsonInput(legalEntity.getIdentifier(), SrdApiConstant.GUID));
                //LOG.info(""Legal Entities Output "" + legalEntitiesOutput);

                Company company = objectMapper.readValue(legalEntitiesOutput, Company.class);
            }
        } catch (IOException e) {
            LOG.error(""No File Path found. So File not generated"", e);
        }
    }
}
</code></pre>

<p>I am having a constant file which has some static fields in which I have described the base URL and the type of input which the call needs.</p>

<pre><code>package com.imosadapter.srd.constant;
import org.springframework.stereotype.Component;

@Component
public class SrdApiConstant {

    private SrdApiConstant() {
    }

    public static final String BASE_URL = ""http://localhost:9100/referencedatanew/"";
    public static final String COMPANIES_URL = ""LegalEntitiesService/GetCompanies"";
    public static final String LEGALENTITIES_URL = ""LegalEntitiesService/GetCompanyByGUID"";


    public static final String COMPANIES_INPUT = ""{\""CompanyCode\"":\""AGSHCODE\""}"";

    public static final String GUID = ""Guid"";
    public static final String LE_GUID = ""LegalEntityGUID"";
}
</code></pre>

<p>Another class for creating a input and getting a connection.</p>

<pre><code>package com.imosadapter.srd.constant;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class ApiRequestUtility {

    private static final Logger LOG = LoggerFactory.getLogger(ApiRequestUtility.class);

    public String srdApiCall(String url, String jsonInputString) throws IOException {
        String user = SrdApiConstant.USER;
        String companyOutput = null;
        StringBuffer result = new StringBuffer();
        String baseUrl = SrdApiConstant.BASE_URL + url;

        URL companyUrl = new URL(SrdApiConstant.BASE_URL + url);
        HttpURLConnection conn = (HttpURLConnection) companyUrl.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod(""POST"");
        conn.setRequestProperty(""Content-Type"", ""application/json"");
        conn.setRequestProperty(""User"", ""user"");
        OutputStream os = conn.getOutputStream();
        os.write(jsonInputString.getBytes());
        os.flush();
        if (conn.getResponseCode() != 200) {
            throw new RuntimeException(""Failed : HTTP error code : "" + conn.getResponseCode());
        }
        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
        LOG.info(""Output from Server .... \n"");
        while ((companyOutput = br.readLine()) != null) {
            result.append(companyOutput);

        }
        br.close();
        conn.disconnect();
        LOG.info(""url : "" + baseUrl);
        return result.toString();
    }

    public String jsonInput(String guid, String guidType) throws JsonProcessingException {
        String jsonString;
        ObjectMapper mapper = new ObjectMapper();
        ObjectNode srdInputJson = mapper.createObjectNode();
        if (SrdApiConstant.GUID.equalsIgnoreCase(guidType)) {
            srdInputJson.put(""Guid"", guid);
        } else if (SrdApiConstant.LE_GUID.equalsIgnoreCase(guidType)) {
            srdInputJson.put(""LegalEntityGUID"", guid);
        }
        jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(srdInputJson);
        LOG.info(""JSON String "" + jsonString);
        return jsonString;
    }
}
</code></pre>

<p>And the test class</p>

<pre><code>package com.imosadapter.srd.main;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.trafigura.titan.imosadapter.srd.constant.ApiRequestUtility;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.test.util.ReflectionTestUtils;

import javax.xml.bind.JAXBContext;

import static org.junit.Assert.*;
import static org.mockito.MockitoAnnotations.initMocks;

public class ImosSrdSampleTest {


    @InjectMocks
    private ImosSrdSample imosSrdSample;

    @Mock
    private JAXBContext jaxbContext;

    @Mock
    private ObjectMapper objectMapper;

    @Mock
    private ApiRequestUtility apiRequestUtility;

    @Before
    public void setUp() throws Exception {
        initMocks(this);
        ReflectionTestUtils.setField(imosSrdSample, ""imosFilepath"", ""src/test/resources/"");
    }

    @Test
    public void getSrdDetails() throws Exception {
        imosSrdSample.getSrdDetails();
    }

}
</code></pre>

<p>Am getting null pointer exception as the response.</p>

<pre><code>java.lang.NullPointerException
    at com.trafigura.srd.main.ImosSrdSample.getSrdDetails(ImosSrdSample.java:35)
    at com.trafigura.srd.main.ImosSrdSampleTest.getSrdDetails(ImosSrdSampleTest.java:42)
    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:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    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:51)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
</code></pre>
",https://stackoverflow.com/questions/48861850/jackson-unit-testing-using-junit-and-mockito,"['java', 'json', 'unit-testing', 'jackson', 'mockito']",44,FALSE,0,0
Unit Testing class that requires file data?,"<p>I'm working on expanding our unit test suite, and I've come across a specific class that I'm attempting to figure out how to mock. I have a method that accepts a byte[] array as a parameter. In a perfect world, this byte array will always be a PDF file that contains a form of some sort. It then extracts all of the form fields from that pdf and returns them. </p>

<p>How can I potentially mock up logic that is dependent on file data? My only real ideas are to include the pdf in the project and use IO to read the test file, or to attempt to generate a pdf form on the fly and then extract those fields.</p>

<p>Here is the code for the PDF extractor:</p>

<pre><code>public class PdfFormExtractor : IDisposable
{
    private readonly PdfReader _pdfReader;
    private readonly MemoryStream _newPdf;
    private readonly PdfStamper _pdfStamper;

    public PdfFormExtractor(byte[] pdf)
    {
        _pdfReader = new PdfReader(pdf);
        _newPdf = new MemoryStream();
        _pdfStamper = new PdfStamper(_pdfReader, _newPdf);
    }

    public FormDto ExtractForm()
    {
        var pdfFormFields = _pdfStamper.AcroFields;
        var form = new FormDto()
        {
            Fields = pdfFormFields.Fields.Select(n =&gt; new FormFieldDto
            {
                Name = n.Key,
                Label = n.Key
            }).ToList()
        };

        return form;
    }

    #region IDisposable Support
    // disposable implementation
    #endregion
}
</code></pre>
",https://stackoverflow.com/questions/53311796/unit-testing-class-that-requires-file-data,"['c#', 'unit-testing', 'mocking']",1205,TRUE,0,2
Unit testing strategy for database connection get,"<p>There's a method in the code under test, that simply tries to get database connection, or returns error if unable to. </p>

<p>It, and the structs involved are defined as follows: </p>

<pre><code>type DatabaseContext struct {
    Context
    Database DatabaseSt
}


// //GetInfo Returns the context.
// func (c *DatabaseContext) GetInfo() *Context {
//  return &amp;c.Context
// }

//GetDB Gets the database connection from the connection string.
func (c *DatabaseContext) GetDB() (*sql.DB, *errors.ErrorSt) {
    var errSt *errors.ErrorSt
    if c.Database.dbConnection == nil {
        c.Database.dbConnection, errSt = c.openDB()
        if errSt != nil {
            return nil, errSt
        }
        c.Database.dbConnection.SetMaxOpenConns(50)
    }
    return c.Database.dbConnection, nil
}
</code></pre>

<p>The other methods, in the same file, which it may hit, are as follows: </p>

<pre><code>//openDB opens the database with the connection string.
func (c *DatabaseContext) openDB() (*sql.DB, *errors.ErrorSt) {
    if c.Database.DBConnectionStr == """" {
        c.GetDatabase()
    }
    return db.OpenConnection(c.Database.DBConnectionStr, c.Database.InterpolateParams)

}

//CloseDB Closes the database.
func (c *DatabaseContext) CloseDB() {
    if c.Database.dbConnection != nil {
        c.Database.dbConnection.Close()
    }
}

//SetDatabaseString Sets the database string into the session.
func (c *DatabaseContext) SetDatabaseString(str string) {
    c.Database.DBConnectionStr = str
    i := strings.Index(str, "")/"") + 2
    c.Database.DBName = str[i:]
    c.SetDatabase()
}

//GetDatabaseString Gets the database string from the session.
func (c *DatabaseContext) GetDatabase() {
    if dbIntf := c.GetFromSession(""Database""); dbIntf != nil {
        c.Database = dbIntf.(DatabaseSt)
    }
}

//SetDatabaseString Sets the database string into the session.
func (c *DatabaseContext) SetDatabase() {
    c.SetToSession(""Database"", c.Database)
}
</code></pre>

<p>Fortunately, <code>DatabaseContext</code> implements <code>DatabaseContextIntf</code>, which I want to use for testing. My instinct is to straight up mock <code>DatabaseContext</code>, but that won't work because it's not an interface (in Golang, you can only mock interfaces). </p>

<p>How would I go about testing this, without hitting a real database, which can fail beyond my control (thus creating false fails in the test)?</p>

<p><strong>UPDATE</strong> My question differs from the suspected duplicate as their question is about database <strong>entries</strong>, and not connections. The flagged duplicate refers to <a href=""https://godoc.org/github.com/DATA-DOG/go-sqlmock"" rel=""nofollow noreferrer"">this library</a> as the answer, however, there is no method in it to return a ""connection"" that is nil, for the sake of the test. The best it has is <a href=""https://godoc.org/github.com/DATA-DOG/go-sqlmock#New"" rel=""nofollow noreferrer""><code>New</code></a> which creates a test double connection, and there's no way to control the state of the returned value (I need it to be <code>nil</code> in one test (""No Connection"") and non-nil in another (""Sanity Test""))</p>
",https://stackoverflow.com/questions/51827365/unit-testing-strategy-for-database-connection-get,"['unit-testing', 'go']",1251,FALSE,0,1
Using If Statements Instead of Unit Testing,"<p>I am a newbie in unit testing (currently learning Jest,) and I can't seem to find a particular reason to use unit testing instead of say an <code>if</code> or <code>else</code> statement binded with a <code>console.log()</code> function. An explanation would be highly appreciated. Thanks.</p>
",https://stackoverflow.com/questions/52337462/using-if-statements-instead-of-unit-testing,"['javascript', 'unit-testing', 'if-statement', 'mocha.js', 'jestjs']",122,TRUE,-1,1
Angular 5 Unit Testing Service UPDATE Method,"<p>I am using stepper back step next step and at last step when user clicks done I called a service to update user data I have tested <code>backStep()</code> and <code>nextStep()</code> methods however I want to test <code>updateAdmin()</code> method to update a boolean value. Here is my code</p>

<p>P.S: How to test a service which UPDATE data and returns the response?</p>

<p>Controller:</p>

<pre><code>backStep(step: number) {
this.currentStep = --step;
this.currentSlide.emit(this.currentStep);
}

nextStep(step: number) {
if (++step &lt;= this.totalSteps.length) {
  this.currentStep = step;
  this.currentSlide.emit(this.currentStep);
} else {
  this.updateAdmin();
 }
}

updateAdmin() {
  const body = {
   is_admin: true
  }

this.adminService.updateAdmin(user_id, body).subscribe(
  (response) =&gt; {
    console.log(response);
   }
 );
}
</code></pre>

<p>Unite Tests</p>

<pre><code>it('backStep() should decrement current step', () =&gt; {
  comp.backStep(2);
  expect(comp.currentStep).toEqual(1);
});

it('nextStep() should increment current step', () =&gt; {
  const start = 1;
  comp.totalSteps = Array.from(Array(4), (_, i) =&gt; start + i);
  comp.nextStep(1);
  expect(comp.currentStep).toEqual(2);
 });

it('Should call updateAdmin method and test mock service', () =&gt; {
  const start = 1;
  comp.totalSteps = Array.from(Array(4), (_, i) =&gt; start + i);
  comp.nextStep(4);
//when steps reached to max limit (4) I need to call a mock service which should update a field and return response, here I dont know how to test updateAdmin() method.
  });
});
</code></pre>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/48807980/angular-5-unit-testing-service-update-method,"['javascript', 'unit-testing', 'typescript', 'angular5']",616,FALSE,0,1
Unit testing http get method in component,"<p>I am new to testing and angular 5.
I have a component function which in turn calls the http get method and retuns json data.
I would like to test it.
this is my component function snippet</p>

<pre><code>this.enablebutton=false;
this.users=[];
getUsers(){
   this.http.get(url).subscribe(result=&gt;{this.users=result

     if(this.users.length&gt;0){
      this.enablebutton=true;
    }
   })
}
</code></pre>

<p>on tutorials I find they have a seperate service layer for calling the web services to fetch data like this and for which we have test cases,but I am not using any services currently.</p>

<pre><code> this.userService.getUsers().subscribe(result=&gt; this.users= result);
</code></pre>

<p>I wrote my test case as </p>

<pre><code>beforeEach(() =&gt; {

    fixture = TestBed.createComponent(AppComponent);

    component = fixture.componentInstance;
  //  spyOn(component, ""getUsers"").and.callThrough();
      component.getUsers();
    fixture.detectChanges();
  });
</code></pre>

<p>I dont know how to set the values for result from http.get call manually and test the conditions for this.enablebutton which relies on the result from the http call.
Thank you.</p>
",https://stackoverflow.com/questions/51257893/unit-testing-http-get-method-in-component,"['unit-testing', 'angular5']",150,FALSE,0,0
Unit Testing a JWT Token with Web API,"<p>I am trying to use Web API2, JWT, Microsoft.IdentityModel.JsonWebTokens 5.2.422 and the token validation logic as outlined in this article: <a href=""http://www.decatechlabs.com/secure-webapi-using-jwt"" rel=""noreferrer"">http://www.decatechlabs.com/secure-webapi-using-jwt</a></p>

<p>Everything works great for my project when I repeat the steps in the article, including testing the API via Restlet.  However, I am trying to use Test Driven Development (TDD) for this project, and I’d ideally like to test that everything works in my tests, including the token validation handler.  I am able to test my Controllers if I call them directly in my unit tests, but that is bypassing the actual token validation handler.  So, I tried using self-hosted HTTP to properly exercise the complete API, including all of the token validation handler logic.  Here is my complete unit test to get a token and then pass the token to a second method requiring authorization: </p>

<pre><code>[TestMethod]

public void GetAuthorizedStatus_SelfHostedHTTP()
{
    HttpServer server = TestAPIHelper.GenerateTestServer();

    using (HttpMessageInvoker client = new HttpMessageInvoker(server))
    {
        string token = string.Empty;

        using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, loginURL))
        {
            var stringContent = new StringContent(JsonConvert.SerializeObject(TestAPIHelper.loginObject), Encoding.UTF8, ""application/json"");
            request.Content = stringContent;

            using (HttpResponseMessage response = client.SendAsync(request, System.Threading.CancellationToken.None).Result)
            {
                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, ""Error getting token from login portion"");

                token = response.Content.ReadAsAsync&lt;string&gt;().Result;
                Assert.IsTrue(token.Length &gt; 50);
            }
        }

        using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, authorizedStatusURL))
        {
            request.Headers.Authorization = new AuthenticationHeaderValue(""Bearer"", token);

            using (HttpResponseMessage response = client.SendAsync(request, System.Threading.CancellationToken.None).Result)
            {
                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode, ""Error getting status from Authenticated portion."");
            }
        }
    };
}
</code></pre>

<p>The problem is that the TokenValidationHandler throws an ""Object reference not set to an instance of an object."" exception on the second of the below two lines of the handler, only when called by my unit test with the token attached.  If I trigger the handler using Restlet/Postman/whatever, no exception is thrown and everything works fine.  </p>

<pre><code>Thread.CurrentPrincipal = handler.ValidateToken(token, validationParameters, out securityToken);
HttpContext.Current.User = handler.ValidateToken(token, validationParameters, out securityToken);
</code></pre>

<p>I don’t understand what is causing only the second line to error when the first, nearly identical line works - both lines call the same method.  And I don’t understand why it works with third party software but doesn’t work with my test code - my concern is that if I don't figure this out for unit testing, then I won't get the code working for the real application calling this api.  I assume it is either some trivial setting in my test code that I need to add to my request before submitting.  But perhaps I need to architect a completely different method of calling the API in my unit tests.  </p>
",https://stackoverflow.com/questions/51353294/unit-testing-a-jwt-token-with-web-api,"['c#', 'unit-testing', 'asp.net-web-api2', 'jwt', 'tdd']",7872,FALSE,7,1
Disable spring boot starter Cassandra for unit testing,"<p>I need to use Cassandra in a project with the following gradle dependecy:</p>

<pre><code>compile ""org.springframework.boot:spring-boot-starter-data-cassandra""
</code></pre>

<p>The problem is that although Cassandra AutoConfiguration classes are marked to be excluded from a unit test, Somehow spring still tries to instantiate classes related to this dependancy.</p>

<p>Here is my unit test:</p>

<pre><code>import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
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.MockMvcResultMatchers;

@RunWith( SpringRunner.class )
@SpringBootTest
@AutoConfigureMockMvc
@EnableAutoConfiguration( exclude = {
        org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration.class,
        org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration.class
} )
public class HealthTest {

    @Autowired
    private MockMvc mockMvc;


    @Test
    public void contextLoads() {
        Assert.assertNotNull( mockMvc );
    }

    @Test
    public void healthControllerIsUp() throws Exception {
        mockMvc.perform( MockMvcRequestBuilders.get( ""/health"" ) )
                .andExpect( MockMvcResultMatchers.status().isOk() );
    }
}
</code></pre>

<p>and this is the error I get, apparently because Spring cannot instantiate <strong>cluster</strong> object.</p>

<pre><code>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.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: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: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cluster' defined in class path resource [org/springframework/boot/autoconfigure/cassandra/CassandraAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.datastax.driver.core.Cluster]: Factory method 'cluster' threw exception; nested exception is java.lang.NoClassDefFoundError: com/google/common/util/concurrent/FutureFallback
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
    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:867)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
    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)
    ... 24 more
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.datastax.driver.core.Cluster]: Factory method 'cluster' threw exception; nested exception is java.lang.NoClassDefFoundError: com/google/common/util/concurrent/FutureFallback
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
    ... 41 more
Caused by: java.lang.NoClassDefFoundError: com/google/common/util/concurrent/FutureFallback
    at org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration.cluster(CassandraAutoConfiguration.java:66)
    at org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration$$EnhancerBySpringCGLIB$$7c58ae77.CGLIB$cluster$0(&lt;generated&gt;)
    at org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration$$EnhancerBySpringCGLIB$$7c58ae77$$FastClassBySpringCGLIB$$fb4ab05b.invoke(&lt;generated&gt;)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358)
    at org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration$$EnhancerBySpringCGLIB$$7c58ae77.cluster(&lt;generated&gt;)
    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.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
    ... 42 more
Caused by: java.lang.ClassNotFoundException: com.google.common.util.concurrent.FutureFallback
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:338)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 53 more
</code></pre>

<p>Looking into <strong>CassandraAutoConfiguration</strong> class, This class is annotated as following: </p>

<pre><code>@Configuration
@ConditionalOnClass({ Cluster.class })
@EnableConfigurationProperties(CassandraProperties.class)
public class CassandraAutoConfiguration
</code></pre>

<p>I am looking for a clean way how to get around this without having to configure Cassandra on each test that has nothing to do with Cassandra.</p>
",https://stackoverflow.com/questions/49006037/disable-spring-boot-starter-cassandra-for-unit-testing,"['spring-boot', 'cassandra', 'spring-data-cassandra', 'spring-mvc-test', 'spring-boot-starter']",3321,FALSE,6,1
Unit testing classes with mocked repository dependecies,"<p>I have a service class with several methods. Service has some dependencies on repositories. I am using Moq to mock the repository. I have a problem with the proper unit testing one of the methods. I will give you an example:</p>

<pre><code>public interface IRepository&lt;T&gt;
{
    IEnumerable&lt;T&gt; FindAll();
    IEnumerable&lt;T&gt; FindByQuery(Predicate&lt;T&gt; predicate);
    //many other methods for retreiving T's
}

public class MyService
{
    private readonly IRepository&lt;Category&gt; _repo;

    public MyService(IRepository&lt;Category&gt; repo)
    {
        _repo = repo;
    }

    public List&lt;Category&gt; FindActiveCategories()
    {
        return _repo.FindAll().Where(x =&gt; x.Active).ToList();
    }
}
</code></pre>

<p>Now, I wrote a unit test:</p>

<pre><code>public FindActiveCategories_WhenCalled_ShouldReturnActiveCategories() {
   var moq = new Mock&lt;IRepository&lt;Category&gt;&gt;();
   var list = new List&lt;Category&gt;
   {
       new Category {Active = true},
       new Category {Active = false}
   };
   moq.Setup(x =&gt; x.FindAll()).Returns(list);
   var service = new MyService(moq.Object);
   var result = service.FindActiveCategories();

   Assert.IsTrue(result.All(x=&gt;x.Active));
}
</code></pre>

<p>And the test of course passed. But than I realized that I retreived all the Categories in my service method using FindAll - it was an obvious thing to correct, because I didn't want to load several thousands of categories to memory just to pull out only few of them. So I changed the implementation of FindActiveCategories method to this:</p>

<pre><code>public List&lt;Category&gt; FindActiveCategories()
{
    return _repo.FindByQuery(x =&gt; x.Active).ToList();
}
</code></pre>

<p>And my test failed this time. The problems is obvious - the test depended on the implementation details. I knew that the FindActiveCategories method uses FindAll method of the repository, so I wrote a setup for this method. After changing the implementation I have to change the implementation of the test method - this seems to be a problem. Of course I could've setup all the Find... methods but there are plenty of them in the repository and one can choose many of them, this also doesn't seem right approach for me. Not to mention TDD - if I was trying to write the test first, I wouldn't know what and how to mock the repository interface. My question is: what is a correct way to handle this kind of dependencies to be able to write implementation independent unit tests.</p>
",https://stackoverflow.com/questions/48426018/unit-testing-classes-with-mocked-repository-dependecies,"['c#', 'unit-testing', 'mocking', 'repository', 'moq']",631,TRUE,0,2
"Unit testing with Vue, Typescript and Karma","<p>I tried to adapt the <a href=""https://v2.vuejs.org/v2/guide/unit-testing.html"" rel=""nofollow noreferrer"">Vue unit testing guide</a>, but got stuck at the first hurdle.  <code>Property 'created' does not exist on type 'VueConstructor&lt;Vue&gt;'</code>.</p>
<p>Here's my test, just to verify that my component does in fact have a <code>created</code> hook:</p>
<pre><code>import {assert} from 'chai';
import MyComponent from '../src/components/MyComponent.vue';

it('has a created hook', function() {
    assert.equal(typeof MyComponent.created, 'function');
});
</code></pre>
<p>Here's my component under test, <code>MyComponent.vue</code>:</p>
<pre><code>&lt;template&gt;
&lt;/template&gt;

&lt;script lang=&quot;ts&quot;&gt;
export default Vue.extend({
    created() {
        console.log(&quot;bye&quot;);
    }
});
&lt;/script&gt;
</code></pre>
<p>This test should now pass.  However, I get an error from the Typescript compiler.</p>
<pre><code>$ karma start --single-run
15 02 2018 14:06:17.345:INFO [compiler.karma-typescript]: Compiling project using Typescript 2.6.2
15 02 2018 14:06:18.905:ERROR [compiler.karma-typescript]: test/vue_test.ts(5,37): error TS2339: Property 'created' does not exist on type 'VueConstructor&lt;Vue&gt;'.
</code></pre>
<p>I am using a file <code>vue-shims.d.ts</code>, which is as such:</p>
<pre><code>declare module &quot;*.vue&quot; {
    import Vue from &quot;vue&quot;;
    export default Vue;
}
</code></pre>
",https://stackoverflow.com/questions/48809244/unit-testing-with-vue-typescript-and-karma,"['javascript', 'typescript', 'vue.js', 'karma-runner']",937,TRUE,0,2
Catch Vue.js warnings for unit testing required properties,"<p>We are porting a very large project into Vue.js and would like to thoroughly implement our unit testing suite as we go.</p>

<p>We would like to validate that components are having all their required properties set at creation, my test case looks something like:</p>

<pre><code>describe('Input', () =&gt; {
  it('fail initialization with no value', () =&gt; {
    const vm = mount(Input, {
      propsData: {},
    });

    // expecting above to fail due to required prop 'value'
  });
});
</code></pre>

<p>The component <code>Input</code> is expected to contain a property <code>value</code>. I can see via the console warning emitted that it is missing but we would like to catch this in our unit tests. Directly testing this doesn't make much sense but once we have components nesting several components, making sure that each component correctly initialises its sub components is important and this is achieved by assuring ourselves that the above test should fail and be caught failing.</p>

<p>There is no exception raised however, we have had ideas to hook into the <code>Vue.warnHandler</code> but this just seems like a lot of work for simply confirming that a constructor works as expected.</p>

<p>Is there a recommended approach to doing this with Vue.js?</p>
",https://stackoverflow.com/questions/50821524/catch-vue-js-warnings-for-unit-testing-required-properties,"['javascript', 'vue.js', 'jestjs', 'mocha.js', 'vue-test-utils']",1553,TRUE,6,1
Kotlin Unit testing - How to mock component of Companion object?,"<p>If I have a (simplified) class that looks like this:</p>

<pre><code>class MyManager @JvmOverloads constructor(/*constructor args*/) : MyManagerInterface {

    @Inject
    lateinit var myLogger: MyLogger

    init {
        component = DaggerLoggerComponent.builder()
                .loggerModule(LoggerModule(internalLogger))
                .build()

        component.inject(this)
    }

    companion object {
        lateinit var component: RemoteLoggerComponent
            private set
    }
}
</code></pre>

<p>When unit testing, how on earth do I mock the component in the companion object?</p>

<p>I've tried all kinds of tricks using Mockito, MockK etc but I come up against several obstacles.</p>

<p>The CUT (class-under-test) is another class that is using the MyManager component to inject its dependencies in its init block like so:</p>

<pre><code>init {
        if(applicationContext == null) {
            throw IllegalStateException(""Application Context must not be null"")
        } else {

            MyManager.component.inject(this)
        }
    }
</code></pre>

<p>Basically, I'd be happy if the injection does nothing because I can set the dependencies externally for the sake of testing.</p>

<p>All help appreciated.  Including if you think I'm coding this wrong.  I'm relatively new to Kotlin and Dagger.  Thanks.</p>
",https://stackoverflow.com/questions/51792130/kotlin-unit-testing-how-to-mock-component-of-companion-object,"['kotlin', 'mockk']",16055,TRUE,19,2
Unit Testing window.location.assign using Karma/Mocha/Sinon/Chai,"<p>I am attempting to unit test a function using Karma as my test runner, Mocha as my testing framework, Sinon as my mocking/stubbing/spying library, and Chai as my assertion library. I am using Chromium as my headless browser in my Karma configuration.</p>

<p>I am totally baffled, however, as to why I am getting the following error:</p>

<pre><code>TypeError: Cannot redefine property: assign
</code></pre>

<p>...when I run npm test on this:</p>

<pre><code>function routeToNewPlace() {  
  const newLoc = ""/accountcenter/content/ac.html"";
  window.location.assign(newLoc);
}
describe('tests', function() {
  before('blah', function() {
    beforeEach('test1', function() {
          window.onbeforeunload = () =&gt; '';
      });
    });
  it('routeToNewPlace should route to new place', function() {
    expectedPathname = ""/accountcenter/content/ac.html"";
    routeToNewPlace();
    const stub = sinon.stub(window.location, 'assign'); 
    assert.equal(true, stub.withArgs(expectedUrl).calledOnce);
    stub.restore();
  });
});
</code></pre>

<p>As you can see, I am attempting to assign an empty string to window.location, but this doesn't seem to help.</p>

<p>Here is my karma.config.js:</p>

<pre><code>module.exports = function(config) {
    config.set({
      frameworks: ['mocha', 'chai', 'sinon'],
      files: ['jstests/**/*.js'],
      reporters: ['progress'],
      port: 9876,  // karma web server port
      colors: true,
      logLevel: config.LOG_INFO,
      //browsers: ['Chrome', 'ChromeHeadless', 'MyHeadlessChrome'],
      browsers: ['ChromeHeadless'],
      customLaunchers: {
        MyHeadlessChrome: {
          base: 'ChromeHeadless',
          flags: ['--disable-translate', '--disable-extensions', '--remote-debugging-port=9223']
        }
      },
      autoWatch: false,
      // singleRun: false, // Karma captures browsers, runs the tests and exits
      concurrency: Infinity
    })
  }
</code></pre>

<p>Any thoughts would be greatly appreciated.</p>
",https://stackoverflow.com/questions/52068740/unit-testing-window-location-assign-using-karma-mocha-sinon-chai,"['unit-testing', 'mocha.js', 'karma-runner', 'sinon', 'chai']",3876,TRUE,6,2
Unit Testing a Static Method of a Static Class,"<pre><code>public static class ApplicationUtils
{
   public static bool IsCurrentUserAManager()
        {
            var username = WindowsIdentity.GetCurrent().Name;

            bool inAdmin;

            if (username == ""AdminUser"") {
               inAdmin = true;
            } else {
               inAdmin = false;
            }

            return inAdmin;
        }
  }
</code></pre>

<p>Above is some code that is used to test if the currently logged in user is an Admin, I want to unit test this section by passing in a different username and test if the result is correct.</p>

<p>I have heard that dependency injection would be the best way to do this. But I have no idea how to dependency inject into a static class and a static method.</p>

<p>Can anyone help me fill out the TestMethod below in order to pass in a username and test the method?
(<strong>Not using enterprise</strong>)</p>

<pre><code>[TestMethod]
public void IsCurrentUserAManagerTestIsAdmin()
{

}
</code></pre>
",https://stackoverflow.com/questions/49318062/unit-testing-a-static-method-of-a-static-class,"['c#', 'unit-testing']",39776,TRUE,13,4
"Unit Testing in Angular, Test Component is undefined","<p>I am trying to unit test a ""add object"" (add dish) component in Angular 6. With my current code I get the error <strong>""Cannot read property 'dishForm' of undefined"".</strong> </p>

<p>So, it seems it does the DishAddComponent is not recognized as the component to be tested? Can anybody help me out with this? Thanks in advance!</p>

<p>I've also tried (amongst others) adding async to beforeEach, as described here: <a href=""https://stackoverflow.com/questions/40039789/angular-2-testing-component-instance-is-undefined"">Angular 2 Testing - Component Instance is undefined</a> , but it does not work.</p>

<p>Angular Component to be Unit Tested:</p>

<pre><code>export class DishAddComponent implements OnInit {
  public dishForm: FormGroup;

  constructor(private dishService: DishService,
    private formBuilder: FormBuilder,
    private router: Router) { }

  ngOnInit() {
    // define dishForm (with empty default values)
    this.dishForm = this.formBuilder.group({
      name: ['', [Validators.required, Validators.maxLength(30), Validators.pattern('[a-zA-Z :]*')]],
      country: [''],
      ingredients: this.formBuilder.array([]),
      recipe: ['', [Validators.required, Validators.minLength(50)]],
    }, { validator: CustomValidators.DishNameEqualsCountryValidator });
  }

  addIngredient(): void {
    let ingredientsFormArray = this.dishForm.get('ingredients') as FormArray;
    ingredientsFormArray.push(IngredientSingleComponent.createIngredient());
  }

  addDish(): void {
    if (this.dishForm.dirty &amp;&amp; this.dishForm.valid) {

      let dish = this.dishForm.value;

      this.dishService.addDish(dish)
        .subscribe(
          () =&gt; {
            this.router.navigateByUrl('/dishes');
          });
    }
  }
}
</code></pre>

<p>Unit Test in Jest:</p>

<pre><code>describe('DishAddComponent', () =&gt; {
  let component: DishAddComponent;
  let fixture: ComponentFixture&lt;DishAddComponent&gt;;
  let formGroup: FormGroup;
  let formBuilderMock: any;
  let dishServiceMock: any;

  beforeEach(() =&gt; {
      formBuilderMock = {
      group: jest.fn().mockName('formBuilderMock.group'),
      array: jest.fn().mockName('formBuilderMock.array')
    };

    dishServiceMock = {
      addDish: jest.fn().mockName('dishServiceMock.addDish')
    };

    TestBed.configureTestingModule({
      imports: [ ReactiveFormsModule, FormsModule, RouterTestingModule.withRoutes(routes)],
      declarations: [ DishAddComponent, IngredientSingleComponent ],
      providers: 
      [ 
        { provide: FormBuilder, useValue: formBuilderMock },
        { provide: FormGroup, useValue: formGroup },
        { provide: DishService, useValue: dishServiceMock }
      ]
    });
    fixture = TestBed.createComponent(DishAddComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('form invalid when empty', () =&gt; {
    (console).log(component);
  expect(component.dishForm.valid).toBeFalsy();
 });
});
</code></pre>

<p><strong>EDIT:</strong>
If I use the code below, I get an error as well:</p>

<p>DishAddComponent › should create  </p>

<p>expect(received).toBeTruthy()   </p>

<p>Received: undefined</p>

<pre><code>  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
</code></pre>
",https://stackoverflow.com/questions/52927304/unit-testing-in-angular-test-component-is-undefined,"['angular', 'unit-testing', 'undefined']",20674,TRUE,5,2
CMake for integrated Microsoft Unit Testing Framework (VS2017),"<p>Similar to my previous question but specifically for the Microsoft Unit Testing Framework:</p>

<p>Visual Studio 2017 has integrated C++ unit testing (MS unit testing, google test, etc.). How can I create a CMakeLists.txt file that will create a project like this that will use the integrated IDE testing, specifically using the Microsoft Unit Testing Framework?</p>

<p>Thank you!</p>
",https://stackoverflow.com/questions/53709197/cmake-for-integrated-microsoft-unit-testing-framework-vs2017,"['visual-studio', 'unit-testing', 'cmake']",2119,TRUE,5,1
Unit testing of styled-components with SVG imports,"<p>I am in the process of upgrading the dependencies of a React project. I upgraded styled-components from <code>1.4.4</code> to <code>2.5.0-1</code>. I didn't expect any breaking changes since I read that styled-components v2 is a drop-in replacement for v1. </p>

<p>I don't see any breaking changes in the web app, but my test cases are broken. </p>

<p>Consider the following, dumb and useless test. </p>

<pre><code>test('does something', () =&gt; {
  expect(true).toBe(true);
});
</code></pre>

<p>As expected, the test works. However, as soon as I even try to import a styled-component in the test file, it fails. </p>

<p>I added the following import.</p>

<pre><code>import {Container} from './styled';
</code></pre>

<p>The Container styled-component is defined thus:</p>

<pre><code>export const Container = styled.div`
  width: 80%;
  display: flex;
  flex-direction: column;
  transition: opacity 0.25s ease-in-out;
`;
</code></pre>

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

<pre><code>Cannot create styled-component for component: [object Object]
</code></pre>

<p>Right now, I fail to understand what's going on. Why can't I import a styled-component?</p>

<p><strong>EDIT</strong></p>

<p>The problem was with styled-components that import svg assets. See answer below.</p>
",https://stackoverflow.com/questions/48640647/unit-testing-of-styled-components-with-svg-imports,"['javascript', 'reactjs', 'jestjs', 'styled-components']",3255,TRUE,4,1
Unit Testing JsonResult anonymous type in .Net Core,"<p><strong>UPdated: Solution at bottom</strong></p>

<p>In .net core JsonResult does not have a ""Data"" property.
Many of the existing answers us that property to retrieve the needed values for unit testing.</p>

<p>I can't seem to wrap my head around the problem here:</p>

<pre><code>        public async Task&lt;IActionResult&gt; GetIndividualPerformanceMetrics(string npi)
    {
        var metrics = new List&lt;PhysicianMetric&gt;();
        var overallRank = new OverallPhysicianRank();
        var userNPI = User.GetSingleClaimValueByType(Constants.ClaimTypes.Npi);
        npi = string.IsNullOrWhiteSpace(npi) ? userNPI : npi;
        if (npi != null)
        {

            if (await _authorizationService.AuthorizeAsync(User, ""IsMetricSupportTeam"")
                || User.GetAllClaimsByType(Constants.ClaimTypes.Npi).Any(n =&gt; n.Value == npi))
            {
                metrics = (await _physicianMetrics.GetAllByNPIAsync(npi)).ToList();
            }
        }
        return Json(new { metrics });
    }
</code></pre>

<p>And in my unit test I'm doing the following:</p>

<pre><code>            _physicianMetrics.Setup(pm =&gt; pm.GetAllByNPIAsync(validNPI))
            .ReturnsAsync(new List&lt;PhysicianMetric&gt;(){_physicianMetric});

        var anonymousDefinition = new { metrics = new List&lt;PhysicianMetric&gt;() };

        //Act
        var result = await (performanceMetricsController.GetIndividualPerformanceMetrics(validNPI)) as JsonResult;
        var obj = JsonConvert.DeserializeAnonymousType(result.Value.ToString(), anonymousDefinition);
        //Assert
        Assert.AreEqual(validNPI, obj.metrics[0].NPI);
</code></pre>

<p>The JsonResult is returning with the mocked repository values, but I can't seem to write the test so that I can ensure the JsonResult data is the data returned by the repository query. The deserialization fails with the following error:</p>

<p>""Invalid character after parsing property name. Expected ':' but got: =. Path '', line 1, position 10. ""</p>

<p>I just need to validate the JsonResult values.</p>

<p>Please Help.</p>

<p><strong>Solution</strong>:  (Thanks Chris Pratt)</p>

<p>I didn't realize that the JsonResult had not yet serialized the object, and that the JsonResult.Value was the pure anonymous type.  I just used reflection to call out the list of objects that I needed and was good to go:</p>

<pre><code>        var result = await (performanceMetricsController.GetIndividualPerformanceMetrics(validNPI)) as JsonResult;
        var metrics = result.Value.GetType().GetProperty(""metrics"")?.GetValue(result.Value, null) as List&lt;PhysicianMetric&gt;;

        //Assert
        _physicianMetrics.Verify(pm =&gt; pm.GetAllByNPIAsync(validNPI), Times.Once);
        Assert.AreEqual(validNPI, metrics[0]?.NPI);
</code></pre>
",https://stackoverflow.com/questions/50932790/unit-testing-jsonresult-anonymous-type-in-net-core,"['c#', 'unit-testing', 'asp.net-core', 'jsonresult']",1502,FALSE,4,0
Angular 6 unit testing a http get request,"<p>I have a component where I have a request in a function like:</p>

<pre><code>getData():Observable&lt;any&gt;{
    return this._http.get('/app/data', {observe: 'response'});
}
</code></pre>

<p>It returns me an object array in subscription like:</p>

<pre><code>[{name: 'a'}, {name: 'b'}]
</code></pre>

<p>or something similar.</p>

<p>I wanted to write a test that makes sure getData() calls http GET once with the proper url and the subscription returns something array-like.</p>

<p>My code:</p>

<pre><code>...
    it('getData() should http GET names', () =&gt; {
        inject([HttpTestingController], (httpMock: HttpTestingController) =&gt; {

          const names = [{name: 'a'}, {name: 'b'}];

          component.getData().subscribe((res) =&gt; {
            expect(res).toEqual(names);
          });

          const req = httpMock.expectOne('/app/data');
          expect(req.request.method).toEqual(""GET"");
          req.flush(names);

          httpMock.verify();
        });
      });
...
</code></pre>

<p>I failed the test with this message: ""Expected no open requests, found 1: GET /app/data""</p>
",https://stackoverflow.com/questions/52817272/angular-6-unit-testing-a-http-get-request,"['angular', 'unit-testing']",17795,TRUE,4,1
Unit testing conformance to Decodable using a SingleValueDecodingContainer,"<p>So, I have a type which looks like this:</p>

<pre><code>struct Identifier {
    let string: String
}

extension Identifier: Decodable {
    public init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        string = try container.decode(String.self)
    }
}
</code></pre>

<p>The point with this type is if I have JSON that looks like this:</p>

<pre><code>{
    ""identifier"": ""abc123"",
    // more properties ...
}
</code></pre>

<p>... it will automatically be serialized to the correct type without much effort. However, I'm having trouble unit testing this conformance to <code>Decodable</code> without creating a wrapping type.</p>

<p>What I want to do is something like this:</p>

<pre><code>func testDecodableInit() {
    let identifier = try! JSONDecoder().decode(Identifier.self, from: ""1"".data(using: .utf8)!)
    XCTAssertEqual(identifier.string, ""1"")
}
</code></pre>

<p>But obviously this doesn't work because <code>""1""</code> is not valid JSON.</p>

<p>Is it possible to write a unit test for this conformance to <code>Decodable</code> without creating a wrapping type and changing the data to valid JSON?</p>
",https://stackoverflow.com/questions/50237898/unit-testing-conformance-to-decodable-using-a-singlevaluedecodingcontainer,"['swift', 'unit-testing', 'codable', 'decodable']",4668,TRUE,4,3
Unit testing with final classes of AWS SDK,"<p>I have written following code to publish some metrics around AWS Step function (its java lambda for aws)</p>

<pre><code>@Override
public void handleRequest(InputStream input, OutputStream output, Context context) throws IOException {
    int inProgressStateMachines = 0;

    LocalDateTime now = LocalDateTime.now();

    long alarmThreshold = getAlarmThreshold(input, context.getLogger());

    AWSStepFunctions awsStepFunctions = AWSStepFunctionsClientBuilder.standard().build();

    ListStateMachinesRequest listStateMachinesRequest = new ListStateMachinesRequest();
    ListStateMachinesResult listStateMachinesResult = awsStepFunctions.listStateMachines(listStateMachinesRequest);

    for (StateMachineListItem stateMachineListItem : listStateMachinesResult.getStateMachines()) {

        ListExecutionsRequest listExecutionRequest = new ListExecutionsRequest()
                .withStateMachineArn(stateMachineListItem.getStateMachineArn())
                .withStatusFilter(ExecutionStatus.RUNNING);

        ListExecutionsResult listExecutionsResult = awsStepFunctions.listExecutions(listExecutionRequest);

        for (ExecutionListItem executionListItem : listExecutionsResult.getExecutions()) {

            LocalDateTime stateMachineStartTime = LocalDateTime.ofInstant(
                    executionListItem.getStartDate().toInstant(), ZoneId.systemDefault());

            long elapsedTime = ChronoUnit.SECONDS.between(stateMachineStartTime, now);

            if (elapsedTime &gt; alarmThreshold){
                inProgressStateMachines++;
            }
        }

        publishMetrics(inProgressStateMachines);
    }
}
</code></pre>

<p>Now I am trying to unit-test this method and having some issues. </p>

<p>First of all, I get error that <code>Mockito can not mock final class</code> when i tried to mock <code>AWSStepFunctionsClientBuilder</code>. </p>

<p>Secondly, I have private methods which are being called with specific params. </p>

<p>The question is</p>

<ol>
<li><p>How can i unit test this code? I read it somewhere that if a code isn't unit-testable then its a bad design. How can i improve this code so that its easily testable? I would prefer to keep those helper methods as <code>private</code> methods.</p></li>
<li><p>How can i mock <code>final</code> objects from <code>AWS SDK</code> to test this code? I can not use any other framework but <code>Mockito</code>. </p></li>
</ol>
",https://stackoverflow.com/questions/48304385/unit-testing-with-final-classes-of-aws-sdk,"['java', 'unit-testing', 'amazon-web-services', 'mockito', 'aws-lambda']",1884,TRUE,3,1
Jasmine unit testing observable subscribe does not trigger,"<p>I'm using Angular 5 with Jasmine and Karma. I'm trying to test whether a certain function works but my subscribe doesn't trigger during unit testing. this causes my unit test to fail as I'm using the done function of jasmine.
I want to make this unit test succeed.</p>

<p>I've set the timeout interval to 20 seconds to see if it just took a while (which it shouldn't).</p>

<p>I've tried to use async and fakeasync as well, but it doesn't trigger. Is it possible for me to make the subscription to trigger?</p>

<p>this is the code ive got:</p>

<pre><code>describe('FilterService', () =&gt; {
  let service: FilterService;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      providers: [FilterService]
    });
    service = TestBed.get(FilterService);
    jasmine.DEFAULT_TIMEOUT_INTERVAL = 20000;
  });

  it(""SetItemsToFilterByAndApplyFilters should set ItemsToFilterBy and set the InFilter property"", (done: DoneFn) =&gt; {
    //arrange
    let item1: any = new Organisation();
    item1.Id = 1;
    item1.InFilter = true;
    let item2: any = new Organisation();
    item1.Id = 2;
    item1.InFilter = false;

    let itemNew1: any = new Organisation();
    itemNew1.Id = 1;
    let itemNew2: any = new Organisation();
    itemNew2.Id = 2;

    service.SetItemsToFilterBy([item1, item2]);
    let spy = spyOn(service.ItemsToFilterBy$, 'subscribe');

    //act
    service.SetItemsToFilterByAndApplyFilters([itemNew1, itemNew2]);
    //assert
    service.ItemsToFilterBy$.subscribe(result =&gt; {
      let result1 = _.find(result, item =&gt; {
        return item.Id == itemNew1.Id;
      });

      let result2 = _.find(result, item =&gt; {
        return item.Id == itemNew2.Id;
      });

      expect(result1.InFilter).toBeTruthy();
      expect(result2.InFilter).toBeFalsy();
      done();
    });
  });
});
</code></pre>

<p>this is the code that worked with thanks to Basavaraj Bhusani</p>

<pre><code>      it(""SetItemsToFilterByAndApplyFilters should set ItemsToFilterBy and set the InFilter property"", (done: DoneFn) =&gt; {

    //arrange
    let spy = spyOn(service.ItemsToFilterBy$, 'subscribe').and.callThrough();

    let item1: any = new Organisation();
    item1.Id = 1;
    item1.InFilter = true;
    let item2: any = new Organisation();
    item2.Id = 2;
    item2.InFilter = false;

    let itemNew1: any = new Organisation();
    itemNew1.Id = 1;
    let itemNew2: any = new Organisation();
    itemNew2.Id = 2;

    service.SetItemsToFilterBy([item1, item2]);

    //act
    service.SetItemsToFilterByAndApplyFilters([itemNew1, itemNew2]);

    //assert
    service.ItemsToFilterBy$.subscribe(result =&gt; {
      let result1 = _.find(result, item =&gt; {
        return item.Id == itemNew1.Id;
      });

      let result2 = _.find(result, item =&gt; {
        return item.Id == itemNew2.Id;
      });

      expect(result1.InFilter).toBeTruthy();
      expect(result2.InFilter).toBeFalsy();
      done();
    });
    expect(spy).toHaveBeenCalled();
  });
});
</code></pre>
",https://stackoverflow.com/questions/49426466/jasmine-unit-testing-observable-subscribe-does-not-trigger,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",11104,TRUE,3,1
How to trigger unit testing from Laravel Artisan,"<p>I have a situation where i have some unit tests with PHPUnit, and i want to trigger them from the artisan console utility of laravel. I have googled and i have not found any reference, Is it possible?  I am not asking how to test artisan commands. or how to dynamically call another artisan command, but to trigger unit tests from artisan</p>

<p>I can call certain commands using Artisan facade like</p>

<pre><code>Artisan::call('migrate'); //which calls migration
</code></pre>

<p>like this is there a way i can call unit tests? I am using PHPUnit </p>
",https://stackoverflow.com/questions/48734840/how-to-trigger-unit-testing-from-laravel-artisan,"['php', 'laravel', 'unit-testing']",602,TRUE,3,2
Creating a mock data object for unit testing,"<p>Currently I'm trying to unit test a function that takes in a parameter that is a data object:</p>

<pre><code>addColor(_ coreDataManagerContext: NSManagedObjectContext, _ object: Color?) {//code here}
</code></pre>

<p>The issue is that it takes in an object: <code>Color?</code> that needs to be mocked.
Here is what the original <code>Color</code> model looks like, it's parsed in Swift 4 :</p>

<pre><code>class Color: Codable {

    var id: String
    var name: String


    enum CodingKeys: String, CodingKey {
        case id = ""Id""
        case name = ""Name""

    }
}
</code></pre>

<p>I thought about doing something like this:</p>

<pre><code>class mockColorObject: Color {

   self.name = ""red""//error here
}
</code></pre>

<p>but get the error: ""expected declaration""</p>
",https://stackoverflow.com/questions/48347150/creating-a-mock-data-object-for-unit-testing,"['ios', 'swift', 'unit-testing', 'codable']",1715,TRUE,3,1
Unit testing ViewModel property bound to ReactiveCommand IsExecuting,"<p>I'm new to ReactiveUI and am following the example set out <a href=""https://reactiveui.net/docs/getting-started/"" rel=""nofollow noreferrer"">here</a>, and unit testing as I go.</p>

<p>As expected, the sample code works perfectly, but my unit test which asserts that the <code>SpinnerVisibility</code> property changes as expected when the <code>IsExecuting</code> property of my <code>ReactiveCommand</code> changes, does not.</p>

<p>As per the sample, I have properties on my view model for a spinner visibility and a command to execute a search:</p>

<pre><code>public Visibility SpinnerVisibility =&gt; _spinnerVisibility.Value;

public ReactiveCommand&lt;string, List&lt;FlickrPhoto&gt;&gt; ExecuteSearch { get; protected set; }
</code></pre>

<p>And in the view model constructor I set up the <code>ExecuteSearch</code> command and <code>SpinnerVisibility</code> is set to change when the command is executing:</p>

<pre><code>public AppViewModel(IGetPhotos photosProvider)
{
    ExecuteSearch = ReactiveCommand.CreateFromTask&lt;string, List&lt;FlickrPhoto&gt;&gt;(photosProvider.FromFlickr);

    this.WhenAnyValue(search =&gt; search.SearchTerm)
        .Throttle(TimeSpan.FromMilliseconds(800), RxApp.MainThreadScheduler)
        .Select(searchTerm =&gt; searchTerm?.Trim())
        .DistinctUntilChanged()
        .Where(searchTerm =&gt; !string.IsNullOrWhiteSpace(searchTerm))
        .InvokeCommand(ExecuteSearch);

    _spinnerVisibility = ExecuteSearch.IsExecuting
        .Select(state =&gt; state ? Visibility.Visible : Visibility.Collapsed)
        .ToProperty(this, model =&gt; model.SpinnerVisibility, Visibility.Hidden);
}
</code></pre>

<p>My initial attempt was to directly invoke the command:</p>

<pre><code>[Test]
public void SpinnerVisibility_ShouldChangeWhenCommandIsExecuting()
{
    var photosProvider = A.Fake&lt;IGetPhotos&gt;();
    var fixture = new AppViewModel(photosProvider);

    fixture.ExecuteSearch.Execute().Subscribe(_ =&gt;
    {
        fixture.SpinnerVisibility.Should().Be(Visibility.Visible);
    });

    fixture.SpinnerVisibility.Should().Be(Visibility.Collapsed);
}
</code></pre>

<p>This did result in the <code>state =&gt; state ? Visibility.Visible : Visibility.Collapsed</code> lambda being executed, but the subsequent assertion fails as for some reason <code>SpinnerVisibility</code> is still <code>Collapsed</code>.</p>

<p>My next attempt was to indirectly invoke the command by emulating a search using <code>TestScheduler</code>:</p>

<pre><code>[Test]
public void SpinnerVisibility_ShouldChangeWhenCommandIsExecuting()
{
    new TestScheduler().With(scheduler =&gt;
    {
        var photosProvider = A.Fake&lt;IGetPhotos&gt;();
        var fixture = new AppViewModel(photosProvider);

        A.CallTo(() =&gt; photosProvider.FromFlickr(A&lt;string&gt;.Ignored)).ReturnsLazily(
            () =&gt; new List&lt;FlickrPhoto&gt; { new FlickrPhoto { Description = ""a thing"", Title = ""Thing"", Url = ""https://thing.com"" } });

        fixture.SearchTerm = ""foo"";
        scheduler.AdvanceByMs(801); // search is throttled by 800ms
        fixture.SpinnerVisibility.Should().Be(Visibility.Visible);
    });
}
</code></pre>

<p>As before, the lambda executes, <code>state</code> is <code>true</code> but then instantly re-executes, with <code>state</code> back to <code>false</code>, presumably because, being mocked, <code>photosProvider.FromFlickr</code> would return instantly (unlike retrieving images from the API normally), which would then mean the command was no longer executing.</p>

<p>I then came across Paul Bett's response to <a href=""https://stackoverflow.com/questions/15047124/reactiveui-testing-progress-indicator-visibility-while-reactiveasynccommand-exe"">a similar question</a>, and added an <code>Observable.Interval</code> to my mock:</p>

<pre><code>A.CallTo(() =&gt; photosProvider.FromFlickr(A&lt;string&gt;.Ignored)).ReturnsLazily(
                    () =&gt;
                    {
                        Observable.Interval(TimeSpan.FromMilliseconds(500), scheduler);
                        return new List&lt;FlickrPhoto&gt; {new FlickrPhoto {Description = ""a thing"", Title = ""Thing"", Url = ""https://thing.com""}};
                    });
</code></pre>

<p>and the corresponding test changes:</p>

<pre><code>scheduler.AdvanceByMs(501);
fixture.SpinnerVisibility.Should().Be(Visibility.Collapsed);
</code></pre>

<p>This had no effect.</p>

<p>Finally, I awaited the <code>Interval</code>:</p>

<pre><code>A.CallTo(() =&gt; photosProvider.FromFlickr(A&lt;string&gt;.Ignored)).ReturnsLazily(async
                    () =&gt;
                    {
                        await Observable.Interval(TimeSpan.FromMilliseconds(500), scheduler);
                        return new List&lt;FlickrPhoto&gt; {new FlickrPhoto {Description = ""a thing"", Title = ""Thing"", Url = ""https://thing.com""}};
                    });
</code></pre>

<p>This allowed the <code>fixture.SpinnerVisibility.Should().Be(Visibility.Visible)</code> assertion to pass, but now regardless how far I advance the scheduler, the mocked method never seems to return and so the subsequent assertion fails.</p>

<p>Is this approach using <code>TestScheduler</code> correct/advised? If so, what am I missing? If not, how should this type of behaviour be tested?</p>
",https://stackoverflow.com/questions/49338867/unit-testing-viewmodel-property-bound-to-reactivecommand-isexecuting,"['c#', 'unit-testing', 'system.reactive']",743,TRUE,3,1
Unit testing text output (stdout.write/print) in Dart,"<p>I am looking for a way in the Dart programming language to redirect the 
output from stdout, into a ""Something"", that I can call .toString() on, and get
anything printed on stdout as String. This is useful for unit tests.</p>

<p>Currently I wrap stdout in my Display class, and store the text for one call and verify that stdout's write is
used. See also my side note below, how it can be done in Java.</p>

<pre><code>import 'dart:io';

import 'package:mockito/mockito.dart';
import 'package:test/test.dart';

class Display {
  IOSink output;
  String lastTextPrinted;

  Display(IOSink output) {
    this.output = output;
  }

  void myPrint(String text) {
    lastTextPrinted = text;
    output.write(text);
  }
}

main() {
  test('prints hello world', () {
    Display display = new Display(stdout);
    display.myPrint(""Hello world!"");
    expect(""Hello world!"", display.lastTextPrinted);
  });

  test('myPrint calls ioSinks write', () {
    MockIOSink ioSink = new MockIOSink();
    Display display = Display(ioSink);
    display.myPrint(""Hello world!"");

    verify(ioSink.write(""Hello world!""));
  });
}

class MockIOSink extends Mock implements IOSink {}
</code></pre>

<p>Sidenote: In Java with JUnit 4 I used something similar to this:</p>

<p>There System.out is a PrintStream and I can assign my own Stream to it, for instance ByteArrayOutPutStream.
The latter has a .toString method I can call to verify its content against.</p>

<pre><code>@Test
public void testMyMessageToDisplay() throws Exception
{
 ByteArrayOutputStream canvas = new ByteArrayOutputStream();
 System.setOut(new PrintStream(canvas);

 new Display().displayMyMessage(""Hello world!"");

 Assert.assertEquals(""Hello World!"", canvas.toString(""UTF-8""));
}

public static class Display {
    public void displayMyMessage(String myMessage) {
        System.out.println(myMessage);
    }
}
</code></pre>
",https://stackoverflow.com/questions/51465222/unit-testing-text-output-stdout-write-print-in-dart,"['unit-testing', 'dart']",1485,TRUE,3,1
Difference with unit testing controller and service method,"<p>I wanted to test same method from controller and service layer. The question is: Why do I have to use <code>@MockBean</code> annotation in controller, why not <code>@Mock</code> annotation for <code>BookFindOperationsService bookService</code>. Same question for service, why do I need to <code>@Mock</code> repository, why not to use <code>@MockBean</code>? Could you give me difference between these two?</p>

<p>Here is controller:</p>

<pre><code>@RestController
public class BookFindOperationsController {

    private final BookFindOperationsService bookService;

    @Autowired
    public BookFindOperationsController(BookFindOperationsService bookService) {
        this.bookService = bookService;
    }

    @GetMapping(""/books/author/{authorID}"")
    public List&lt;Book&gt; findBooksByAuthor(@PathVariable String authorID) {
        return bookService.findBooksByAuthor(authorID);
    }

}
</code></pre>

<p>Here is service class:</p>

<pre><code>@Service
public class BookFindOperationsService {
    private final BookRepository bookRepository;

    @Autowired
    public BookFindOperationsService(BookRepository bookRepository) {
        this.bookRepository = bookRepository;
    }

    public List&lt;Book&gt; findBooksByAuthor(String authorID) {
        return bookRepository.findByAuthorAllIgnoreCase(authorID);
    }
}
</code></pre>

<p>Service test:</p>

<pre><code>@RunWith(MockitoJUnitRunner.class)
public class BookFindOperationsServiceTest {

    @Mock
    BookRepository bookRepository;

    @InjectMocks
    BookFindOperationsService bookFindOperationsService;

    @Test
    public void findBooksByAuthor() {
        Book book = createDummyBook();
        List&lt;Book&gt; books = new ArrayList&lt;&gt;();
        books.add(book);

        when(bookRepository.findByAuthorAllIgnoreCase(""Henryk Sienkiewicz"")).thenReturn(books);

        assertEquals(1, bookFindOperationsService.findBooksByAuthor(""Henryk Sienkiewicz"").size());
    }

private Book createDummyBook() {
        return new Book(""W pustyni i w puszczy"", ""Henryk Sienkiewicz"", ""dramat"", true);
    }
</code></pre>

<p>Controller test:</p>

<pre><code>@RunWith(SpringRunner.class)
@WebMvcTest(BookFindOperationsController.class)
public class BookFindOperationsControllerTest {
    @Autowired
    MockMvc mockMvc;

    @MockBean
    BookFindOperationsService bookService;

    @Test
    public void findBooksByAuthor() throws Exception {
        List&lt;Book&gt; books = new ArrayList&lt;&gt;();
        Book book = new Book(""W pustyni i w puszczy"", ""Henryk Sienkiewicz"", ""dramat"", true);
        books.add(book);

        when(bookService.findBooksByAuthor(""Henryk Sienkiewicz"")).thenReturn(books);

        String expected = ""[{\""id\"":0,\""title\"":\""W pustyni i w puszczy\"",\""author\"":\""Henryk Sienkiewicz\"",\""category\"":\""dramat\"",\""available\"":true}]"";

        MvcResult mvcResult = mockMvc.perform(get(""/books/author/Henryk Sienkiewicz"")
                .contentType(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
                .andReturn();

        String content = mvcResult.getResponse().getContentAsString();

        assertEquals(expected, content);

        verify(bookService, times(1)).findBooksByAuthor(anyString());
    }
</code></pre>
",https://stackoverflow.com/questions/53776659/difference-with-unit-testing-controller-and-service-method,"['java', 'spring', 'unit-testing', 'spring-boot', 'mockmvc']",1924,TRUE,3,2
python unit testing for my password validation code,"<p>I have this functional code:</p>

<pre><code>class PasswordChecker(object):

 passwords = [""aD23""]

 def check(self, passwords):
     if not passwords:
         raise NameError('You have not entered any password')
     else:
         pass
</code></pre>

<p>And this test code:</p>

<pre><code>import unittest

from app.passwordchecker import PasswordChecker

class TestPasswordChecker(unittest.TestCase):
  def setUp(self):
    self.pswd = PasswordChecker()

  def test_password_checker_raises_nameerror_for_noargs(self):
    self.assertRaises(NameError, self.pswd.check, [])
</code></pre>

<p>I expect that when the test is made to fail by replacing <code>[]</code> with <code>[items]</code> in <code>self.assertRaises()</code>, it should throw a <code>NameError - You have not entered any password</code>. However, it throws a different error meaning my code has a problem. Please help</p>
",https://stackoverflow.com/questions/52374267/python-unit-testing-for-my-password-validation-code,"['python', 'python-3.x', 'unit-testing', 'tdd']",1248,TRUE,2,1
Jest unit testing config with Quasar-Framework 0.15,"<p>I had Jest tests working under Quasar version 0.14. Currently some simple tests and all snapshot-tests pass but for some tests I keep getting:
1.</p>

<pre><code>console.error node_modules/vue/dist/vue.common.js:593
      [Vue warn]: Error in config.errorHandler: ""TypeError: Cannot read property 'form' of undefined""
</code></pre>

<p>and 2:</p>

<pre><code>console.error node_modules/vue/dist/vue.common.js:1743
      TypeError: Cannot read property 'getters' of undefined
</code></pre>

<p>and 3:</p>

<pre><code>console.error node_modules/vue/dist/vue.common.js:593
  [Vue warn]: Unknown custom element: &lt;q-page-sticky&gt; - did you register the component correctly? For recursive components, make sure to provide the ""name"" option.
</code></pre>

<p>1 and 2 seem to relate to Jest not recognizing a $v.form and the vuex store within the components.</p>

<p>Any suggestions/ best practices how to get this working? I followed along <a href=""http://forum.quasar-framework.org/topic/1864/0-15-1-components-registering-within-jest-tests"" rel=""nofollow noreferrer"">this</a>, and have these settings:
.babelrc:</p>

<pre><code>{
  ""presets"": [
    [ ""env"", {""modules"": false} ],
    ""stage-2""
  ],
  ""plugins"": [""transform-runtime""],
  ""comments"": false,
  ""env"": {
    ""test"": {
      ""presets"": [
        [
          ""env"",
          {
            ""targets"": {
              ""node"": ""current""
            }
          }
        ]
      ],
      ""plugins"": [
        [
          ""module-resolver"",
          {
            ""root"": [
              ""./src""
            ],
            ""alias"": {
              ""quasar"": ""quasar-framework/dist/quasar.mat.esm.js"",
              ""^vue$"": ""vue/dist/vue.common.js""
            }
          }
        ]
      ]
    }
  }
}
</code></pre>

<p>within package.json:</p>

<pre><code>  ""jest"": {
    ""testMatch"": [
      ""&lt;rootDir&gt;/src/**/?(*.)(spec).js?(x)""
    ],
    ""testPathIgnorePatterns"": [
      ""&lt;rootDir&gt;/src/e2e/""
    ],
    ""moduleNameMapper"": {
      ""src/components/([^\\.]*).vue$"": ""&lt;rootDir&gt;/src/components/$1.vue"",
      ""src/components/([^\\.]*)$"": ""&lt;rootDir&gt;/src/components/$1.js"",
      ""^vue$"": ""vue/dist/vue.common.js"",
      ""src/([^\\.]*)$"": ""&lt;rootDir&gt;/src/$1.js"",
      ""src/([^\\.]*).vue$"": ""&lt;rootDir&gt;/src/$1.vue"",
      ""(.*)/(.*).vue$"": ""$1/$2.vue"",
      ""(.*)/(.*)/(.*).vue$"": ""$1/$2/$3.vue""
    },
    ""moduleFileExtensions"": [
      ""js"",
      ""json"",
      ""vue""
    ],
    ""collectCoverageFrom"": [
      ""**/*.{vue}""
    ],
    ""coverageDirectory"": ""&lt;rootDir&gt;/src/components/coverage"",
    ""transformIgnorePatterns"": [
      ""node_modules/core-js"",
      ""node_modules/babel-runtime"",
      ""node_modules/lodash"",
      ""node_modules/vue""
    ],
    ""transform"": {
      ""^.+\\.js$"": ""&lt;rootDir&gt;/node_modules/babel-jest"",
      "".*\\.(vue)$"": ""&lt;rootDir&gt;/node_modules/vue-jest""
    },
    ""snapshotSerializers"": [
      ""&lt;rootDir&gt;/node_modules/jest-serializer-vue""
    ]
  },
</code></pre>
",https://stackoverflow.com/questions/49616642/jest-unit-testing-config-with-quasar-framework-0-15,"['javascript', 'vue.js', 'jestjs', 'babel-jest', 'quasar-framework']",2128,TRUE,2,2
Unit Testing a Basic c# application with repository,"<p>I have a basic .NET application that I am being asked to write a unit test for, but unit tests have always confused me.</p>

<p>This application has two repositories (FoodRepository and DrinkRepository) that return data from a hardcoded list.</p>

<p>Here's the Program.cs:</p>

<pre><code>public static void Main(string[] args)
    {
        var foodSvc = new FoodService();
        var foodId = 12;
        var grade = 98.2d;
        foodSvc.UpdateFoodGrade(foodId, grade);
    }
</code></pre>

<p>which calls:</p>

<pre><code>public void UpdateFoodGrade(int foodId, double grade)
    {
        var foodRepo = new FoodRepository();
        var food = foodRepo.GetFood(foodId);

        food.Grade = grade;

        if (!food.IsPassed)
        {
            var drinkRepository = new DrinkRepository();
            var drink = drinkRepository.GetDrink(foodId);

            if (grade &gt;= drink.MinimumPassingGrade)
            {
                food.IsPassed = true;
            }
            else
            {
                food.IsPassed = false;
            }
        }
    }
</code></pre>

<p>My question is, what unit test(s) typically would someone do here for this? And, can I get some examples?</p>

<p>Been googling and grinding on this, but the concept continues to escape me.</p>

<p>I've historically used full integration tests in test environments, and not really done unit tests.</p>

<p>If anyone needs more of the code to help with this please let me know. I'm super stuck.</p>

<p>Thanks</p>

<p>UPDATE:</p>

<p>I've gotten a lot further thanks to below, but I am still stuck on the rest of the test. Here's what my updated service looks like:</p>

<pre><code>public class FoodService
{
    private readonly FoodRepository _foodRepo;
    private readonly DrinkRepository _drinkRepository;

    public FoodService(FoodRepository foodRepo, DrinkRepository drinkRepository)
    {
        _foodRepo = foodRepo;
        _drinkRepository = drinkRepository;
    }

    public void UpdateFoodGrade(int foodId, double grade)
    {
        var food = _foodRepo.GetFood(foodId);

        food.Grade = grade;

        if (!food.IsPassed)
        {
            var drink = _drinkRepository.GetDrink(foodId);

            if (grade &gt;= drink.MinimumPassingGrade)
            {
                food.IsPassed = true;
            }
            else
            {
                food.IsPassed = false;
            }
        }
    }
}
</code></pre>

<p>Updated Main:</p>

<pre><code>public class Program
{
    public static void Main(string[] args)
    {
        var foodRepository = new FoodRepository();
        var drinkRepository = new DrinkRepository();
        var foodSvc = new FoodService(foodRepository, drinkRepository);

        var foodId = 12;
        var grade = 98.2d;

        foodSvc.UpdateFoodGrade(foodId, grade);
    }
}
</code></pre>

<p>Test So far (I have no idea what to do next)</p>

<pre><code>[TestMethod]
    public void UpdateFoodGrade_Test()
    {
        //Arrange
        var foodId = 12;
        var grade = 98.2d;           
        var expected = true;

        var food = new Food() { FoodId = foodId };
        var drink = new Drink() { DrinkId = foodId };

        var foodRepositoryMock = new Mock&lt;FoodRepository&gt;();
        foodRepositoryMock.Setup(m =&gt; m.GetFood(foodId)).Returns(food).Verifiable();

        var drinkRepositoryMock = new Mock&lt;DrinkRepository&gt;();
        drinkRepositoryMock.Setup(m =&gt; m.GetDrink(foodId)).Returns(drink).Verifiable();

        var foodService = new FoodService(foodRepositoryMock.Object, drinkRepositoryMock.Object);

        //Act
        var actual = foodService.UpdateFoodGrade(foodId, grade);

        //Assert
        foodRepositoryMock.Verify();
        drinkRepositoryMock.Verify();
        Assert.AreEqual(expected, actual);
    }
}
</code></pre>

<p>EDIT 2:</p>

<p>I went ahead and refactored in the interfaces, etc. Here's how it shook out:</p>

<pre><code>[TestMethod]
    public void UpdateLessonGrade_IsPassingGrade()
    {
        //Arrange
        var lessonId = 12;

        var lesson = new Lesson() { LessonId = lessonId };
        var module = new Module() { ModuleId = lessonId };

        var lessonRepositoryMock = new Mock&lt;ILessonRepository&gt;();
        lessonRepositoryMock.Setup(x =&gt; x.GetLesson(lessonId)).Returns(lesson);

        var moduleRepositoryMock = new Mock&lt;IModuleRepository&gt;();
        moduleRepositoryMock.Setup(x =&gt; x.GetModule(lessonId)).Returns(module);

        var lessonService = new LessonService(lessonRepositoryMock.Object, moduleRepositoryMock.Object);

        //Act
        lessonService.UpdateLessonGrade(12, 98.2d);

        //Assert
        Assert.IsTrue(lesson.IsPassed); // assuming it should pass in this condition
        Assert.AreEqual(98.2d, lesson.Grade); // expected Lesson Grade should be what you expected the grade to be after you call UpdateLessonGrade
    }
</code></pre>
",https://stackoverflow.com/questions/53458667/unit-testing-a-basic-c-application-with-repository,"['c#', 'asp.net', 'unit-testing']",273,TRUE,2,2
Unit Testing A Moment Date - Memory Address Issues?,"<p>The problem?
I am trying to test a method that uses the moment.subtract() method which takes 1 day off the current date. Firstly, the subtract method provided to us by Moment only manipulates the date, it does not create a new date, so no new memory address location. When trying to test this method, I am getting the following expectation error:</p>

<p><code>[ Wed Jun 20 2018 09:14:52 GMT+0100 ]
but actual calls were
[ Wed Jun 20 2018 09:14:52 GMT+0100 ]</code></p>

<p>Weird right?</p>

<p>The only thing I can think of is somewhere in my code the date reference is changing. I will place my code below with the unit test as well</p>

<pre><code>public prevDate = () =&gt; {
  this.datePickerService.changeDate(this.date.subtract(1, 'day'));
}

ngOnInit() {
  this.date = this.datePickerService.date; // Is this the problem?
}
</code></pre>

<p>Unit tests:</p>

<pre><code>describe('When the prevDate method is called', () =&gt; {
   setupComponent();

   it('should show yesterdays date', () =&gt; {
     spyOn(datePickerService, 'changeDate');
     datePickerService.date = moment();
     component.prevDate();
 expect(datePickerService.changeDate).toHaveBeenCalledWith(datePickerService.date.add(-1, 'days'));
    });
  });
</code></pre>
",https://stackoverflow.com/questions/50963673/unit-testing-a-moment-date-memory-address-issues,"['javascript', 'angular', 'unit-testing', 'momentjs']",105,FALSE,2,1
Unit Testing a function dealing with database records,"<p>Unit tests should only test the logic of one function and should ""mock"" the data that is used in that function. I am wondering how would we unit the following function with ""mocking"" the data? or even if its the correct way. The function signature is </p>

<pre><code>    public String doSomething(int firstId, int secondId, int count){
     //this function looks in a table e.g. C which has foreign keys from table A, and B
    //if firstId and secondId exist in db table C return ""already-exists""
    //if count &lt; a_column_value_in_table_C return ""not-allow""
    // else return ""success""
    }
</code></pre>

<p>The <code>firstId</code> and <code>secondId</code> are foreign keys form two different tables. Now, how do we go about unit testing this function in terms of:
1. how the unit test should be design so it is able to test 3 scnarios in the function
2. how do we prepare data for this unit test given that it will need foreign keys from two different tables. </p>
",https://stackoverflow.com/questions/51068530/unit-testing-a-function-dealing-with-database-records,"['java', 'unit-testing', 'tdd']",600,TRUE,2,4
unit testing - jest with supertest gives a timeout,"<p>I got an error running my unit tests. I am using a express app from NodeJS. I want to test the return message (200) and (eventually) the output of a function.</p>

<pre><code>const {Router} = require('express');
const {query} = require('../dbConfig');

module.exports = (router = new Router()) =&gt; {
    //get only one user from the id
    router.post('/getUser', async (req,res)=&gt;{
        id = req.body.id;
        sql = ""SELECT lastname, firstname, email, title_id, id, state FROM users WHERE id="" + id;
        let result = await query(sql);
        if(result.length &gt;= 1){
            res.send(result[0]);
        }

    })
    return router;
};
</code></pre>

<p>But when I try to run the following test : </p>

<pre><code>const app = require('../../app')
const request = require('supertest')
jest.mock('../../dbConfig');;

describe('POST /getUser', () =&gt; {
    let data = {
        id:1
    }

    it('Response 200 + response type',(done)=&gt;{
        request.agent(app)
            .post('/getUser')
            .send(data)
            .expect(200, done)
    })
});
</code></pre>

<p>It returns me the following error</p>

<pre><code>Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.
</code></pre>

<p>I tried diffrent variations without success... I also tried the doc online which wasn't really helpful for this error... I run jest with <code>npx jest</code> and the mock file looks like this : </p>

<pre><code>const rep={
    ""lastname"": ""admin"",
    ""firstname"": ""admin"",
    ""email"": ""admin@etsmtl.ca"",
    ""title_id"": 1,
    ""id"": 1,
    ""state"": 1
};


const query = (sqli) =&gt;{
    return new Promise((resolve, reject) =&gt;{
        console.log(""SQL request : "" + sqli)
        if(sqli === ""SELECT lastname, firstname, email, title_id, id, state FROM users WHERE id=1""){
            console.log(""Passed"")
            resolve(rep);
        }
    });

}

module.exports = {query};
</code></pre>
",https://stackoverflow.com/questions/53484391/unit-testing-jest-with-supertest-gives-a-timeout,"['node.js', 'unit-testing', 'express', 'jestjs', 'supertest']",4011,TRUE,2,2
Spring boot - unit testing Spring Data JPA repositories,"<p>I have a repository (say, MovieRepository) created with the help of Spring Data.  </p>

<pre><code>public interface MovieRepository extends JpaRepository&lt;Movie, Short&gt; {}  
</code></pre>

<p>Let's say i want to unit test one of the methods provided by <strong>JpaRepository interface</strong> for exemple <code>getOne(short id)</code>, is that making sense ? as i'm usually not writing any implementation code myself.  </p>

<p>And what about if i write a method with query myself, for exemple:  </p>

<pre><code>@Query(""SELECT m "" +
            ""FROM Movie m inner join  MovieGenre mg ON m.id = mg.movie.id "" +
            ""WHERE mg.genre.id = (SELECT mg2.genre.id FROM MovieGenre mg2 WHERE mg2.movie.id = ?1 AND mg2.movie.id &lt;&gt; mg.movie.id AND mg.genre.id = mg2.genre.id) "" +
            ""GROUP BY mg.movie.id "" +
            ""ORDER BY count(m) DESC"")
Page&lt;Movie&gt; findRelatedMoviesToMovieById(@Param(""id"") short id, Pageable pageable);  
</code></pre>

<p>Should i test this method ?</p>
",https://stackoverflow.com/questions/51881803/spring-boot-unit-testing-spring-data-jpa-repositories,"['java', 'spring-boot', 'junit', 'spring-data']",4900,TRUE,2,1
"Exception using mock library, python unit testing issue","<ul>
<li>Windows 7 Professional (64 bit)</li>
<li>Python 2.7.14 (2.7.14150 64 bit)</li>
<li>mock 2.0.0</li>
</ul>

<p>When I just run <code>python -c ""import mock""</code> from command prompt (as an administrator) it yields Exception:</p>

<pre><code>Traceback (most recent call last):
  File ""&lt;string&gt;"", line 1, in &lt;module&gt;
  File ""C:\Python27\lib\site-packages\mock\__init__.py"", line 2, in &lt;module&gt;
    import mock.mock as _mock
  File ""C:\Python27\lib\site-packages\mock\mock.py"", line 71, in &lt;module&gt;
    _v = VersionInfo('mock').semantic_version()
  File ""C:\Python27\lib\site-packages\pbr\version.py"", line 461, in semantic_version
    self._semantic = self._get_version_from_pkg_resources()
  File ""C:\Python27\lib\site-packages\pbr\version.py"", line 448, in _get_version_from_pkg_resources
    result_string = packaging.get_version(self.package)
  File ""C:\Python27\lib\site-packages\pbr\packaging.py"", line 755, in get_version
    name=package_name))
Exception: Versioning for this project requires either an sdist tarball, or access to an upstream git repository. It's also possible that there is a mismatch between the package name in setup.cfg and the argument given t
o pbr.version.VersionInfo. Project name mock was given, but was not able to be found.
</code></pre>
",https://stackoverflow.com/questions/48557981/exception-using-mock-library-python-unit-testing-issue,"['python', 'unit-testing', 'mocking']",1409,TRUE,2,2
Jasmine Unit Testing errors using ng-select package,"<p>I have imported ng-select component (<a href=""https://github.com/ng-select/ng-select"" rel=""nofollow noreferrer"">https://github.com/ng-select/ng-select</a>) into my angular app and does not throw any console errors when running the app, and works as expected. However it causes errors when running my angular unit tests using Jasmine.</p>

<p>I have imported the NgSelectModule into my app.module.ts file under the imports array, and I have also imported the NgSelectComponent into my configuration.component.spec.ts file via the declarations array:</p>

<pre><code>import { NgSelectComponent } from '@ng-select/ng-select';

 describe('Test Configuration Component',
  () =&gt; {
    let component: ConfigurationComponent;
    let fixture: ComponentFixture&lt;ConfigurationComponent&gt;;

    beforeEach(() =&gt; {
      TestBed.configureTestingModule({
        declarations: [ConfigurationComponent, NgSelectComponent],
        imports: [FormsModule],
        providers: [{ provide: APIService, useClass: APIServiceMock }, Helper]
      });

      fixture = TestBed.createComponent(ConfigurationComponent);
      component = fixture.componentInstance;
    });
</code></pre>

<p>My unit test looks like the following:</p>

<pre><code>  it('check that array of employees got binded to accounts', async () =&gt; {
    fixture.detectChanges();
    let employeeAccounts = [
      { ""employeeAccountId"": 1, ""employeeId"": 1, ""name"": ""Name"", ""descriptor"": ""descriptor"", ""street"": ""Street"", ""postcode"": ""postcode"", ""state"": ""VIC"", ""city"": ""Melb"", ""country"": ""AU"", ""phone"": ""3123"", ""MCC"": ""MCC"" },
      { ""employeeAccountId"": 2, ""employeeId"": 1, ""name"": ""Name2"", ""descriptor"": ""descriptor2"", ""street"": ""Street2"", ""postcode"": ""postcode2"", ""state"": ""VIC2"", ""city"": ""Melb2"", ""country"": ""AU2"", ""phone"": ""3123"", ""MCC"": ""MCC2"" }];
      component.employeeAccounts = employeeAccounts;
      component.ngOnInit();
      fixture.whenStable().then(() =&gt; {
        fixture.detectChanges();
        expect(component.employeeAccounts[1]).toEqual(employeeAccounts[1]);
      });
    });
</code></pre>

<p>The HTML for ng-select in configuration component looks like the following:</p>

<pre><code>&lt;ng-select [(ngModel)]=""selectedEmployeeAccountId"" [items]=""employeeAccounts"" (change)=""accountSelected()"" [disabled]=""isLoadingAccounts"" [loading]=""isLoadingAccounts"" bindLabel=""name"" bindValue=""employeeAccountId"" placeholder=""Please Select""&gt;&lt;/ng-select&gt;
</code></pre>

<p>I have had to use an older version of ng-select (v 1.5.2) due to Angular 5 compability issues.</p>

<p>Unit Test Error:</p>

<pre><code>HeadlessChrome 0.0.0 (Windows 10 0.0.0) Test Configuration Component check that array of employees got binded to accounts FAILED
        Error: Template parse errors:
        Can't bind to 'virtualScroll' since it isn't a known property of 'ng-dropdown-panel'.
        1. If 'virtualScroll' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component.
        2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. (""
        &lt;ng-dropdown-panel *ngIf=""isOpen""
            class=""ng-dropdown-panel""
            [ERROR -&gt;][virtualScroll]=""virtualScroll""
            [bufferAmount]=""bufferAmount""
            [appendTo]=""appendTo""
        ""): ng:///DynamicTestModule/NgSelectComponent.html@47:4
        Can't bind to 'bufferAmount' since it isn't a known property of 'ng-dropdown-panel'.
        1. If 'bufferAmount' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component.
        2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. (""
            class=""ng-dropdown-panel""
            [virtualScroll]=""virtualScroll""
            [ERROR -&gt;][bufferAmount]=""bufferAmount""
            [appendTo]=""appendTo""
            [position]=""dropdownPosition""
        ""): ng:///DynamicTestModule/NgSelectComponent.html@48:4
        Can't bind to 'appendTo' since it isn't a known property of 'ng-dropdown-panel'.
        1. If 'appendTo' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component.
        2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. (""
            [virtualScroll]=""virtualScroll""
            [bufferAmount]=""bufferAmount""
            [ERROR -&gt;][appendTo]=""appendTo""
            [position]=""dropdownPosition""
            [headerTemplate]=""headerTemplate""
        ""): ng:///DynamicTestModule/NgSelectComponent.html@49:4
        Can't bind to 'position' since it isn't a known property of 'ng-dropdown-panel'.
        1. If 'position' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component.
        2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. (""
            [bufferAmount]=""bufferAmount""
            [appendTo]=""appendTo""
            [ERROR -&gt;][position]=""dropdownPosition""
            [headerTemplate]=""headerTemplate""
            [footerTemplate]=""footerTempl""): ng:///DynamicTestModule/NgSelectComponent.html@50:4
        Can't bind to 'headerTemplate' since it isn't a known property of 'ng-dropdown-panel'.
        1. If 'headerTemplate' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component.
        2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. (""
            [appendTo]=""appendTo""
            [position]=""dropdownPosition""
            [ERROR -&gt;][headerTemplate]=""headerTemplate""
            [footerTemplate]=""footerTemplate""
            [items]=""itemsList.filter""): ng:///DynamicTestModule/NgSelectComponent.html@51:4
        Can't bind to 'footerTemplate' since it isn't a known property of 'ng-dropdown-panel'.
        1. If 'footerTemplate' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component.
        2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. (""
            [position]=""dropdownPosition""
            [headerTemplate]=""headerTemplate""
            [ERROR -&gt;][footerTemplate]=""footerTemplate""
            [items]=""itemsList.filteredItems""
            (update)=""viewPortItems =""): ng:///DynamicTestModule/NgSelectComponent.html@52:4
        Can't bind to 'items' since it isn't a known property of 'ng-dropdown-panel'.
        1. If 'items' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component.
        2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. (""
            [headerTemplate]=""headerTemplate""
            [footerTemplate]=""footerTemplate""
            [ERROR -&gt;][items]=""itemsList.filteredItems""
            (update)=""viewPortItems = $event""
            (scrollToEnd)=""scrollToEn""): ng:///DynamicTestModule/NgSelectComponent.html@53:4
        'ng-dropdown-panel' is not a known element:
        1. If 'ng-dropdown-panel' is an Angular component, then verify that it is part of this module.
        2. If 'ng-dropdown-panel' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. (""
            &lt;/span&gt;
        &lt;/div&gt;
        [ERROR -&gt;]&lt;ng-dropdown-panel *ngIf=""isOpen""
            class=""ng-dropdown-panel""
            [virtualScroll]=""virtualScroll""
        ""): ng:///DynamicTestModule/NgSelectComponent.html@45:0
            at syntaxError node_modules/@angular/compiler/esm5/compiler.js:486:22)
            at TemplateParser.webpackJsonp../node_modules/@angular/compiler/esm5/compiler.js.TemplateParser.parse node_modules/@angular/compiler/esm5/compiler.js:24674:1)
            at JitCompiler.webpackJsonp../node_modules/@angular/compiler/esm5/compiler.js.JitCompiler._parseTemplate node_modules/@angular/compiler/esm5/compiler.js:34629:1)
            at JitCompiler.webpackJsonp../node_modules/@angular/compiler/esm5/compiler.js.JitCompiler._compileTemplate node_modules/@angular/compiler/esm5/compiler.js:34604:1)
            at http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/compiler/esm5/compiler.js:34505:48
            at Set.forEach (&lt;anonymous&gt;)
            at JitCompiler.webpackJsonp../node_modules/@angular/compiler/esm5/compiler.js.JitCompiler._compileComponents node_modules/@angular/compiler/esm5/compiler.js:34505:1)
            at http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/compiler/esm5/compiler.js:34393:1
            at Object.then node_modules/@angular/compiler/esm5/compiler.js:475:33)
            at JitCompiler.webpackJsonp../node_modules/@angular/compiler/esm5/compiler.js.JitCompiler._compileModuleAndAllComponents node_modules/@angular/compiler/esm5/compiler.js:34391:1)
        Failed: Cannot read property 'detectChanges' of undefined
        TypeError: Cannot read property 'detectChanges' of undefined
            at Object.&lt;anonymous&gt; src/app/configuration/configuration.component.spec.ts:87:17)
            at step (http://localhost:9876/_karma_webpack_/main.bundle.js:89:23)
            at Object.next (http://localhost:9876/_karma_webpack_/main.bundle.js:70:53)
            at http://localhost:9876/_karma_webpack_/main.bundle.js:64:71
            at new ZoneAwarePromise node_modules/zone.js/dist/zone.js:891:1)
            at webpackJsonp../src/app/configuration/configuration.component.spec.ts.__awaiter (http://localhost:9876/_karma_webpack_/main.bundle.js:60:12)
            at UserContext.&lt;anonymous&gt; src/app/configuration/configuration.component.spec.ts:86:66)
            at ZoneDelegate.webpackJsonp../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke node_modules/zone.js/dist/zone.js:388:1)
            at ProxyZoneSpec.webpackJsonp../node_modules/zone.js/dist/zone-testing.js.ProxyZoneSpec.onInvoke node_modules/zone.js/dist/zone-testing.js:288:1)
            at ZoneDelegate.webpackJsonp../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke node_modules/zone.js/dist/zone.js:387:1)
</code></pre>

<p>I believe it could be because the version of ng-select I am using does not import all the necessary dependencies, but then I am using the dropdown successfully on the front-end so I think it may be a separate issue.</p>

<p>Any help identifying the problem would be great.</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/50559812/jasmine-unit-testing-errors-using-ng-select-package,"['javascript', 'angular', 'unit-testing', 'jasmine']",2373,TRUE,2,2
Reset global variables during python unit testing runtime,"<p>I am currently writing tests for a bit of Python (using the 3.5 version) software for the company I'm working with, but am stumbling upon a problem which I currently believe is because of <em>global variables</em> if I could call it that.</p>

<p>The software architecture is extremely modular, hence to test individual modules a separate test file (perhaps called <code>test_somemodule_py</code>) is created containing one class that extends the <code>unittest.TestCase</code> one.</p>

<p><strong>NOTE</strong> that what I call <code>modules</code> here is not really a Python module, but rather an application module</p>

<p>All of the tests are triggered through a single runner script which contains a custom loader:</p>

<pre class=""lang-python prettyprint-override""><code>def load_tests(loader, tests, pattern):
suite = unittest.TestSuite()
for all_tests in loader.discover('tests', pattern='test_*.py'):
    for test_suite in all_tests:
        suite.addTests(test_suite)

return suite
</code></pre>

<p>During actual runtime all of the individual modules are held (contained) in a master like wrapper, which is basically a Singleton.</p>

<p>Now my problem is that whenever I run the tests as individual files (changing the loader from <code>test_*.py</code> to <code>test_somemodule.py</code>), all tests succeed, however if they are run all together (leaving the <code>test_*.py</code> pattern), some of the tests start failing.</p>

<p>I am pretty sure it was never the case when I hadn't implemented the master wrapper as a singleton, but the application functionality and architecture really requires that kind of approach. Since I am suspecting that only one instance of it is created, can anyone advise me on how to best solve this issue?</p>

<p>My theory is that if there was a method to <em>reset all 'globals' to an initial state</em>, it would work like a charm. Or perhaps there is some sort of method to isolate memory which is then discarded when test goes out of scope.</p>

<p>Many thanks in advance.</p>
",https://stackoverflow.com/questions/48445554/reset-global-variables-during-python-unit-testing-runtime,"['python', 'python-3.x', 'unit-testing']",2506,TRUE,2,1
Unit testing (?) an angular 6 component with TestBed,"<p>When using the <code>TestBed</code>, are you really unit testing a component or are you making integration tests?</p>

<p>Creating a fixture (<code>TestBed.createComponent(AppComponent)</code>) and calling <code>fixture.detectChanges()</code> automatically calls <code>ngOnInit</code>. If you want to test another method, you are now testing multiple units.</p>

<p>This leads to another question: should you be testing units, or should you be testing user actions? For example, should you be testing the method <code>setDimensions</code> or should you be testing that when the user clicks on a certain button, an element has the appropriate dimensions amongst other things.</p>

<p>I guess the first way of testing would be closer to the ""unit test"" way, but then you still have to deal with the lifecycle methods of the component being called. This makes me think there is no way to do unit tests of a component using <code>TestBed</code>. Stubbing all lifecycle methods seems ridiculous.</p>

<p>Whichever way you decide to test, you should also test the DOM, should you not? Then you are not testing in isolation by including the DOM api.</p>
",https://stackoverflow.com/questions/50475520/unit-testing-an-angular-6-component-with-testbed,"['angular', 'unit-testing', 'integration-testing', 'angular-components', 'testbed']",1452,TRUE,2,2
Unit testing Private Functions in Junit with Mockito,"<p>I am Newbie to Java and Junit,</p>

<p>Does Anyone know how to write test cases for private functions in Junit ? </p>

<p>After Some research in Google I setup environment and wrote unit test cases for public functions and mocked parent classes with help of Mock() proxy.</p>

<p>For public function with inline valued arguments, I reached my expectations and tested both Positive and Negative Path.</p>

<p>For Private Methods I followed </p>

<p><a href=""https://stackoverflow.com/questions/34571/how-do-i-test-a-private-function-or-a-class-that-has-private-methods-fields-or][1]"">How do I test a private function or a class that has private methods, fields or inner classes?</a></p>

<pre><code>Method method = targetClass.getDeclaredMethod(methodName, argClasses);
method.setAccessible(true);
return method.invoke(targetObject, argObjects);
</code></pre>

<p>And for fields:</p>

<pre><code>Field field = targetClass.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(object, value);
</code></pre>

<p>code:</p>

<pre><code>public class universalConfiguration { 
   private Integer getTotalDocuments(Client client, String indexName, String indexType, QueryBuilder searchQueryBuilder) {
    SearchResponse response = client.prepareSearch()
             .setIndices(indexName)
             .setTypes(indexType)
             .setSize(0)
             .setQuery(searchQueryBuilder)
             .execute().actionGet();

     return (int) response.getHits().totalHits;
 }
}
</code></pre>

<p>This is My code I want to test this private method with this public class, i tried to use this method using <strong>getDeclaredMethod</strong> and <strong>setAccessible</strong> but I am getting errors. </p>

<pre><code>UniversalConfiguration universalConfiguration = new UniversalConfiguration();    
getTotalDocuments getTotalDocuments= universalConfiguration .
                                         getDeclaredMethod(getTotalDocuments,
                                         client,
                                         indexName,
                                         indexType, 
                                         searchQueryBuilder);           
    getTotalDocuments.setAccessible(true);
</code></pre>

<blockquote>
  <p>getTotalDocuments method cannot be resolved to a type</p>
</blockquote>

<p>Correct me If i did any mistakes.</p>
",https://stackoverflow.com/questions/51017494/unit-testing-private-functions-in-junit-with-mockito,"['java', 'unit-testing', 'junit', 'mockito']",2387,TRUE,2,3
Visual Studio 2017 community/Professional - Live Unit Testing,"<p>I'm looking for a extension/plugin to allow live unit testing in VS 2017 Community or Professional. </p>

<p>I understand that this feature is available on the enterprise version, however I wanted to see if anyone knows of any alternatives out there without having to upgrade to enterprise.</p>

<p>Any information on this would be appreciated. Thanks! </p>
",https://stackoverflow.com/questions/49943729/visual-studio-2017-community-professional-live-unit-testing,"['visual-studio-2017', 'live-unit-tests']",351,FALSE,2,1
"Failed: Can&#39;t resolve all parameters for MatDialogRef: (?, ?, ?). unit testing Angular project","<p>I am new to angular development and more new towards unit testing using jasmine.
I have created a component to sow a dialog using angular material MatDialogRef, MAT_DIALOG_DATA from @angular/material.
The component is working fine but the Unit testing is giving me an error which i am not able to resolve.</p>

<p>I really need this to work and any help would be appreciated....
Thanks in advance..!!!</p>

<p>Please find my code below:</p>

<p><strong>app.module.ts</strong></p>

<pre><code>        import { BrowserModule } from '@angular/platform-browser';
    import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
    import { HttpClientModule, HttpClient } from '@angular/common/http';
    import { HttpModule } from '@angular/http';
    import { RouterModule, Routes } from '@angular/router';
    import 'hammerjs';
    import { NgxPhoneSelectModule } from 'ngx-phone-select';
    import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
    import { FormsModule, ReactiveFormsModule } from '@angular/forms';
    import { MatInputModule, MatButtonModule, MatSelectModule } from '@angular/material';
    import { MatGridListModule } from '@angular/material';
    import { MatTableModule } from '@angular/material';
    import { MatDialogModule} from '@angular/material';
    import { MatCardModule} from '@angular/material';
    import { MaterialModule } from './modules/material/material.module';


    import { AppComponent } from './app.component';
    import { CustomerComponent } from './components/customer/customer.component';
    import { LoginComponent } from './components/login/login.component';
    import { ForgetPasswordComponent } from './components/forget-password/forget-password.component';
    import { PageNotFoundComponent } from './components/page-not-found/page-not-found.component';
    import { DashboardComponent } from './components/dashboard/dashboard.component';

    import { LoaderService } from './services/loader.service';
    import { CustomerDataService } from './services/customer-data.service';
    import { UserService } from './services/user/user.service';


    import { HeaderComponent } from './components/header/header.component';
    import { UpdateCustomerComponent } from './components/update-customer/update-customer.component';
    import { AuthService } from './services/auth.service';
    import { AuthGuard } from './services/auth/auth.guard';
    import { DeleteCustomerComponent } from './components/delete-customer/delete-customer.component';
    import { FooterComponent } from './components/footer/footer.component';
    const appRoutes: Routes = [
      {
        path: '',
        component: LoginComponent
      },
      {
        path: 'create-customer',
        component: CustomerComponent,
        //        canActivate: [AuthGuard] // ristrict direct access of links
      },
      {
        path: 'forget-password',
        component: ForgetPasswordComponent,
        //        canActivate: [AuthGuard] // ristrict direct access of links
      },
      {
        path: 'dashboard',
        component: DashboardComponent,
        //        canActivate: [AuthGuard] // ristrict direct access of links
      },
      {
        path: 'update-customer',
        component: UpdateCustomerComponent,
        //        canActivate: [AuthGuard] // ristrict direct access of links
      },
      {
        path: '**',
        component: PageNotFoundComponent
      }
    ];

    @NgModule({
      declarations: [
        AppComponent,
        CustomerComponent,
        LoginComponent,
        ForgetPasswordComponent,
        PageNotFoundComponent,
        DashboardComponent,
        HeaderComponent,
        UpdateCustomerComponent,
        DeleteCustomerComponent,
        FooterComponent
      ],
      imports: [
        BrowserModule,
        HttpClientModule,
        HttpModule,
        RouterModule.forRoot(appRoutes),
        NgxPhoneSelectModule,
        BrowserAnimationsModule,
        FormsModule,
        ReactiveFormsModule,
        MatInputModule,
        MatButtonModule,
        MatSelectModule,
        MatGridListModule,
        MatTableModule,
        MaterialModule
      ],
      entryComponents: [
          DeleteCustomerComponent
      ],
      schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
    providers: [LoaderService, AuthService, AuthGuard, UserService, CustomerDataService],

      bootstrap: [AppComponent]
    })
    export class AppModule { }
</code></pre>

<p><strong>delete customer component</strong></p>

<pre><code>        import { Component, OnInit, Inject } from '@angular/core';
    import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';

    import { Router} from '@angular/router';
    @Component({
      selector: 'app-delete-customer',
      templateUrl: './delete-customer.component.html',
      styleUrls: ['./delete-customer.component.scss']
    })
    export class DeleteCustomerComponent implements OnInit {

      constructor(private router: Router, public deleteCustDialogRef: MatDialogRef&lt;DeleteCustomerComponent&gt;, @Inject(MAT_DIALOG_DATA) public data: string) { }

      ngOnInit() {
      }

    onClosedeleteCustomer() {
        this.deleteCustDialogRef.close('confirm');
        this.router.navigate(['./dashboard']);
      }
      onCloseCancel() {
        this.deleteCustDialogRef.close('cancel');

    }
    }
</code></pre>

<p><strong>delete-customer.component.spec.ts</strong></p>

<pre><code>        import { async, ComponentFixture, TestBed } from '@angular/core/testing';
    import {RouterTestingModule} from '@angular/router/testing';
    import { DeleteCustomerComponent } from './delete-customer.component';
    import { MaterialModule } from '../../modules/material/material.module';
    import { MatDialogRef, MAT_DIALOG_DATA, MatDialog, MatDialogModule  } from '@angular/material';
    describe('DeleteCustomerComponent', () =&gt; {
      let component: DeleteCustomerComponent;
      let fixture: ComponentFixture&lt;DeleteCustomerComponent&gt;;

      beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
          declarations: [ DeleteCustomerComponent ],
          imports: [ MaterialModule, RouterTestingModule, MatDialogModule ],
          providers : [ MatDialogRef, MAT_DIALOG_DATA, MatDialog ]
        })
        .compileComponents();
      }));

      beforeEach(() =&gt; {
        fixture = TestBed.createComponent(DeleteCustomerComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
      });

      it('should create', () =&gt; {
        expect(component).toBeTruthy();
      });
    });
</code></pre>

<p><strong>karma error</strong></p>

<pre><code>        DeleteCustomerComponent should create
        Failed: Can't resolve all parameters for MatDialogRef: (?, ?, ?).
        Error: Can't resolve all parameters for MatDialogRef: (?, ?, ?).
        at syntaxError (http://localhost:9876/_karma_webpack_/webpack:/C:/dewatering_FST/node_modules/@angular/compiler/esm5/compiler.js:485:22)
        at CompileMetadataResolver.webpackJsonp.../../../compiler/esm5/compiler.js.CompileMetadataResolver._getDependenciesMetadata (http://localhost:9876/_karma_webpack_/webpack:/C:/dewatering_FST/node_modules/@angular/compiler/esm5/compiler.js:15662:1)
        at CompileMetadataResolver.webpackJsonp.../../../compiler/esm5/compiler.js.CompileMetadataResolver._getTypeMetadata (http://localhost:9876/_karma_webpack_/webpack:/C:/dewatering_FST/node_modules/@angular/compiler/esm5/compiler.js:15497:1)
        at CompileMetadataResolver.webpackJsonp.../../../compiler/esm5/compiler.js.CompileMetadataResolver._getInjectableMetadata (http://localhost:9876/_karma_webpack_/webpack:/C:/dewatering_FST/node_modules/@angular/compiler/esm5/compiler.js:15477:1)
        at CompileMetadataResolver.webpackJsonp.../../../compiler/esm5/compiler.js.CompileMetadataResolver.getProviderMetadata (http://localhost:9876/_karma_webpack_/webpack:/C:/dewatering_FST/node_modules/@angular/compiler/esm5/compiler.js:15837:1)
        at http://localhost:9876/_karma_webpack_/webpack:/C:/dewatering_FST/node_modules/@angular/compiler/esm5/compiler.js:15748:1
        at Array.forEach (&lt;anonymous&gt;)
        at CompileMetadataResolver.webpackJsonp.../../../compiler/esm5/compiler.js.CompileMetadataResolver._getProvidersMetadata (http://localhost:9876/_karma_webpack_/webpack:/C:/dewatering_FST/node_modules/@angular/compiler/esm5/compiler.js:15708:1)
        at CompileMetadataResolver.webpackJsonp.../../../compiler/esm5/compiler.js.CompileMetadataResolver.getNgModuleMetadata (http://localhost:9876/_karma_webpack_/webpack:/C:/dewatering_FST/node_modules/@angular/compiler/esm5/compiler.js:15276:1)
        at JitCompiler.webpackJsonp.../../../compiler/esm5/compiler.js.JitCompiler._loadModules (http://localhost:9876/_karma_webpack_/webpack:/C:/dewatering_FST/node_modules/@angular/compiler/esm5/compiler
</code></pre>
",https://stackoverflow.com/questions/48058457/failed-cant-resolve-all-parameters-for-matdialogref-unit-testing-a,"['angular', 'unit-testing', 'jasmine', 'angular-material', 'karma-jasmine']",20991,TRUE,21,3
Mocking time for Scala Deadline during unit testing,"<p>Java 8's time API allows mocking by passing in a custom <code>clock</code> in <a href=""https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html#now-java.time.Clock-"" rel=""nofollow noreferrer""><code>Instant.now(clock)</code></a> invocations. Similarly, <a href=""https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html#now-java.time.Clock-"" rel=""nofollow noreferrer""><code>LocalDateTime.now(clock)</code></a>.</p>

<p>I have a <code>Deadline</code> object in a custom Cache implementation that indicates whether an entry is expired. I would like to be able to test this by not using <code>sleep</code> method in unit test. Does classes in Scala's <code>scala.concurrent.duration</code> package provide any plugin mocking capabilities? </p>
",https://stackoverflow.com/questions/50955230/mocking-time-for-scala-deadline-during-unit-testing,"['scala', 'time']",876,TRUE,2,1
Angular CLI Unit Testing An Extended Window Method,"<p>I am trying to write a unit test for an Angular CLI (v6.0.8, with <code>@angular/core</code> v6.0.9) component that calls a method on the window object injected via a service, but I'm running into some issues.</p>

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

<pre><code>import { WindowRefService} from '../../services/window-reference/window-reference.service'

export class MyComponent {

  constructor(private windowRef: WindowRefService) {}

  addAnother() {
    if ((this.windowRef.nativeWindow._thirdPartyWindowObject) {
      this.windowRef.nativeWindow._thirdPartyWindowObject.track(""toolstart"")
    }
  }
}
</code></pre>

<p>and here is the service: <code>WindowRefService</code></p>

<pre><code>import { Injectable } from '@angular/core'

export interface ICustomWindow extends Window {
  _thirdPartyWindowObject: {
    track: Function
  }
}

function getWindow (): any {
    return window
}

@Injectable()
export class WindowRefService {
    get nativeWindow (): ICustomWindow {
        return getWindow()
    }
}
</code></pre>

<p>This service is a way to extend the <code>Window</code> type to include a third party library introduced into the window object in the page the app is loaded into. Not ideal, I know, but it's the  use case I was handed.</p>

<p>This is the test I've written for the <code>addAnother</code> method:</p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing'

import { MyComponent } from './MyComponent'
import { WindowRefService, ICustomWindow } from '../../services/window-reference/window-reference.service'

class WindowServiceMock {
  get nativeWindow (): ICustomWindow {
    return {
      ...window,
      _thirdPartyWindowObject: {
        track: (props: string) =&gt; {
          console.log('props', props)
          return true
        }
      }
    }
  }
}

describe('MyComponent', () =&gt; {
  let component: MyComponent
  let fixture: ComponentFixture&lt;MyComponent&gt;
  let windowSpy: WindowServiceMock

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ MyComponent ],
    })
    .overrideComponent(MyComponent, {
      set: {
        providers: [
          { provide: WindowRefService, useClass: WindowServiceMock }
        ]
      }
    })
    .compileComponents()
  }))

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(MyComponent)
    component = fixture.componentInstance
    windowSpy = fixture.debugElement.injector.get(WindowRefService) as any
    fixture.detectChanges()
  })

  it('should call the third party scripts', () =&gt; {
    let spy = spyOn(windowSpy.nativeWindow._thirdPartyWindowObject, 'track')
    component.addAnother()
    expect(spy).toHaveBeenCalled()
  })
})
</code></pre>

<p>This all works perfectly up until the point I would expect the <code>spy</code> for <code>windowSpy.nativeWindow._thirdPartyWindowObject.track</code> to have been called. When I check my logs, I can see the <code>toolstart</code> string being passed into the <code>track</code> method inside <code>WindowServiceMock</code> being logged out so the stubbed service <em>is</em> being called. However, for some reason, the spy is not.</p>

<p>I'm sure I'm missing something extremely obvious here, but any help would be appreciated.</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/51994338/angular-cli-unit-testing-an-extended-window-method,"['angular', 'unit-testing', 'jasmine', 'angular-cli']",516,TRUE,2,1
Angular firebase - Unit testing a service using angularFireAuth,"<p>I have a core service that gets an instance of the <code>firebase.auth</code> obj and returns it with a getter. It is simple and looks as follows:</p>

<pre><code>export class AuthService {

  ...
  constructor(private afAuth: AngularFireAuth,
              private afs: AngularFirestore) {
  ...
}

  public getAuthInstance(): FirebaseAuth {
    return this.afAuth.auth;
  }
}
</code></pre>

<p>Now I have a LoginService that needs the AuthService for logging into my app.</p>

<pre><code>export class LoginService {

  constructor(private authService: AuthService) {
  }

  public login(email, password): Promise&lt;UserCredential | string&gt; {
    return this.authService.getAuthInstance().signInWithEmailAndPassword(email, password)
      .catch(() =&gt; Promise.reject('Login failed.'));
  }
</code></pre>

<p>Also not too complex. But now I want to test my login comp. - specifically the <code>login</code> method. I am not able to mock <code>signInWithEmailAndPassword</code>. I tried basically everything:</p>

<ul>
<li><code>jasmine.spies</code></li>
<li>self created fake obj.</li>
</ul>

<p>The test class looks as follows:</p>

<pre><code>  ...
  const authStub: AuthService = jasmine.createSpyObj('AuthService', ['getAuthInstance']);
  const fireStub = {
    auth: {
      signInWithEmailAndPassword() {
        return Promise.resolve();
      }
    }
  };

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      providers: [
        {provide: AuthService, useValue: authStub},
        {provide: AngularFireAuth, useValue: fireStub},
        LoginService
      ]
    });
  });

  const spy = it('should call signInWithPasswordAndEmail', inject([LoginService], (service: LoginService) =&gt; {
    (&lt;jasmine.Spy&gt;authStub.getAuthInstance).and.returnValue({username: 'test'});
    spyOn(fireStub.auth, 'signInWithEmailAndPassword').and.callThrough();


    service.login(email, password).then(() =&gt; expect(spy).toHaveBeenCalledTimes(1));
  }));
</code></pre>

<p>Can anyone help me to get this damn test green? xD^^
The Error msg. That ist thrown is: this.getAuthInstance().signInWithEmail.... Is Not a function</p>
",https://stackoverflow.com/questions/51894948/angular-firebase-unit-testing-a-service-using-angularfireauth,"['angular', 'unit-testing', 'jasmine', 'mocking', 'angularfire2']",1087,TRUE,2,1
Angular4 and AngularFire2 unit testing is not working,"<p>I am trying to unit test my project. I get a very weird error</p>

<pre><code>TypeError: app.auth is not a function

at new AngularFireAuth (http://localhost:9876/_karma_webpack_/webpack:/Users/xx/xx/xx-xx/xx/xx/xx-xx-xx/xx-xx/xx/xx/xx/node_modules/angularfire2/auth/auth.js:12:1)
</code></pre>

<p>This is the spec file I am trying to run </p>

<pre><code>import { TestBed, inject } from '@angular/core/testing';

import { FirebaseAuthService } from './firebase-auth.service';
import {AngularFireAuth} from 'angularfire2/auth';
import {FirebaseApp} from 'angularfire2';

describe('FirebaseAuthService', () =&gt; {

  // Configure testbed

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      providers: [
        FirebaseAuthService,
        AngularFireAuth,
        FirebaseApp,

      ]
    });
  });

  // Create test cases below

  it('should be created', inject([FirebaseAuthService], (service: FirebaseAuthService) =&gt; {
    expect(service).toBeTruthy();
  }));
});
</code></pre>

<p>and inside the constructor of my service I initialise these services</p>

<pre><code>constructor(public _firebaseAuth: AngularFireAuth, private router: Router, private db: AngularFireDatabase) 
</code></pre>

<p>Can anyone tell my why is that happening? same thing happens when I do a unit test with AngularfireDatabase</p>
",https://stackoverflow.com/questions/49118440/angular4-and-angularfire2-unit-testing-is-not-working,"['angular', 'testing', 'karma-jasmine', 'angularfire2']",66,FALSE,2,0
Unit testing of a function with conditional statement,"<p>I have a function to track analytics from google analytics. So that in my function i need to see if the code exists or not.</p>

<pre><code>Analytics.js

const gaCode = process.env.REACT_APP_GA_TRACKING_CODE;
const gaCodeExists = gaCode &amp;&amp; gaCode.Length &gt; 0;

function trackEvent(category = ""Event"", name) {
    if(gaCodeExists) {
        GoogleAnalytics.event({
            category,
            action: name,
        });
    }

    return;
}

export default {
    gaCodeExists,
    trackEvent
}
</code></pre>

<p>At first I was doing like this (which I am pretty sure I am not doing correctly).</p>

<pre><code>describe('Testing analytics', () =&gt; {
    beforeEach(() =&gt; {
        Analytics.trackEvent(null, 'Tracking');
    });

    it('should not call google analytics', () =&gt; {
        if (!gaCodeExists) {
            const mockGoogleAnalytics = jest.fn(() =&gt; GoogleAnalytics.event);
            expect(mockGoogleAnalytics.mock.calls.length).toBe(0);
        }
    });
})
</code></pre>

<p>After reading some blog posts and looking at <a href=""https://stackoverflow.com/questions/42977961/how-to-mock-an-exported-const-in-jest"">stackover flow questions</a>. I changed it to like this which I think I am mocking the gaCodeExists variable as below. </p>

<pre><code>import constants from '../index';
import { isUsingGoogleAnalytics } from '../index';

describe('Analytics Testing', () =&gt; {
    it('Should test trackEvent', () =&gt; {
        constants.isUsingGoogleAnalytics = true;
        expect(constants.isUsingGoogleAnalytics).toBe(true);
    });
});
</code></pre>

<p>Now I am stuck how can I do the testing on <code>trackEvent</code> function. How can I apply mock gaCodeExists variable to it? The test cases would be if the <code>gaCodeExists</code> is true, <code>expect(mockFunction).toHaveBeenCalled(1)</code>.</p>

<p>P.S: I am new to testing. </p>
",https://stackoverflow.com/questions/53111571/unit-testing-of-a-function-with-conditional-statement,"['javascript', 'unit-testing', 'testing', 'jestjs']",6852,TRUE,2,2
Unit testing React components in ASP.NET Core project,"<p>I have managed to setup a basic React project using the React template in ASP.NET Core. I am not clear from the documentation and given this basic framework how I unit test individual components. I assume that I would use Jest and Enzyme to unit test the components but my efforts to set this up so far have failed. Let me list what I have done so far. 
1) In the root of the project (above the ClientApp folder) I have created a <strong>tests</strong> folder. In that folder I have a single test named CancelButton.test.js that looks like:</p>

<pre><code>import React from 'react';
import { shallow, mount, render } from 'enzyme';
import { CancelButton } from '../ClientApp/components/CancelButton';

describe('A suite', function() {
  it('should render without throwing an error', function() {
    expect(shallow(&lt;CancelButton /&gt;).contains(&lt;button className=""btn btn-default""&gt;&lt;/button&gt;)).toBe(true);
  });

  it('should be selectable by class ""foo""', function() {
    expect(shallow(&lt;CancelButton /&gt;).contains(&lt;button className=""btn btn-default""&gt;&lt;/button&gt;)).toBe(true);
    expect(shallow(&lt;CancelButton /&gt;).is('.btn')).toBe(true);
  });

  it('should mount in a full DOM', function() {
    expect(mount(&lt;CancelButton /&gt;).find('.btn').length).toBe(1);
  });
});
</code></pre>

<p>I have modified the package.json to have the lines</p>

<pre><code>  ""scripts"": {
    ""start"": ""npm-run-all --parallel watch:server watch:build"",
    ""watch:build"": ""node node_modules/webpack/bin/webpack.js -d --watch --progress --colors"",
    ""watch:server"": ""nodemon \""server/server.js\"" --watch \""./server\"""",
    ""test"": ""jest"",
    ""lint"": ""tslint ClientApp/components ClientApp/models ClientApp/store ClientApp/utils || true""
  },
  ""jest"": {
    ""setupTestFrameworkScriptFile"": ""&lt;rootDir&gt;/test-setup.js""
  },
</code></pre>

<p>The Jest test-setup.js looks like</p>

<pre><code>import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-15';

Enzyme.configure({ adapter: new Adapter() });
</code></pre>

<p>jest.config.js looks like</p>

<pre><code>const {defaults} = require('jest-config');
module.exports = {
  transform: {
      ""^.+\\.tsx?$"": ""ts-jest"",
      ""^.+\\.ts?$"": ""ts-jest""
  },
  testRegex: ""(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?|ts?|js?)$"",
  moduleFileExtensions: [...defaults.moduleFileExtensions,""ts"", ""tsx""],
  transformIgnorePatterns: [""&lt;rootDir&gt;/node_modules""]
};
</code></pre>

<p>I have installed Jest, Ts-jest, and Enzyme. </p>

<p>But when I run <code>npm run test</code> I get errors</p>

<pre><code>&gt; AspReact@0.0.0 test /Users/rebeccaannburton/Projects/AspReact/AspReact
&gt; jest

 FAIL  __tests__/CancelButton.test.js
  ● Test suite failed to run

    Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plainJavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring ""node_modules"".

    Here's what you can do:
     • To have some of your ""node_modules"" files transformed, you can specify a custom ""transformIgnorePatterns"" in your config.
     • If you need a custom transformation specify a ""transform"" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the ""moduleNameMapper"" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/en/configuration.html

    Details:

    /Users/rebeccaannburton/Projects/AspReact/AspReact/__tests__/CancelButton.test.js:1
    ({""Object.&lt;anonymous&gt;"":function(module,exports,require,__dirname,__filename,global,jest){import React from 'react';
                                                                                             ^^^^^^

    SyntaxError: Unexpected token import

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.926s
Ran all test suites.
</code></pre>

<p>The first error is 'import'? The second seems node_modules should be excluded but in the configuration file I have specifically excluded the folder ad suggested. What else in the configuration am I missing or in error?</p>
",https://stackoverflow.com/questions/52906158/unit-testing-react-components-in-asp-net-core-project,"['reactjs', 'unit-testing', 'asp.net-core-2.1']",854,FALSE,2,0
StackOverflow in .NET unit testing when references are circular,"<p>I was testing something else for circular reference resistance when I noticed:</p>

<pre><code>    public class Foo
    {
        private Bar myBar = new Bar();
    }

    public class Bar
    {
        private Foo myFoo = new Foo();
    }

    [Fact]
    public void CircularReferenceTest()
    {
        var foo = new Foo();
        var bar = new Bar();
    }
</code></pre>

<p>resulted in XUnit runner halt and console log:</p>

<blockquote>
  <p>The active test run was aborted. Reason: Process is terminated due to StackOverflowException.</p>
</blockquote>

<p>I tested it on MStest and had same result. Is there a way around this? Is it a bug, or it's intended to stop execution in that way?</p>
",https://stackoverflow.com/questions/48392039/stackoverflow-in-net-unit-testing-when-references-are-circular,"['c#', 'unit-testing', 'stack-overflow']",10578,TRUE,8,2
Angular 6 unit testing with ngx-translate dependency,"<p>I have an <code>angular 6</code> application with <code>ngx-translate/core@10.0.2</code>. Trying to use a <code>CustomLoader</code> with hard-coded values. But something is not quite right.</p>

<p><strong>Test</strong></p>

<pre><code>class CustomLoader implements TranslateLoader {
  getTranslation(lang: string): Observable&lt;any&gt; {
   return of({
      'DETAILS': {
        'PIN_ENTRY': {              
          'INPUT': {
            'ERRORS': {
              'INVALID': 'Blah',
              'INELIGIBLE': 'Blah Blah'
            }
          }
        }
      }
  });
 }
}

beforeEach(async(() =&gt; {
 TestBed.configureTestingModule({
  declarations: [ MyComponent ],
  imports: [
    ... // Elided for brevity
    TranslateModule.forRoot({
      loader: { provide: TranslateLoader, useClass: CustomLoader}
    })
  ],      
})
.compileComponents();
}));
</code></pre>

<p><strong>Component</strong></p>

<pre><code>ngOnInit() {
  this.translateService.getTranslation('DETAILS.PIN_ENTRY.INPUT').pipe(first()).subscribe(translations =&gt; {      
    this.errorTranslations = translations['ERRORS'];
  });
}
</code></pre>

<p>The issue is, <code>translate</code> inside the <code>subscribe</code> is always 'DETAILS.PIN_ENTRY.INPUT'. I also added a logging statement in <code>CustomLoader#getTranslation</code>, to see if it was loaded, but couldn't see the output. </p>

<p>What is wrong with my set up?</p>
",https://stackoverflow.com/questions/51070018/angular-6-unit-testing-with-ngx-translate-dependency,"['angular', 'ngx-translate', 'angular-test']",2457,TRUE,1,1
Unit testing with third party libraries and Carthage,"<p>What is the proper way to use Carthage for dependency management, but also be able to write tests with it for types it pulls in.  For example, (this is hypothetical) if I pull in AlamoFire and let’s say it has a Response protocol and different concrete types conform to the Response protocol.  In my own library, if I were to do</p>

<pre><code>   @testable import AlamoFire 
</code></pre>

<p>it would complain that Module ‘AlamoFire’ was not compiled for testing.  Doing some research, I believe it’s because enable testability should be set to NO on release builds, which Carthage uses by default.  Is there a way to use third party types like this in your test target?</p>
",https://stackoverflow.com/questions/48388957/unit-testing-with-third-party-libraries-and-carthage,"['ios', 'swift', 'unit-testing', 'carthage']",1040,TRUE,1,1
How to do Unit testing in Android Studio?,"<p>I am a Beginner in Android. I want to write a unit testing code in Android studio. How to run that testing in real device and also how to get the test result. I can able to see AndroidTest folder in src folder.</p>
",https://stackoverflow.com/questions/49124584/how-to-do-unit-testing-in-android-studio,['android'],799,FALSE,1,1
Unit testing onClick handler using Jest in React,"<p>I have the following code which sets a custom handler to each element (which can be a <code>button</code> or a <code>li</code>) click.</p>

<pre><code>componentWillReceiveProps(nextProps) {
   this._setCallbackToItemLinks(nextProps);
}

_setCallbackToItemLinks(props) {
    const items = props &amp;&amp; props.items;
    items.forEach(item =&gt; {
      item.links.forEach(link =&gt; {
        this._setCallbackToLink(link);
      });
    });
 }



 _setCallbackToLink(link) {
    link.onClickFromProps = link.onClick;
    link.onClick = e =&gt; this._onItemClick(e, link.onClickFromProps);
 }



onItemClick(e, onClickFromProps) {
    console.log(""Custom click event handler called"");
    if (onClickFromProps) 
      onClickFromProps(e);
}
</code></pre>

<p>I want to unit test the above functionality using Jest.  </p>

<pre><code>const component= mount(&lt;Comp /&gt;);
const mock2 = jest.fn();
component.setProps({ items: [{links: [{ name: 'Test', key: 'Test', url: 'Test', onClick: mock2 }]}] });
const link= component.find('.nav-link');
navLink.simulate('click');
expect(mock2.mock.calls.length).toBe(1);
</code></pre>

<p>the test is passing, however I am not getting the <code>console.log</code> statement written in <code>onItemClick</code> method. When I try to debug this test, it is not even going into <code>onItemClick</code> after the simulate click is called.</p>

<p>the <code>navLink</code> does show an <code>&lt;a&gt;</code> tag. </p>

<p>when I log <code>navLink.props().onClick</code>, it shows <code>[Function: bound]</code> </p>
",https://stackoverflow.com/questions/53491761/unit-testing-onclick-handler-using-jest-in-react,"['javascript', 'reactjs', 'unit-testing', 'jestjs', 'enzyme']",786,FALSE,1,0
Unit Testing ReactiveCocoa SignalProducer keeps coming back interrupted,"<p>Ive been unit testing ReactiveCocoa Signals and Producers using XCTest expectations for a project im working on. For one some reason (I suspect after a pod update) my tests started failing and SignalProducer events are returning the interrupted value and never actually sending the successful value. If I set breakpoints everything seems to work fine in the actual task its just when it gets to the observer lifecycle where i dont see the value passed back.
Using XCode 9.4.1
ReactiveCocoa (8.0.0)
ReactiveSwift (4.0.0)
Result (4.0.0)</p>

<pre><code>let signalExpectation = self.expectation(description: ""Signal Expectation"")   
let aSut =  SignalProducer&lt;Data,WXClientError&gt; { observer, _ in
            let task = URLSession.shared.dataTask(with: url!) { (data, URLResponse, Error) in   if let Error = Error {
                    observer.send(error: WXClientError.webFailure(description: Error.localizedDescription))
                } else if let httpResponse = URLResponse as? HTTPURLResponse {
                    if httpResponse.statusCode == 200 {
                        observer.send(value:data!)
                    }
                }
            }
            task.resume()
        }

        let testObserver = Signal&lt;Data,WXClientError&gt;.Observer{ (event) in
            switch event {
            case let .value(v):
                print(""Test Observation value = \(v)"")
                signalExpectation.fulfill()
            case let .failed(error):
                print(""Test Observation error = \(error)"")
            case .completed:
                print(""Test Observation completed"")
            case .interrupted:
                print(""Test Observation interrupted"")
            }
        }
        aSut.start(testObserver)  
        self.waitForExpectations(timeout: 5.0, handler:nil)
</code></pre>
",https://stackoverflow.com/questions/51664150/unit-testing-reactivecocoa-signalproducer-keeps-coming-back-interrupted,"['ios', 'swift', 'unit-testing', 'asynchronous', 'reactive-cocoa']",522,FALSE,1,0
"Jasmine unit testing, issue with .subscribe on ActivatedRoute","<p><strong>Background</strong>: We recently upgraded to angular 6, we are using RXJS 6.1.0, rxjs-compat 6.1.0, and jasmine-core 2.99.1. Our tests had been broken for a bit, so im not sure when this test started to fail.</p>

<p><strong>Issue</strong>: Whenever I go to run the unit test, i got this error on the first test.</p>

<pre><code>TypeError: this.activatedRoute.paramMap.subscribe is not a function
</code></pre>

<p><br/>
<br/>
<strong>Preface</strong>: Now, when you use the below code segment. It creates a mockRoute with the value of paramMap as a function. It is supposed to have the function return the value specified, in this case an Observable of type Number.</p>

<p>component.spec.ts</p>

<pre><code>mockRoute = jasmine.createSpyObj('mockRoute', ['paramMap']);
(&lt;any&gt;mockRoute.paramMap).and.returnValue(of({ orderId }));
sut = new ContractSchedulesComponent(&lt;Store&lt;AppState&gt;&gt;&lt;any&gt;mockStore, 
      actions, mockRoute, null);
sut.ngOnInit();
</code></pre>

<p>Here is the code segment that it is failing on:</p>

<p>component.ts</p>

<pre><code>ngOnInit() {
    const routeSub = this.activatedRoute.paramMap.subscribe(paramMap =&gt; {
            this.orderId = paramMap['params']['orderId']; 
</code></pre>

<p><br/>
<br/>
I know that it is failing because paramMap is a function and subscribe does not work on a function, even though it is supposed to return an Observable via the unit test.</p>

<p>Curious if this is maybe a bug between jasmine and the newer version of RXJS. But maybe i have done something wrong and i just cant see it. Would appreciate any help you guys could give. Also, if you need more insight into any of the code i can post more. Thanks!</p>
",https://stackoverflow.com/questions/51087579/jasmine-unit-testing-issue-with-subscribe-on-activatedroute,"['angular', 'unit-testing', 'jasmine', 'angular-ui-router']",1537,FALSE,1,0
How to set up Unit Testing using FETCH,"<p>I have been trying to set up a unit testing on VSC - JS /React for the following code below. </p>

<pre><code>getNotificationgetNotificationCount = () =&gt;{
fetch(`${this.state.services.NotificationReporting.URL}/NOTIFICATIONS?$count=true&amp;$filter=contains(Notified,'${this.state.user.Email}') and Status eq 'Unread'`, {
  headers: {
    'Content-Type': 'application/json',
    'Ocp-Apim-Subscription-Key': this.state.services.NotificationReporting.subscription_key,
    ""DDHFirm"": this.state.user.DDHFirm
  },
  method: 'GET',
  credentials: 'include',
})
.then(res =&gt; {return(validationManager.ResolveHTTPResponse(res, 'Request Successful', 'Request Failed', res.ok ? true : false))})
  .then(response =&gt; {
    this.setState({
      unreadNotifications: response.body ? response.body['@odata.count'] : 0,
    })
  })
</code></pre>

<p>}</p>

<p>Expecting the function/method gets call at the moment. Actual results will be handle later</p>
",https://stackoverflow.com/questions/53856811/how-to-set-up-unit-testing-using-fetch,"['javascript', 'reactjs', 'unit-testing']",317,TRUE,1,1
Unit Testing ItemChanged on ReactiveList Triggering Property Change,"<p>Boiled down: I need to delay execution in my unit test thread so that an observable has time to update a property. Is there a Reactive way to do this without having to resort to Thread.Sleep?</p>

<p>I have a ViewModel that manages a ReactiveList of ""Thing"". Both ThingViewModel and the main ViewModel are derived from ReactiveObject. Thing has an IsSelected property and the ViewModel has a SelectedThing property that I keep synched based on observing changes on IsSelected. I have a couple of different views that use the ViewModel and this allows me to synch the selected Things between those views nicely. And it works. The problem comes when I try to unit test this interaction.</p>

<p>The ViewModel has this subscription in its constructor:</p>

<pre><code>Things.ItemChanged.Where(c =&gt; c.PropertyName.Equals(nameof(ThingViewModel.IsSelected))).ObserveOn(ThingScheduler).Subscribe(c =&gt;
{
    SelectedThing = Things.FirstOrDefault(thing =&gt; thing.IsSelected);
});
</code></pre>

<p>In my unit test, this assert always fails:</p>

<pre><code>thingVM.IsSelected = true;
Assert.AreEqual(vm.SelectedThing, thingVM);
</code></pre>

<p>But this assert always passes:</p>

<pre><code>thingVM.IsSelected = true;
Thread.Sleep(5000);
Assert.AreEqual(vm.SelectedThing, thingVM);
</code></pre>

<p>Essentially, I need to wait long enough for the subscription to complete the change. (I don't really need that long to wait as when running in the UI, it's pretty snappy.)</p>

<p>I tried adding an observer in my unit test to wait on that processing, hoping they'd be similar. But that's been a wash. Here's what didn't work.</p>

<pre><code>var itemchanged = vm.Things.ItemChanged.Where(x =&gt; x.PropertyName.Equals(""IsSelected"")).AsObservable();
. . . 
thingVM.IsSelected = true;
var changed = itemChanged.Next();
Assert.AreEqual(vm.SelectedThing, thingVM);
</code></pre>

<p>Moving the itemChanged.Next around didn't help, nor did triggering iteration by calling .First() or .Any() on <code>changed</code> (both of those hung the process as it blocked the thread for a notification that never occurred).</p>

<p>So. Is there a Reactive way to wait on that interaction so that I can Assert that the property change is happening correctly? I messed around some with TestScheduler (I needed manual Scheduler setting for the UI anyway, so this wasn't hard), but that doesn't seem to apply, as the actual action given to the scheduler happens in my ViewModel on ItemChanged and I couldn't find a way to make that trigger in the ways TestScheduler seems set up to work.</p>
",https://stackoverflow.com/questions/48527676/unit-testing-itemchanged-on-reactivelist-triggering-property-change,"['c#', 'unit-testing', 'reactiveui']",544,TRUE,1,2
Unit testing a method with user input validations,"<p>I have a method that takes user inputs and validates them until they enter a correct value. I am not sure how to write a unit test for this method since it already validates the user input.</p>

<pre><code>def refreshtime_validation():
    while True:
        try:
            runtime_input = float(raw_input(""Enter Refresh Time (in seconds): ""))
        except ValueError:
            print ""\n**Please enter a valid number (Must be an integer).**\n""
            continue
        if runtime_input &lt;= 0:
            print ""\n**Please enter a valid number (Must be greater than 0).**\n""
            continue
        else:
            return runtime_input
</code></pre>

<p>How do I go about in writing a unit test for this method? The only one I have so far is</p>

<pre><code>self.assertEquals('1','1')    
self.assertEquals('100','100')
self.assertEquals('100000','100000')
</code></pre>
",https://stackoverflow.com/questions/53688071/unit-testing-a-method-with-user-input-validations,"['python', 'python-2.7', 'unit-testing', 'tdd']",879,TRUE,1,1
ReferenceError: Quill is not defined while unit testing,"<p>I got  <a href=""https://github.com/primefaces/primeng/issues/807"" rel=""nofollow noreferrer"">this same issue</a> and i resolved it and working perfectly when i run the application. </p>

<p>But same issue am getting right now while run the unit test. am using karma and jasmine tool. </p>

<p>I have tried include quill.js file in karma.config.js fill as well. </p>

<pre><code>  files: ['./node_modules/quill/quill.js',
          { pattern: './src/test.ts', watched: true }
        ],
</code></pre>

<p>but still am facing the same issue. </p>

<p>Any idea to resolve this issue?</p>
",https://stackoverflow.com/questions/48708937/referenceerror-quill-is-not-defined-while-unit-testing,"['angular', 'typescript', 'jasmine', 'primeng', 'quill']",2474,TRUE,1,2
Unit testing for REST with Client and invokation,"<p>I would like to write unit tests for my endpoints when the endpoint is calling another application.
So far I could test if the Invocation has correct URI or method type, but I would like mock the response.</p>

<pre><code>public Response getFormById(Integer formId) {
        Invocation invocation = prepareRequestForGettingForm(formId);
        Response response = invocation.invoke();
        return response;
    }

public Invocation prepareRequestForGettingForm(Integer formId) {
        return ClientBuilder
                .newClient()
                .register(authenticator)
                .target(""localhost:8080"" + ""/form"" + formId)
                .request(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .build(""get"");
    }
</code></pre>

<p>TEST:</p>

<pre><code>  @Test
        public void request_getFormById_shouldContainsProperEndpointAddress() {
            String expectedUri = expectedUriBase + formId;
            Invocation invocation = mock.prepareRequestForGettingForm(formId);
            String uri = ((ClientInvocation) invocation).getUri().toString();
            assertEquals(uri, expectedUri);
            when(invocation.invoke()).thenReturn(Response.ok().build());
            Response response = formServiceBean.getFormById(formId);
            assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
        }
</code></pre>

<p>When I try to mock the invocation.invoke then I have error:</p>

<pre><code>javax.ws.rs.ProcessingException: RESTEASY004655: Unable to invoke request

    at org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine.invoke(ApacheHttpClient4Engine.java:317)
</code></pre>

<p>So can Anybody tell me how to mock it? </p>

<p>Is there any chance also to use Rest-Assure but do it smartly to have later on Code Coverage?</p>
",https://stackoverflow.com/questions/53479475/unit-testing-for-rest-with-client-and-invokation,"['java', 'rest', 'unit-testing', 'resteasy']",209,FALSE,1,0
Unit testing a Vue.js/Node.js app with Websockets,"<p>I have a Vue (3.0.3) project that pairs with a Node.js server. How in the world would I go about unit testing this? This is for a game that uses web-sockets to communicate.</p>

<p>Can anyone point me in the right direction? Thanks.</p>
",https://stackoverflow.com/questions/52584184/unit-testing-a-vue-js-node-js-app-with-websockets,"['javascript', 'node.js', 'vue.js']",210,TRUE,1,1
Unit testing canActivate as an Observable crashes karma,"<p>When I try to unit test my guard, it fails in an odd way.  If I try to subscribe to the Observable returned by <code>canActivate</code>, the tests freeze and eventually Karma disconnects citing a timeout:</p>

<blockquote>
  <p>WARN [HeadlessChrome 0.0.0 (Mac OS X 10.13.0)]: Disconnected (1
  times), because no message in 10000 ms.</p>
</blockquote>

<p>The guard itself functions fine in the application, it's only causing issues in the test.  Raising the timeout value does not solve the issue.</p>

<p>This <strong>doesn't</strong> crash:</p>

<pre><code>it('...', async(() =&gt; {
    guard.canActivate(
        { params: { id: 'a' } as any } as ActivatedRouteSnapshot
    );
}));
</code></pre>

<p>This <strong>does</strong> crash (only change is adding <code>.subscribe()</code>):</p>

<pre><code>it('...', async(() =&gt; {
    guard.canActivate(
        { params: { id: 'a' } as any } as ActivatedRouteSnapshot
    ).subscribe();
}));
</code></pre>

<p>This <strong>does</strong> crash too, using Jasmine's done callback:</p>

<pre><code>it('...', done =&gt; {
    guard.canActivate(
        { params: { id: 'a' } as any } as ActivatedRouteSnapshot
    ).subscribe(x =&gt; done());
});
</code></pre>

<hr>

<p>Test source:</p>

<pre><code>describe('Guard', () =&gt; {
    let store: Store&lt;fromRoot.State&gt;;
    let guard: Guard;

    beforeEach(() =&gt; {
        TestBed.configureTestingModule({
            imports: [
                RouterTestingModule.withRoutes([]),
                StoreModule.forRoot(reducers)
            ],
            providers: [
                Guard
            ]
        });

        store = TestBed.get(Store);
        guard = TestBed.get(Guard);
    });

    it('...', async(() =&gt; {
        guard.canActivate(
            { params: { id: 'a' } as any } as ActivatedRouteSnapshot
        ).subscribe();

        expect(1).toBe(1);
    }));
});
</code></pre>

<p>Guard source:</p>

<pre><code>@Injectable()
export class Guard implements CanActivate {
    constructor(
        private store: Store&lt;fromRoot.State&gt;,
        private router: Router
    ) {}

    getFromStoreOrApi(id: string): Observable&lt;any&gt; {
        return this.store.select(fromRoot.selectState)
            .do(state =&gt; {
                if (!state.entities[id]) {
                    this.store.dispatch(new actions.Get(id));
                }
            });
    }

    canActivate(route: ActivatedRouteSnapshot): Observable&lt;boolean&gt; {
        return this.getFromStoreOrApi(route.params.id)
            .switchMap(() =&gt; Observable.of(true))
            .catch(() =&gt; Observable.of(false));
    }
}
</code></pre>
",https://stackoverflow.com/questions/48349544/unit-testing-canactivate-as-an-observable-crashes-karma,"['angular', 'jasmine', 'rxjs']",1377,TRUE,1,1
MVVM Cross null references when unit testing MxvAsyncCommand,"<p>We have recently upgraded to MvvMCross 6.2.2 and noticed we had to change to use Mvx.IoCProvider.  </p>

<p>We have found that if we are constructing an MvxAsyncCommand in a ViewModel this causes a null reference exception on all unit tests that call this constructor</p>

<p>*</p>

<pre><code>Result StackTrace:  
at MvvmCross.Commands.MvxCommandBase..ctor()
   at MvvmCross.Commands.MvxAsyncCommand..ctor(Func`1 execute, Func`1 canExecute, Boolean allowConcurrentExecutions)
   at App.Mobile.Core.ViewModels.TestViewModel..ctor(IMvxNavigationService navigation, ITestService encService, ILogger logger)
   at App.Mobile.Core.UnitTests.TestViewModelTests.&lt;TestViewModel_Prepare&gt;d__1.MoveNext()
</code></pre>

<p>*</p>

<p>Looking at the source in github the problem is due to Mvx.IocProvider being null.</p>

<pre><code>public MvxCommandBase()
    {
        if (!Mvx.IoCProvider.TryResolve&lt;IMvxCommandHelper&gt;(out _commandHelper))
            _commandHelper = new MvxWeakCommandHelper();

        var alwaysOnUIThread = MvxSingletonCache.Instance == null || MvxSingletonCache.Instance.Settings.AlwaysRaiseInpcOnUserInterfaceThread;
        ShouldAlwaysRaiseCECOnUserInterfaceThread = alwaysOnUIThread;
    }
</code></pre>

<p>A fix has been implemented in the ""develop"" branch but this isn't available on nuget.  </p>

<pre><code>public MvxCommandBase()
    {
        // fallback on MvxWeakCommandHelper if no IoC has been set up
        if (!Mvx.IoCProvider?.TryResolve(out _commandHelper) ?? true)
            _commandHelper = new MvxWeakCommandHelper();

        // default to true if no Singleton Cache has been set up
        var alwaysOnUIThread = MvxSingletonCache.Instance?.Settings.AlwaysRaiseInpcOnUserInterfaceThread ?? true;
        ShouldAlwaysRaiseCECOnUserInterfaceThread = alwaysOnUIThread;
    }
</code></pre>

<p>Does anyone know of a workaround to initialize this IoCProvider within our unit test projects. </p>
",https://stackoverflow.com/questions/53597908/mvvm-cross-null-references-when-unit-testing-mxvasynccommand,['mvvmcross'],955,TRUE,1,1
Unit Testing Code which contains Linux system calls,"<p>I am new to unit testing in C++. I am using googletest for performing unit testing(and gcovr for coverage report) of the sources which contains linux system calls. To test them I thought of 2 approaches</p>

<p><strong>1. Using **LD_PRELOAD</strong> (by stubbing own implementation of system calls such as write,read etc.)**</p>

<p><strong>2. Using --wrap</strong> linker options to wrap actual system call with my stub implementation.</p>

<p>Using option 2 is little infeasible as the number of system calls used are more (open,write,read,fseek,socket and so on), hence I thought of using Method 1.</p>

<p>However, I am not able to generate coverage report using Method 1 (I do compile my stub library with --coverage options). It is getting locked when I see strace. I don't know how to solve this problem. So I thought of keeping system calls instead create dummy device files and work on them. (for example: /sys/devices/system/cpu1/online --> /home/user/dummy/cpu/online). </p>

<p>Now, I want to simulate a error condition from write system call to this file, but it does not seem to work (I already set for example O_NONBLOCK flag of the dummy file using fcntl function).</p>

<p>I need suggestions on </p>

<p><strong>1. Using method 1, how to generate coverage report?</strong></p>

<p><strong>2. If this is not possible, how to set the same properties of the dummy file as device file.</strong></p>

<p>Just a snapshot of my code:
openstub.c</p>

<pre><code>#include &lt;sys/types.h&gt;
#include &lt;sys/stat.h&gt;

int open(const char *pathname, int flags, mode_t mode)
{
  if(mode ==1)
    {
      return 1;
    }
  else
    {
      return 0;
    }
}
</code></pre>

<p>usingopen.c</p>

<pre><code>#include&lt;stdio.h&gt;
#include &lt;sys/types.h&gt;
#include &lt;sys/stat.h&gt;
#include &lt;fcntl.h&gt;

int main()
{
  char dummypath[]=""dummypath"";
  int filehandle;
  filehandle = open(dummypath,O_WRONLY);
  if(0&gt;filehandle)
    printf(""i am NOT using stubs\n"");
  else if(filehandle ==1) {
    printf(""I am using stub\n"");
  }
  else
    {
      printf(""I am using stub with Not the WRITE mode\n"");
    }
}
</code></pre>

<hr>

<p>compile command: </p>

<pre><code>gcc -shared -fPIC -ftest-coverage -fprofile-arcs openstub.c -o openstub.so
</code></pre>

<p>for usingopen</p>

<pre><code>gcc -ftest-coverage -fprofile-arcs -o usingopen usingopen.c
</code></pre>

<p><code>gcovr -f usingopen</code> (this gets stuck after LD_PRELOAD set to openstub.so)</p>

<p>Thank you for your suggestions!</p>
",https://stackoverflow.com/questions/52005873/unit-testing-code-which-contains-linux-system-calls,"['c++', 'linux', 'unit-testing', 'system-calls', 'gcovr']",908,FALSE,1,0
Unit Testing InterruptedException for ThreadPoolTaskExecutor with Mockito Spy,"<p>I am using spring's <code>ThreadPoolTaskExecutor</code> for executing tasks in multiple threads. The class looks like below</p>

<pre><code>    @Component
    public class LoadData {
    //... ...    

        @Inject
        private ThreadPoolTaskExecutor taskExecutor;

        public SomeData getData(Long id) {
            Future&lt;SomeData&gt; loadData = taskExecutor.submit(() -&gt; {
                    //return methodToGetDataSynchronously(id);
                    return new SomeData();
            });
            try {
                SomeData data = loadData.get();
            } catch (InterruptedException | ExecutionException e) {
                logger.error(""error"");
                //some more processing for the error here
            }
            return data;
       }
  }
</code></pre>

<p>To be able to unit test this class and cover the <code>InterruptedException</code> and <code>ExecutionException</code> branches, I have tried multiple approaches (using <code>Mockito</code> <code>Spy</code>), but have not been able to successfully test this.</p>

<p>Unit test class looks like below:</p>

<pre><code>@RunWith(MockitoJUnitRunner.class)
public class LoadDataTest {

    @InjectMocks
    private LoadData loadData;

    @Spy
    private ThreadPoolTaskExecutor spyTaskExecutor = new ThreadPoolTaskExecutor();

    @Before
    public void init() {
        MockitoAnnotations.initMocks(this);
        spyTaskExecutor.setCorePoolSize(1);
        spyTaskExecutor.setWaitForTasksToCompleteOnShutdown(true);
        spyTaskExecutor.initialize();
    }

    @Test
    public void testGetData_shouldThrowInterruptedException () {
        Mockito.when(spyTaskExecutor.submit(Matchers.&lt;Callable&lt;SomeData&gt;&gt;any())).thenAnswer(new Answer&lt;Future&lt;SomeData&gt;&gt;() {
            public Future&lt;SomeData&gt; answer(InvocationOnMock invocation) throws Throwable {
                Future&lt;SomeData&gt; future = Mockito.mock(FutureTask.class);
                when(future.isDone()).thenReturn(false, false, true);
                when(future.get()).thenThrow(new InterruptedException ());
                return future;
            }
        });

        SomeData result = null;
        result = loadData.getData(101L);
        //verify here that InterruptedException processing was performed
    }
}
</code></pre>

<p>I am using <code>Spy</code> for <code>ThreadPoolTaskExecutor</code> as I have other methods in the Test that tests the actual behavior of the multi threaded execution.
When I try to run the test method, it throws <code>NullPointerException</code> on stubbing spy:</p>

<pre><code>Mockito.when(spyTaskExecutor.submit(Matchers.&lt;Callable&lt;SomeData&gt;&gt;any()))...
</code></pre>

<p>The exception:</p>

<pre><code>java.lang.NullPointerException
    at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:132)
    at org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor.submit(ThreadPoolTaskExecutor.java:320)
at com.company.LoadDataTest.testGetData_shouldThrowInterruptedException(LoadDataTest.java:20)
</code></pre>

<p>I think, the problem may be with the way I am stubbing the Mockito Spy. However, I am not sure if I am on the right path here to stub the <code>InterruptedException</code>. Has anyone got a sample of how to achieve this?</p>

<p>Versions:</p>

<pre><code>  jdk-1.8.0_72
  junit-4.12
  mockito-core-1.10.19
  spring-context-4.3.4.RELEASE
</code></pre>

<p>Note: this is an extract of the actual code. The actual code performs many other things and have many other beans injected into it - some of which are <code>Mock</code> in the <code>Test</code>, some are <code>Spy</code> - depending on what I am testing. I have only mentioned the part which I am facing an issue with here.</p>
",https://stackoverflow.com/questions/52436254/unit-testing-interruptedexception-for-threadpooltaskexecutor-with-mockito-spy,"['java', 'spring', 'junit', 'mockito', 'interrupted-exception']",7423,TRUE,1,1
What is the point in unit testing mock returned data?,"<p>Consider the scenario where I am mocking certain service and its method. </p>

<pre><code>Employee emp = mock(Employee.class);
when(emp.getName(1)).thenReturn(""Jim"");
when(emp.getName(2)).thenReturn(""Mark"");

//assert
assertEquals(""Jim"", emp.getName(1));
assertEquals(""Mark"", emp.getName(2));
</code></pre>

<p>In the above code when <code>emp.getName(1)</code> is called then mock will return Jim and when <code>emp.getName(2)</code> is called mock will return Mark. My Question is I am declaring the behavior of Mock and checking it <code>assertEquals</code> what is the point in having above(or same kind of) assert statements? These are obviously going to pass. it is simply like checking <code>3==(1+2)</code>  what is the point? When will these tests fail (apart from changing the return type and param type)?</p>
",https://stackoverflow.com/questions/48711883/what-is-the-point-in-unit-testing-mock-returned-data,"['java', 'unit-testing', 'junit', 'mocking', 'mockito']",4258,TRUE,14,5
Akka.NET Persistence unit testing - PersisteAll/PersistAllAsync never runs,"<p>I have a problem in some unit tests of a ReceivePersistentActor implementation using PersistAll and PersistAllAsync methods.</p>

<p>The problem is that when unit testing with TestKit.NUnit, the PersistAll/Async calls never call their completion callbacks. Persist/Async calls work fine however and the PersistAll/Async calls work fine outside of unit testing.</p>

<p>Has this something to do with TestKit and the way it tries to run things on the CallingThreadDispatcher?</p>

<p>I'm not sure how to write unit tests for code where PersistAll/Async is used - the tests always fail by timing out due to the callbacks never being invoked (where I have my Sender.Tell code).</p>

<p>I'm not doing anything weird - i'm using the in-memory journal and snapshot-store and these are running on the default dispatcher (I tried using calling-thread dispatcher for these but then nothing worked at all in the unit tests).</p>

<p>public interface IEvent;<br>
public class Test : ReceivePersistentActor {</p>

<pre><code>    public class StringReceivedEvent:IEvent {}

    public Test()
    {
        Console.WriteLine(""Started""); // &lt;-- This is seen, but the next console output is not - callback is never fired
        Command&lt;string&gt;(message =&gt; { 
            Console.WriteLine($""Received {message}"");

            PersistAll(new List&lt;IEvent&gt;(){new StringReceivedEvent()}, @event =&gt; {
                Console.WriteLine(""Persisted event""); //&lt;-- never see this
                Sender.Tell(true); //&lt;-- this never gets called
            });
        });
    }

    public override string PersistenceId =&gt; ""test-id"";
}

[TestFixture]
public class Tests : Akka.TestKit.NUnit.TestKit
{
    IActorRef subject;

    public PublishingTests() : base(ConfigurationFactory.Load().WithFallback(Akka.TestKit.Configs.TestConfigs.DefaultConfig))
    {
    }

    [SetUp]
    public void Setup() {
        subject = ActorOf(Props.Create&lt;Test&gt;(), ""My-Test-Actor"");
    }

    [Test]
    public void Can_Persist_Event_And_Send_Completion_Reply() {

        subject.Tell(""hello"");
        ExpectMsg&lt;bool&gt;(TimeSpan.FromSeconds(15)); //&lt;---- This times out

    }
}
</code></pre>
",https://stackoverflow.com/questions/49723591/akka-net-persistence-unit-testing-persisteall-persistallasync-never-runs,"['unit-testing', 'nunit', 'persistence', 'akka.net', 'testkit']",355,TRUE,1,1
Spring mvc rest Controller unit testing with testNG,"<p>I have a rest controller in Spring mvc application like below:
I searched lot of examples on net, but most of them are with junit.I want to do unit test with testNg</p>

<p>public class SomeController {</p>

<pre><code>@Autowired
private GeneralManager generalManager;

@Autowired
private DataManager dataManager;



@RequestMapping(value=""/submit"", method = RequestMethod.POST, produces=""application/json"")
public Object processSubmit(@RequestBody String inputData, @RequestHeader(""authtoken"") String atoken) {

    MessageEntity msgObj = """"
    if(generalManager.checktoken(atoken)){
        try{
            return dataManager.processSubmit(inputData);
        }catch (Exception e) {
            logger.error(""Exception occurred in submitting the  data"",e);
            msgObj.setMessageId(1);
            msgObj.setMessage(""Exception in processSubmit. Failed to submit the  data."");

        }
    }else{
        return new ""Exception""
    }

    return msgObj;
}
</code></pre>

<p>I need to unit test the above code.The input is Json String(big Json payload).
How do I unit test the above controller with testNG in my Spring mvc application?</p>

<p>In actual method, I am taking inputdata string(that Json payload) and building entities by extracting json payload.How do I pass this json String(payload) to testNG unit test class?</p>
",https://stackoverflow.com/questions/52977134/spring-mvc-rest-controller-unit-testing-with-testng,"['java', 'unit-testing', 'spring-mvc', 'testng']",218,FALSE,1,0
Unit Testing with libgdx and own GameText Class,"<p>I have created a GameTest Class for extending my Testclasses, but when I use them I get the following error:</p>

<pre><code>com.badlogic.gdx.utils.GdxRuntimeException: Couldn't load shared library 'gdx64.dll' for target: Windows 8.1, 64-bit
</code></pre>

<p>My Class:</p>

<pre><code>public class GameTest {
    // This is our ""test"" application
    private static Application application;

    // Before running any tests, initialize the application with the headless backend
    @BeforeClass
    public static void init() {
        // Note that we don't need to implement any of the listener's methods
        application = new HeadlessApplication(new ApplicationListener() {
            @Override public void create() {}
            @Override public void resize(int width, int height) {}
            @Override public void render() {}
            @Override public void pause() {}
            @Override public void resume() {}
            @Override public void dispose() {}
        });

        // Use Mockito to mock the OpenGL methods since we are running headlessly
        Gdx.gl20 = Mockito.mock(GL20.class);
        Gdx.gl = Gdx.gl20;
    }

    // After we are done, clean up the application
    @AfterClass
    public static void cleanUp() {
        // Exit the application first
        application.exit();
        application = null;
    }
}
</code></pre>

<p>Can someone help me in which direction I should solve the problem ?</p>
",https://stackoverflow.com/questions/53031633/unit-testing-with-libgdx-and-own-gametext-class,['libgdx'],242,FALSE,1,1
unit testing with the input and output validation,"<p>I am completely new to Unit Testing in Android. I want to write the unit test for a method in my presenter class. </p>

<p><strong>Sharing the methods need to be covered with unit test</strong> </p>

<pre><code> override fun getRequiredUri(uri: Uri): Uri {
    val moduleName = uri.moduleName
    return when (moduleName) {
        ""sample"" -&gt; getStandardUriFromSampleUri(uri)
        ""application"" -&gt; getStandardAppLaunchUri(uri)
        else -&gt; {
            return uri
        }
    }
}

private fun getStandardUriFromSampleUri(uri: Uri): Uri {
    var stringUrl = uri.toString()
    stringUrl = stringUrl.replaceFirst(""/sample"", """")
    var standardUri = Uri.parse(stringUrl)
    val moduleName = uri.moduleName
    if(moduleName == ""application""){
        standardUri = getStandardAppLaunchUri(uri)
    }
    return standardUri
}

private fun getStandardAppLaunchUri(uri: Uri): Uri {
    var stringUrl = uri.toString()
    stringUrl = stringUrl.replaceFirst(""application"", ""link/application"")
    return  Uri.parse(stringUrl)
}
</code></pre>

<p><strong>I am sharing my test class that I have tried to implement:</strong> </p>

<pre><code>class PresenterTest {

   lateinit var presenter: Presenter
   @Mock
   lateinit var mockActivity: Activity
   @Mock
   lateinit var mockUri: Uri

   @Before
   fun setUp() {
       MockitoAnnotations.initMocks(this)
       presenter = Presenter()
       presenter.view = mockActivity
   }

   @Test
   fun shouldGenerateStandardUriFromNewUri() {
       val input = Uri.parse(""https://example.org/sample/account/edit"")
       val expectedOutput = Uri.parse(""https://example.org/account/edit"")
       val output = presenter. getRequiredUri(input)
       assertTrue(output == expectedOutput)
   }

}
</code></pre>

<p>This line is getting failed always with class not found an exception. </p>

<pre><code>val output = presenter.getRequiredUri(input)
</code></pre>

<p>Is this the right way to unit test the method? If yes, please suggest the changes that I need to make. If no, then please suggest the alternative ways.</p>
",https://stackoverflow.com/questions/53851456/unit-testing-with-the-input-and-output-validation,"['android', 'unit-testing', 'junit', 'kotlin']",140,TRUE,1,1
Vue Unit Testing - Mocking a plugins return value,"<p>I have a custom plugin that returns a boolean. Rather than importing the plugin to the test, I want to mock this value. I can mock the plugin easily enough, but how can I change the return value in the test?</p>

<pre><code>const $mq = () =&gt; {};    
wrapper = shallowMount(Component, { 
  //...
  mocks: {
    $mq
  }
  //...
});
</code></pre>

<p>Test</p>

<pre><code>it ('Test description', () =&gt; {
  wrapper.vm.$mq = () =&gt; true; // HOW TO MOCK PLUGIN RETURNS???
});
</code></pre>
",https://stackoverflow.com/questions/50830171/vue-unit-testing-mocking-a-plugins-return-value,"['javascript', 'unit-testing', 'vue.js', 'vue-test-utils']",971,TRUE,1,1
Unit testing mongoose model with Chai and Mocha,"<p>I am trying to run the unit testing on my Nodejs application using Mocha and Chai. I am using Mongodb with Mongoose Framework. Here is my student.model.js </p>

<pre><code>var mongoose = require('mongoose')
var studentsSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    name: {
        type: String,
        required: true
    },
    email: String,
    phone: Number,
    address: String,
    username: String,
    password: String
});


var Students = mongoose.model('Student', studentsSchema);


module.exports = Students;
</code></pre>

<p>And this is my student.model.test.js</p>

<pre><code>let assert = require('chai').assert;
var expect = require('chai').expect;
var mongoose = require('mongoose');
var Students = require('../models/students.model');

describe ('Student',function(){

    before(function (done) {
        mongoose.connect('mongodb://localhost/mongoose_basics');
        const db = mongoose.connection;
        db.on('error', console.error.bind(console, 'connection error'));
        db.once('open', function() {
          console.log('We are connected to test database!');
          done();
        });
      });

    it('student works!',function(){
        var s = new Students({name:'krishna'});

        s.save(err =&gt; {
            if(err) { return done(); }
            throw new Error('Should generate error!');
          });

    });
    after(function(done){
        mongoose.connection.db.dropDatabase(function(){
          mongoose.connection.close(done);
        });
      });

});
</code></pre>

<p>I want to run the unit test using Mocha and Chai. When I run <code>mocha student.model.test.js</code> I am getting following error </p>

<pre><code>TypeError: Students is not a constructor
</code></pre>

<p>I am not sure why it's returning not a constructor. </p>
",https://stackoverflow.com/questions/51465519/unit-testing-mongoose-model-with-chai-and-mocha,"['node.js', 'mongoose', 'mocha.js', 'tdd', 'chai']",2607,FALSE,1,1
Unit testing of exported function using react / enzyme,"<p>I have an exported function, which I import and use in my react component:</p>

<pre><code>//in App.js
import { getSum } from ""../helpers/helpers.js;
//some react component code here.

//in helpers.js
export function getSum(arg1, arg2){return arg1+arg2; }
</code></pre>

<p>in my test suite, normal testing of non-imported react components is fine, but 
but I am not sure how to call the exported ""helper"" function in the other file.</p>

<pre><code>describe('App', () =&gt; {

it('correctly calculates the sum of 1 and 3', () =&gt; {
        const wrapper = shallow(&lt;App /&gt;);
        assert.equal(wrapper.instance().getSum(1, 3), 4);
    });

});
</code></pre>

<p>results in</p>

<pre><code> TypeError: wrapper.instance(...).getSum is not a function
        at Context.&lt;anonymous&gt; (client/test/index.js:191:5325)
</code></pre>

<p>How would I properly locate and call the function ""getSum"" in my test suite?</p>
",https://stackoverflow.com/questions/52506155/unit-testing-of-exported-function-using-react-enzyme,"['javascript', 'reactjs', 'unit-testing', 'enzyme']",1092,TRUE,1,1
Accessing private ArrayList while unit testing (Java/JUnit),"<p>Writing unit tests (JUnit) for a class that manipulates an ArrayList of objects. Is it possible to directly test the contents of that ArrayList, or do I just need to test the function that returns formatted information from ArrayLists and use that to test the rest of the program? (code below)</p>

<pre><code>import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;

public class HardeWareStore {
  private ArrayList&lt;Item&gt; itemList;

  public HardwareStore() throws IOException {
    itemList = new ArrayList&lt;&gt;();
  }


  public String getAllItemsFormatted() {
    return getFormattedItemList(itemList);
  }

private String getFormattedItemList(ArrayList&lt;Item&gt; items) {

    String text = "" ------------------------------------------------------------------------------------\n"" +
            String.format(""| %-10s| %-25s| %-20s| %-10s| %-10s|%n"", ""ID Number"", ""Name"", ""Category"", ""Quantity"", ""Price"") +
                  "" ------------------------------------------------------------------------------------\n"";

    for (int i = 0; i &lt; items.size(); i++) {
        text += String.format(""| %-10s| %-25s| %-20s| %-10s| %-10s|%n"",
                items.get(i).getIdNumber(),
                items.get(i).getName(),
                items.get(i).getCategory(),
                Integer.toString(items.get(i).getQuantity()),
                String.format(""%.2f"", items.get(i).getPrice()));
    }
    text += "" ------------------------------------------------------------------------------------\n"";

    return text;
}

public void addNewItem(String idNumber, String name, String category, int quantiy, float price) {
    //If passed all the checks, add the item to the list
    itemList.add(new Item(idNumber, name, category, quantiy, price));
    System.out.println(""Item has been added.\n"");
}
</code></pre>

<p>(This is an assignment, so changing the source code in any way is not an option)</p>

<p>Is there any way for a test class to know what is in ""itemList"", so I can test the ""addNewItem"" method without relying on another method like ""getFormattedItemList""?</p>
",https://stackoverflow.com/questions/49528256/accessing-private-arraylist-while-unit-testing-java-junit,"['java', 'junit']",1190,TRUE,1,1
Unit testing code with Google Cloud API dependencies,"<p>I'm writing a small slack bot which helps my developers get DB dumps from Google Cloud SQL. I've written it using <a href=""https://godoc.org/cloud.google.com/go"" rel=""nofollow noreferrer"">https://godoc.org/cloud.google.com/go</a> packages heavily, but now I've stumbled in writing unit tests. I want to opensource the code for others to use, but want to contribute something that follows basic guidelines, i.e. has test coverage.</p>

<p>I've read a lot about mocking, using interfaces, and that google library is notorious for being a pain to use in tests, and that Google people look down on mocking. But still can't make first step to writing tests, piece of code for example:</p>

<pre><code>type StorageClient struct {
    client       *storage.Client
    targetBucket string
    Logger       *log.Logger
    context      context.Context
}
...
// Accepts name of object to be published, makes it world readable and returns its public URL as a string
func (c *StorageClient) PublishDumpFile(name string) (string, error) {
    obj := c.client.Bucket(c.targetBucket).Object(name)
    err := obj.ACL().Set(c.context, storage.AllUsers, storage.RoleReader)
    if err != nil {
        return """", err
    }
    return fmt.Sprintf(""http://storage.googleapis.com/%s/%s"", c.targetBucket, name), nil
}
</code></pre>

<p>Notice the cascading calls like Bucket().Object() and such, each returns new struct, so to mock it I'd need to define for each one a corresponding interface and create logic inside my test that will somewhat resemble logic behind google package (Bucket() returns struct which belongs to interface which has Object() method which returns... etc). But at this point I'm thinking I'm approaching it from wrong perspective.</p>

<p>I'm new to this ecosystem and testing such high-level things, so any help appreciated.</p>
",https://stackoverflow.com/questions/51661847/unit-testing-code-with-google-cloud-api-dependencies,"['unit-testing', 'go', 'google-cloud-storage']",734,FALSE,1,1
Unit Testing Flink Streams with Multiple Event Streams,"<p>I have 2 <code>DataStream</code>s that I connect and feed into a <code>CoFlatMap</code> function. I need to be able to test generating messages on two different <code>DataStream</code>s, but coordinating when the messages arrive. How does one go about doing that in Flink?</p>
",https://stackoverflow.com/questions/50454231/unit-testing-flink-streams-with-multiple-event-streams,"['apache-flink', 'flink-streaming']",594,FALSE,1,2
Interfaces / Virtual for Domain Models for Unit Testing,"<p>I am working on a .Net Core Web Application which is being Unit Tested with NUnit and Moq. Example below is very simplified for question purposes.</p>

<p>I have a ""purchaseOrderService"" class that fetches a purchase order from the Repository and calls </p>

<pre><code>purchaseOrder.Cancel();
</code></pre>

<p>before saving to the repository. The PurchaseOrder and StockItem classes are below,</p>

<pre><code>public class PurchaseOrder
{
    public int Id { get; set; }

    public List&lt;StockItem&gt; StockItems { get; set; }

    public PurchaseOrderStatus Status { get; private set; }

    public void Cancel()
    {
        Status = PurchaseOrderStatus.Cancelled;
        foreach(var stockItem in StockItems)
            stockItem.Cancel();
    }
}

public class StockItem
{
    public int Id { get; set; }

    public StockItemStatus Status { get; private set; }

    public void Cancel()
    {
        Status = StockItemStatus.Cancelled;
    }
}
</code></pre>

<p>In the unit test for my purchaseOrder.Cancel method, i wanted to Mock the stockItem, so I could verify that the cancel cancel method was called once for every stockItem inside the purchase order.</p>

<p>I would typically achieve this with something like.</p>

<pre><code>Mock&lt;StockItem&gt; mockSI = new Mock&lt;StockItem&gt;();
mockSI.Setup(x =&gt; x.Cancel());
mockSI.Setup( x=&gt; x.Cancel(), Times.Once);
</code></pre>

<p>However, the domain model isn't exposed as an interface and the Cancel method is not virtual so the Cancel method cannot be overridden for the purposes of a Mock.</p>

<p>This leaves me with 3 options</p>

<ol>
<li><p>Make the cancel method Virtual - This seems like a terrible idea and exposes it to being overridden at unwanted times.</p></li>
<li><p>Make an interface for the domain model needing to be mocked - This seems excessive as i would be making the interface for testing only without plan to have any other class inherit the interface and on classes I have full control over. Multiple posts on StackOverflow say that interfaces for Domain Models without good reason is bad practice.</p></li>
</ol>

<p>for example,
<a href=""https://stackoverflow.com/questions/29253606/interfaces-for-rich-domain-models"">Interfaces for Rich Domain Models</a></p>

<ol start=""3"">
<li>Treat this as more of an integration test and test the 2 classes working together</li>
</ol>

<p>At the moment I'm leaning towards making the StockItem class implement an interface. What would you recommend?</p>
",https://stackoverflow.com/questions/53054417/interfaces-virtual-for-domain-models-for-unit-testing,"['c#', 'unit-testing', 'interface', 'moq']",73,TRUE,1,1
Angular: Unit testing lazy-loaded modules with routing,"<p>I'm facing some issues testing lazy-loaded modules in Angular. This is my <code>.spec</code> file:</p>

<pre><code>  import { Location } from '@angular/common';
    import { TestBed, ComponentFixture } from '@angular/core/testing';
    import { RouterTestingModule } from '@angular/router/testing';
    import { Router } from '@angular/router';
    import { routes } from './app-routing.module';
    import { AppComponent } from './app.component';
    import { AppConfigService } from './services/appConfig.service';
    import { TranslateModule } from '@ngx-translate/core';
    import { NgModuleFactoryLoader } from '@angular/core';
    import { VehicleModule} from './views/vehicle/vehicle.module';
    import { DriverModule} from './views/driver/driver.module';
    import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

    describe('Router: App', () =&gt; {

      let location: Location;
      let router: Router;
      let fixture: ComponentFixture&lt;AppComponent&gt;;
      let loader: any;

      beforeEach(() =&gt; {
        TestBed.configureTestingModule({
          imports: [
            BrowserAnimationsModule,
            TranslateModule.forRoot(),
            RouterTestingModule.withRoutes(routes),
          ],
          declarations: [AppComponent],
          providers: [AppConfigService]
        });

        router = TestBed.get(Router);
        location = TestBed.get(Location);

        loader = TestBed.get(NgModuleFactoryLoader);
        loader.stubbedModules = {
          'VehicleModule': VehicleModule,
          'DriverModule': DriverModule
        };

        fixture = TestBed.createComponent(AppComponent);

        router.resetConfig([
          {
            path: 'vehicle',
            loadChildren: 'VehicleModule'
          },
          {
            path: 'driver',
            loadChildren: 'DriverModule'
          },
          {
            path: '',
            loadChildren: 'VehicleModule'
          }
        ]);

        fixture = TestBed.createComponent(AppComponent);
        router.initialNavigation();
      });

      it('should create APP', () =&gt; {
        expect(fixture.componentInstance).toBeDefined();
      });

      it('lazily navigates to ""/driver""',(() =&gt; {
        router.navigate(['/driver']);
        expect(location.path()).toBe('/driver');
      }));
    });
</code></pre>

<p>This is what i got from running the test:  </p>

<pre><code> Expected '' to be '/driver'.
</code></pre>

<p>The routes work fine on the app, the problem is showing up only during the unit testing session.</p>

<p>What am i missing?</p>

<p>I'm using karma 1.7.1, Angular 6, jasmine 2.99.1</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/51635273/angular-unit-testing-lazy-loaded-modules-with-routing,"['angular', 'unit-testing', 'angular2-routing', 'karma-jasmine']",3424,FALSE,1,1
How to wrap correctly the unit testing diff?,"<p>I am running python <code>3.6.4</code>, but some times the unit testing diff does not work as expected. For example, on the following there is a forced unit test error versus expected where the line wrapping behavior is not desired.</p>

<pre><code>import unittest

class TestSemanticRules(unittest.TestCase):
    maxDiff = None

    def test_badWrapping(self):
        self.assertEqual(
            ""1. Duplicated target language name defined in your grammar on: [@-1,63:87='Abstract Machine Language'&lt;__ANON_3&gt;,3:19]\n""
            ""2. Duplicated master scope name defined in your grammar on: [@-1,138:147='source.sma'&lt;__ANON_3&gt;,5:20]""
            ,
            ""1. Duplicated target language name defined in your grammar on: free_input_string\n""
            ""  text_chunk_end  Abstract Machine Language""
            ""\n""
            ""2. Duplicated master scope name defined in your grammar on: free_input_string\n""
            ""  text_chunk_end  source.sma""
        )

unittest.main(failfast=True)
</code></pre>

<p>Running it with <code>python3 test.py</code> you see the first error diff line does not got wrapped:</p>

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

<p>An expected result would be:</p>

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

<p>I tried searching for an alternative diff library, then I tried replacing the <code>unittest</code> diff by a custom diff library as the built-in <code>difflib</code>, but the diff results where the same. So, I assume the <code>unittest</code> package is using the <code>difflib</code>.</p>

<pre><code>import unittest
import difflib

class TestSemanticRules(unittest.TestCase):
    maxDiff = None

    def myAssertEquals(self, expected, actual):
        expected = expected.splitlines( 1 )
        actual = actual.splitlines( 1 )

        if expected != actual:
            diff = difflib.context_diff( expected, actual, fromfile='expected input', tofile='actual output', lineterm='\n' )
            self.fail( '\n' + ''.join( diff ) )

    def test_badWrapping(self):
        self.myAssertEquals(
            ""1. Duplicated target language name defined in your grammar on: [@-1,63:87='Abstract Machine Language'&lt;__ANON_3&gt;,3:19]\n""
            ""2. Duplicated master scope name defined in your grammar on: [@-1,138:147='source.sma'&lt;__ANON_3&gt;,5:20]""
            ,
            ""1. Duplicated target language name defined in your grammar on: free_input_string\n""
            ""  text_chunk_end  Abstract Machine Language""
            ""\n""
            ""2. Duplicated master scope name defined in your grammar on: free_input_string\n""
            ""  text_chunk_end  source.sma""
        )
</code></pre>

<p>Can the <code>difflib</code> built-in library used by the <code>unittest</code> package to be configured, so, this behavior does not happen? Or there is an reliable alternative for the <code>difflib</code> package?</p>
",https://stackoverflow.com/questions/52682351/how-to-wrap-correctly-the-unit-testing-diff,"['python', 'unit-testing', 'diff', 'python-unittest', 'difference']",1178,TRUE,1,2
Unit Testing Model property binding in Angular 5,"<p>I am using Angular 5 with Jasmine to perform Unit Testing.</p>

<p>I have a model called PlayerAccount array that looks like the following:</p>

<pre><code>export interface IPlayerAccount {
  playerId: number;
  name: string;
  phone: number;
  street: string;
  postcode: string;
  state: string;
  country: string;
}
</code></pre>

<p>This PlayerAccount array gets populated on ngOnInit by calling method</p>

<pre><code>getPlayerAccounts(playerId: number);
</code></pre>

<p>I'm trying to unit test that the returned PlayerAccount data successfully binds to the PlayerAccount array.</p>

<p>I have got this far but I feel like my approach is a little hacky, so I’m wondering if there is a nicer way to bind the returned data from getPlayerAccounts to my array of IPlayerAccount </p>

<pre><code> it('check that array of players successfully bind to component accounts players array', async () =&gt; {
          fixture.detectChanges();

          IPlayerAccount accounts = new IPlayerAccount();

          var account1 = new IPlayerAccount();
          account1.playerId = 1;
          account1.name = 'Ben';
          account1.phone = 12345;
          account1.street = 'Cloud Street';
          account1.postcode = 111;
          account1.state = 'MELB'
          account1.country = 'AU';

          var account2 = new IPlayerAccount();
          account2.playerId = 2;
          account2.name = 'James';
          account2.phone = 6789;
          account2.street = 'Jamming Street';
          account2.postcode = 2323;
          account2.state = 'VIC'
          account2.country = 'AU';

          component.accounts.push(account1);
          component.accounts.push(account2);

          IPlayerAccount[] returnedAccounts = component.getMerchantAccounts(1);

          expect(component.accounts[0]).toEqual(returnedAccounts[0]);
          expect(component.accounts[1]).toEqual(returnedAccounts[1]);

        });
</code></pre>

<p>Can someone please help me write this unit test? Any help would be greatly appreciated!</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/50285408/unit-testing-model-property-binding-in-angular-5,"['angular', 'unit-testing', 'jasmine']",477,FALSE,1,0
Controller is not registered -angular js unit testing,"<p>Hi i am new to unit testing in angular. I am trying to add a simple test, but i keep getting an error saying that my angular controller is not registered. Below is my test case. I am not sure where i am going wrong?</p>

<pre><code>'use strict'; 

/**
 * 
 */
describe('Controller',function() {   
    beforeEach(module('Module')); 
    var $controller;  
    beforeEach(inject(function(_$controller_) {
        $controller = _$controller_;   
    }));

    it(""Should initialize AllValues to an empty array"",function() {
        var $scope = {

        };

        var testController= $controller(
            'TestController', {
                $scope : $scope
        });

        expect(testController.AllValues).toEqual(new Array());
    })
});
</code></pre>

<p>below is my file structure in  karma.conf.js</p>

<pre><code>files: [
    'node_modules/angular/angular.js',
    'node_modules/angular-mocks/angular-mocks.js',
    'App/**/*Test.js',
    'App/**/*Module.js',
    //'App/**/**.js',
]
</code></pre>
",https://stackoverflow.com/questions/52952107/controller-is-not-registered-angular-js-unit-testing,"['angularjs', 'jasmine', 'karma-jasmine']",594,FALSE,1,1
Unit Testing Component in AngularJS 1.5 and Typescript,"<p>Working on converting some old broken AngularJS unit tests to TypeScript and came across this error:</p>

<pre><code>Error: [$injector:unpr] Unknown provider: myComponentDirectiveProvider &lt;- myComponentDirective
</code></pre>

<p>In every example of AngularJS unit testing I've seen, they have a main module with everything on it, and they inject that main module into the unit test with <code>angular.mock.module('theWholeStinkingApp')</code>.  That is nice for a little tutorial, but I'm dealing with a very large application with hundreds of components and dozens of services.  Not to mention filters and other directives.  It doesn't work to just inject the whole app into a unit test.  Nor do I think it's a good idea to start up the whole app just to unit test a component (kind of defeats the purpose of unit testing when you have to include everything you own in every test).</p>

<p>For testing services I can just create my module in the test in a <code>beforeEach</code> like this, so I'm mocking dependencies, but injecting the real service I want to test:</p>

<pre><code>angular.mock.module(($provide) =&gt; {
  $provide.service('firstDependency', FirstDependencyMock);
  $provide.service('secondDependency', SecondDependencyMock);
  $provide.service('serviceIWantToTest', ServiceIWantToTest);
});
</code></pre>

<p>I can't figure out how to do this and inject a Component.  Any help would be appreciated.  </p>

<p><strong>Please keep in mind, I do not want to have to <code>angular.mock.module('theWholeApp')</code> to get this working.  I just want to create a mock module and attach my component to it.</strong></p>

<p>Here's a slimmed down version of what I'm doing.</p>

<p>Component looks something like this</p>

<pre><code>angular.module('theWholeApp', [])
  .component('myComponent', {
    controller: MyComponentController, // class is defined elsewhere
    templateUrl: 'path/to/my/template.html'
  )
  ... // 100+ other components;
</code></pre>

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

<pre><code>describe('MyComponent', () =&gt; {
  beforeEach(() =&gt; {
    // angular.mock.module('theWholeApp'); This is not an option.

    // Creating a mock module with just the dependencies I need for this test
    angular.mock.module(($provide) =&gt; {
        $provide.service('firstDependency', FirstDependencyMock);
        $provide.service('secondDependency', SecondDependencyMock);
    });

    // Tried adding this to register the controller, but it doesn't help.  
    angular.mock.module(($controllerProvider) =&gt; {
        $controllerProvider.register('MyComponentController', MyComponentController);
    });

    angular.mock.inject(($injector) =&gt; {
      $rootScope = $injector.get('$rootScope');
      $componentController = $injector.get('$componentController');
      firstDependency= $injector.get('firstDependency');
      secondDependency= $injector.get('secondDependency');

      $scope = $rootScope.$new();
    });
  });

  describe('doSomething', () =&gt; {
    it('exists', () =&gt; {
      controller = $componentController('myComponent', {$scope});
        expect(controller.doSomething).toBeDefined();
      });
  });
});
</code></pre>

<p>Obviously, this isn't the live code, just a representation.  Hopefully I got all the made up names right.  The point is, I want to create a mock module and add my component to it so a call to <code>$componentController('myComponent', {$scope})</code> works.</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/48890079/unit-testing-component-in-angularjs-1-5-and-typescript,"['angularjs', 'unit-testing', 'typescript', 'jasmine', 'karma-runner']",1354,TRUE,0,1
Why is my unit testing is not working?,"<p>I'm using vs17, Whenever I run any of the tests I get this</p>

<blockquote>
  <p>[4/5/2018 12:10:19 PM Informational] ------ Run test started ------
  [4/5/2018 12:10:19 PM Warning] [MSTest][Discovery][C:*path*\bin\Debug\FeatureFlags.API.Tests.dll] The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)
  [4/5/2018 12:10:19 PM Warning] No test is available in C:*path*\bin\Debug\FeatureFlags.API.Tests.dll. Make sure that test discoverer &amp; executors are registered and platform &amp; framework version settings are appropriate and try again.
  [4/5/2018 12:10:19 PM Informational] ========== Run test finished: 0 run (0:00:00.7650001) ==========</p>
</blockquote>

<p>I feel the need to ensure that I have searched for this problem in tons of other questions and other sites and non of the solutions solve my problem, and most of them is either very old questions or for vs15 before update 2 where it solves the problem or prior to framework 4.6 and I'm currently using framework 4.7. and I can't downgrade my framework version.</p>

<p>I've added a .runsettings file, used debugging "" it never hits the break points or even start to run anything"", I have changed the default processor architecture, and I've disabled ""Enable just my code"", none of that worked for me. I rebuilt the solution a lot of times and even did closed the visual studio and restarted my pc.</p>

<p>In the debugging mode, I can see in the output windows </p>

<blockquote>
  <p>""Cannot find or open the PDB file""</p>
</blockquote>

<p>a lot of times for different files.</p>

<p>What is my mistake and how to solve this?</p>

<p><strong>EDIT 1</strong>
here is an example of my test cases</p>

<pre><code>[TestClass]
public class VezeetaFeatureFlagsTests
{
    private readonly FeatureFlagController _controller;

    public VezeetaFeatureFlagsTests()
    {
        MockHttpContext();
        _controller = new FeatureFlagController(new FeatureFlagCore(new FeatureFlagDAL(new RedisClient(""FeatureFlags.RedisConnectionString""))));
    }

    private void MockHttpContext()
    {
        HttpContext.Current = new HttpContext(
            new HttpRequest("""", ""http://localhost:2812/"", """"),
            new HttpResponse(new StringWriter())
        );

        Path.Combine(@""*Path*"", """");

    }

[TestMethod]
    public void Valid_AddKey()
    {
        List&lt;AddTagsAndFeaturesModel&gt; addTagsAndFeaturesModels = new List&lt;AddTagsAndFeaturesModel&gt;
        {
            new AddTagsAndFeaturesModel()
            {
                Key = ""test"",
                Values = new List&lt;object&gt;()
            {
                ""Feature 1"",
                ""Feature 2""
            },
                IsHide = false,
                IsTags = false
            }
        };

        var result = _controller.AddFeaturesOrTags(addTagsAndFeaturesModels);

        Assert.AreEqual(result.StatusCode, HttpStatusCode.OK);

    }
</code></pre>

<p>}
and I can see it in the test explorer.</p>
",https://stackoverflow.com/questions/49672228/why-is-my-unit-testing-is-not-working,"['c#', 'visual-studio', 'unit-testing']",544,FALSE,0,0
Unit-testing ABC with helper functions in Python,"<p>I'm wondering if it is possible to change helper functions in a testing environment in Python. My app is structured as follows:</p>

<pre><code>app/
  trader/
    __init__.py
    strategies/
      __init__.py
      base_strategy.py
      util.py
      models/
        __init__.py
        base_model.py
  tests/
    __init__.py
    strategies/
      __init__.py
      stub_strategy.py
      test_strategies.py
      models/
        __init__.py
        stub_model.py
</code></pre>

<p>where each <code>base_*.py</code> is an abstract base class, which are inherited from in each <code>stub_*.py</code> file in the tests directory. In my <code>util.py</code> file, there is a helper function which looks through the <code>trader/strategies/models</code> directory and registers all models that are available:</p>

<pre><code>import inspect
from . import alpha_models

existing_alpha_models = []
alpha_model_dict = {}
for name, obj in inspect.getmembers(alpha_models):
    if inspect.isclass(obj):
        existing_alpha_models.append(name)
        alpha_model_dict[name] = obj
</code></pre>

<p>Now to my problem: In my <code>BaseTradingStrategy</code>-class I have a method, which uses the <code>existing_alpha_models</code> list, to check if the model exists.</p>

<pre><code>from abc import ABC, abstractmethod
from .util import existing_alpha_models

class BaseTradingStrategy(ABC):
    """"""BaseTrading Code comes here""""""
    @abstractmethod
    def some_abs_method(self):
        raise NotImplementedError

    def register_model(self, model_name):
        if model_name not in existing_alpha_models:
            raise ValueError
</code></pre>

<p>For unit testing, I have created stub classes, which are not in the <code>trader/strategies/models</code> directory, and are, therefore, not registered in the <code>existing_alpha_models</code> list. When I want to test the functionality of the ABC with pytest, many tests fail since the method that checks the availability of the models fails. A simple solution would be to put the stub classes in the <code>trader</code> directory of my app, but I'd rather have my test code separated from the rest of the app. I probably could also make <code>existing_alpha_models</code> a property of the base class, but I don't really see the point in doing so, except making the tests pass. Is there a way to inject the stub classes in the <code>existing_alpha_models</code> for unit testing so that the test of the ABC does not fail without changing the base class too much?</p>

<p>--------------EDIT-------------------</p>

<p>I now have 2 working versions of my test code. One is using the verison of @hoefling, where I simply add the <code>alpha_models</code> to the <code>existing_alpha_models</code> list:</p>

<pre><code>from tests.strategies import StubTradingStrategy
from tests.strategies.alpha_models import StubModel, StubModel2, StubModel3
from trader.strategies.util import existing_alpha_models
existing_alpha_models.extend([""StubModel"", ""StubModel2"", ""StubModel3""])
</code></pre>

<p>and one version where I add the models to the <code>alpha_models</code> module and reload 2 modules:</p>

<pre><code>import importlib
from trader.strategies import alpha_models
from tests.strategies.alpha_models import StubModel, StubModel2, StubModel3

setattr(alpha_models, ""StubModel"", StubModel)
setattr(alpha_models, ""StubModel2"", StubModel2)
setattr(alpha_models, ""StubModel3"", StubModel3)

from nutrader.strategies import util
import nutrader.strategies.base_strategy
importlib.reload(util)
importlib.reload(nutrader.strategies.base_strategy)
from tests.strategies import StubTradingStrategy
</code></pre>

<p>The advantage of the second version is that it allows me to actually test the <code>util</code> code, but it also introduces potential risks in my test code since there exist 2 version of certain modules, which is not the case in the production environment. Is this a good idea, or should I leave it at the first version for my test environment?</p>
",https://stackoverflow.com/questions/50172358/unit-testing-abc-with-helper-functions-in-python,"['python', 'unit-testing', 'pytest', 'helper']",539,FALSE,0,0
Unit testing delete and update images with django,"<p>I have an inlineformset using my imagemodel. It has a foreignkey to my lodging model defined like this:</p>

<pre><code>ImageFormset = inlineformset_factory(Lodging,ImageModel,fields=('image',),
can_delete=True,form=ImageForm,extra=0)
</code></pre>

<p>I can get lodging_id from url and can use it to create an instance of lodging. I, then, pass it to my ImageFormset instance</p>

<pre><code>lodging=Lodging.objects.get(id=ad_id)
formset = ImageFormset(instance=lodging)
</code></pre>

<p>In this way, I will get some initial-forms. My question is what should I pass as data in unit testing.
What I have tried so far is:</p>

<pre><code>data = {
        'imagemodel_set-TOTAL_FORMS': 2,
        'imagemodel_set-INITIAL_FORMS': 2,
        'imagemodel_set-0-image': SimpleUploadedFile('test_image1.jpg',
                get_binary_data(self.image3_location),
                content_type='image/jpeg'),
        'imagemodel_set-1-image': SimpleUploadedFile('test_image2.jpg',
                get_binary_data(self.image4_location),
                content_type='image/jpeg'),
    }
</code></pre>

<p>But this is giving me error: ""['ManagementForm data is missing or has been tampered with']""
Any help would be appreciated.</p>

<p>edit:</p>

<p>test code</p>

<pre><code>def test_lodging_edit_view_success(self):
    create_lodging(self)
    response = self.client.get(reverse('lodging:edit',args=[1]))
    data = {
        'imagemodel_set-TOTAL_FORMS': 2,
        'imagemodel_set-INITIAL_FORMS': 2,
        'imagemodel_set-0-image': SimpleUploadedFile('test_image1.jpg',
                get_binary_data(self.image3_location),
                content_type='image/jpeg'),
        'imagemodel_set-1-image': SimpleUploadedFile('test_image2.jpg',
                get_binary_data(self.image4_location),
                content_type='image/jpeg'),
        'rent': '4100',
        'update': 'any value'
    }
    response = self.client.post(reverse('lodging:edit',args=[1]),data)
</code></pre>

<p>form code</p>

<pre><code>@login_required
def lodging_edit_view(request,ad_id):
    try:
        lodging=Lodging.objects.get(id=ad_id)
        if lodging.posted_by!=request.user:
            raise ViewException('Unauthorized access.')
        sublodging = lodging.sublodging
        images = lodging.imagemodel_set.all()
    except Lodging.DoesNotExist:
        return HttpResponseRedirect(reverse('dashboard:home'))
    sublodging_form = CommonlyUsedLodgingUpdateForm(instance=sublodging)
    uneditable_form = UneditableForm(initial={
         'address': lodging.address,
         'posted_at': lodging.posted_at,
         'updated_at': lodging.updated_at,
         'no_times_booked': lodging.no_times_booked,
         'location': sublodging.location,
         'type': sublodging.lodging_type,
         'title': sublodging.title
    })
    formset = ImageFormset(instance=lodging)
    if request.method=='POST':
        if request.session.test_cookie_worked():
            if 'delete' in request.POST:
                with transaction.atomic():
                    for image in images:
                        image.delete()
                    lodging.delete()
            elif 'update' in request.POST:
                sublodging_form = CommonlyUsedLodgingUpdateForm(request.POST,instance=sublodging)
                formset = ImageFormset(request.FILES,request.POST,instance=lodging)
                if sublodging_form.is_valid() and formset.is_valid():
                    with transaction.atomic():
                        sublodging_form.save()
                        formset.save()
        else:
            uneditable_form.add_error(None,'Cookies are not enabled.')
    else:
        request.session.set_test_cookie()
    return render(request,'lodging/edit_lodging.html',{
        'uneditable_form':uneditable_form ,
        'sublodging_form': sublodging_form,
        'formset': formset
    })
</code></pre>
",https://stackoverflow.com/questions/49812813/unit-testing-delete-and-update-images-with-django,"['django', 'django-forms']",79,FALSE,0,0
Unit Testing React-Redux Connected Components in Enzyme,"<p>I have a connected component with Form and button. While unit testing the component using mount , i get the error  ""Actions must be plain objects."" </p>

<p>This is happening due to the redux calls being made in the handleSubmit method, is there a way to mock the calls from happening.</p>

<pre><code> import React from ""react"";
    import {Provider} from ""react-redux"";
    import configureStore from ""redux-mock-store"";  
    import {Props, InitialState} from ""../mock_data/mock.data.jsx"";
    const mockStore = configureStore();
    let store = mockStore(InitialState);
    const params = {
    url: ""http://localhost:9879""
    };
    let props = {};
  beforeEach(() =&gt; {
    // reset props before each test
    props = JSON.parse(JSON.stringify(Props));
    props.actions = {};
   props.email = Props.email;
    props.params = params;
  });
    handleSubmit({ values }) {
        const {url} = this.props;
        const val = values.valcode;
        this.props.actions.getCode(url);
        this.props.makeExternalCall(val);
      }


      return (
              &lt;Form
                initialValues={{ ...personalUser }}
                onSubmit={this.handleSubmit}&gt;
                {
                  ({ form, errors }) =&gt; {
                    const isDisabled = errors !== null || this.state.disableReset;

                    return (
                      &lt;div&gt;
                        &lt;button name=""btnConfirm"" type=""submit""
                          className={styles.btnConfirm} disabled={isDisabled}&gt;/&gt;
                        &lt;/button&gt;
                      &lt;/div&gt;
                    );
                  }
                }
              &lt;/Form&gt;
            );

    const mapDispatchToProps = (dispatch) =&gt; ({
      actions: bindActionCreators(actions, dispatch),
      makeExternalCall: bindActionCreators(makeExternalCallAction, dispatch)
    });

export default connect(null, mapDispatchToProps)(injectIntl(TestComponent));
</code></pre>

<p>Test</p>

<pre><code>it("" - should display the proper label"", () =&gt; {

    props.error = ""This is an error message"";
    props.actions.getCode = sinon.stub().returns({
      then: () =&gt; {}
    });
    props.makeExternalCall = sinon.stub().returns({
      then: () =&gt; {}
    });
    store = mockStore(props);
    const wrapper = mountWithIntl(&lt;Provider store={store}&gt;
        &lt;TestComponent {...props}/&gt;
      &lt;/Provider&gt;);
    expect(wrapper).to.not.be.null;
    expect(wrapper.find(""button"").prop(""disabled"")).equals(true);
   wrapper.find(""TestComponent"").get(0).handleSubmit({values:{valcode: ""AkPdQ2"" }});
  });
</code></pre>

<p>Is it possible to mock the mapDispatchToProps ,which is giving the error </p>

<pre><code>PhantomJS 2.1.1 (Mac OS X 0.0.0) &lt;TestComponent Component /&gt;  - should display the proper label FAILED
    Actions must be plain objects. Use custom middleware for async actions.
</code></pre>
",https://stackoverflow.com/questions/49990463/unit-testing-react-redux-connected-components-in-enzyme,"['reactjs', 'ecmascript-6', 'redux', 'mocha.js', 'enzyme']",437,FALSE,0,0
Unit Testing a Service without a return type,"<p>I am trying to follow a <code>TTD</code> approach to building a new <code>Email Service</code>. The service will have a number of methods that form a ""pipeline"" of sorts, in that they receive an <code>object</code>, perform some actions on the <code>object</code> then pass it over to the next service. </p>

<p>Is there a way to unit test these methods individually? </p>

<p>Example of one method:</p>

<pre><code>public void RecieveMessage(string message)
{
    var @event = JsonAdapter.ToObject&lt;RecievedEvent&gt;(message);

    if(@event.IsValid())
    {
        CreateTemplates(@event);
    }
    else
    {
        Log(""Warn"", ""Invalid message received"");
    }
}
</code></pre>

<p>Can this be tested? Do I need to rethink my approach? Should I tests the methods together?</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/53298029/unit-testing-a-service-without-a-return-type,"['c#', 'unit-testing']",148,TRUE,0,1
angular 6 unit testing on http service errors,"<p>I get errors while I m trying to test one of my services.</p>

<p>The service has a method that makes a POST request on the server and then returns a data, yes I know why POST and not GET.</p>

<p>I need to say that I can't use the authentication service because using my login and then I get the tokens from the server. 
Since I can't log in to get the token all the requests are not valid.</p>

<p>How to unit test HTTP calls without making requests on the server, just using local data that simulates the server response.</p>

<p>my service is this.</p>

<h3>inventory.service.ts</h3>

<pre><code>  /**
   * GETS THE INVENTORY DATA.
   * @returns Observable of inventory data from the server.
   */
  getInventoryData&lt;T&gt;() {

    const options = { headers: this.getHeaders() };
    const body: AdditionFiltersEntity = this.shared.getAdditionFilters({});
    const url = `${this.shared.baseUrl}/inventory`;

    return this.http.post(url, body, options).pipe(
      tap(val =&gt; console.log(`BEFORE MAP: ${val}`)),
      map(res =&gt; res.json()),
      catchError(e =&gt; this.shared.handleError(e))
    );

  }
</code></pre>

<p>The problem is because I have the <code>catchError(e =&gt; this.shared.handleError(e))</code>
this checks if the response has errors in my case I have ""UNAUTHORIZED"" statusText</p>

<p>In my case, I have all the time this type of error on all HTTP tests.</p>

<blockquote>
  <p>status: 401, ok: false, statusText: ""UNAUTHORIZED""
  but this is ok since I m unit testing I can't pass the authorization part.</p>
</blockquote>

<p>My unit test file is this.</p>

<h3>inventory.service.spec.ts</h3>

<pre><code>import { TestBed, async, inject } from '@angular/core/testing';

// Modules
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HttpModule } from '@angular/http';
import { MatSnackBarModule } from '@angular/material';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { HttpClientModule } from '@angular/common/http';
import { RouterTestingModule } from '@angular/router/testing';

// Services
import { InventoryService } from './inventory.service';
import { HelpersService } from '@app-services/helpers/helpers.service';
import { MediatorService } from '@app-services/mediator/mediator.service';
import { AuthService } from '@app-services/auth/auth.service';
import { StorageService } from '@app-services/storage/storage.service';

// Models
import { InventoryEntity } from '@app-models/inventory';



describe('InventoryService', () =&gt; {

  // let service: InventoryService;
  let httpMock: HttpTestingController;
  let auth: AuthService;
  // let user: User;

  beforeEach(() =&gt; {

    TestBed.configureTestingModule({
      imports: [ HttpModule, MatSnackBarModule, RouterTestingModule, HttpClientModule,
      HttpClientTestingModule, BrowserAnimationsModule
    ],
      providers: [
        InventoryService, AuthService, HelpersService, MediatorService, StorageService
      ]
    });


    httpMock  = TestBed.get(HttpTestingController);
    auth      = TestBed.get(AuthService);
    localStorage.setItem('store_ids', JSON.stringify([1])); // just set a test id so we gonna get some kind data.

  });


  beforeEach(async(() =&gt; {
    TestBed.compileComponents().catch(error =&gt; console.error(error));
  }));

  it('should be created', inject([InventoryService], (service: InventoryService) =&gt; {
    expect(service).toBeTruthy();
  }));

  // This is where I get the errors
  fit('Should get inventory data', inject([InventoryService], async (service: InventoryService) =&gt; {

    await service.getInventoryData().subscribe( (res: InventoryEntity[]) =&gt; {

      // get array first element keys.
      const evaluationKeys = ['brand', 'color_code', 'color_tag', 'family', 'frame_size', 'gender', 'provider', 'quantity', 'tag'];
      const keys = Object.keys(res[0]);

      expect(keys).toEqual(evaluationKeys);

    });

  }));


});
</code></pre>

<ul>
<li><p>Can someone explain to me how to make unit tests on HTTP calls like this one
<code>service.getInventoryData().subscribe</code></p></li>
<li><p>And how to deal with the authentication part. 
the authentication is where all my tests fail.</p></li>
<li><p>if I need to use mock data, how to make this, can someone show me an example?</p></li>
</ul>

<h3>The response should give me this data.</h3>

<pre><code>[
  {
    'brand': 'brand-1',
    'color_code': '593',
    'color_tag': 'SILVER',
    'family': 'SOL',
    'frame_size': '54x16x140',
    'gender': 'Unisexe',
    'provider': 'hgg',
    'quantity': 82,
    'tag': '44554'
  }, {
    'brand': 'brand-2',
    'color_code': 'MAU1O1',
    'color_tag': 'BLACK',
    'family': 'SOL',
    'frame_size': '54x17x140',
    'gender': 'Unisexe',
    'provider': 'hgg',
    'quantity': 98,
    'tag': '45445'
  }
]
</code></pre>
",https://stackoverflow.com/questions/52890604/angular-6-unit-testing-on-http-service-errors,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",3136,TRUE,0,1
Unit testing method with method reference as parameter,"<p>I have a method that takes as parameter an object and a method reference to that object to collect the integers in a collection from that object. The code works fine but I am unable to unit test with mockito on the when() method.</p>

<pre><code>public class UserCredentials {

  private Integer accountId;

  private Integer customerNameId;
}

public class UserCredentialsUtil {

  public List&lt;Integer&gt; userCredentialsGetter(
      final List&lt;UserCredentials&gt; userCredentials,
      final Function&lt;UserCredentials, Integer&gt; func) {
    return userCredentials.stream().map(func).collect(Collectors.toList());
  }
}
</code></pre>

<p>My unit test basically returns to me an empty List.</p>

<pre><code>  @Mock
  private UserCredentialsUtil userCredentialsUtil;

final List&lt;Integer&gt; accountIds = Arrays.asList(1, 2, 3);

        when(
        this.userCredentialsUtil.userCredentialsGetter(
            userCredentials,
         UserCredentials::getAccountId)).thenReturn(accountIds);
</code></pre>

<p>I know this isn't a problem with my setup because if I change the UserCredentialsGetter to</p>

<pre><code>  public List&lt;Integer&gt; userCredentialsGetter(
      final List&lt;UserCredentials&gt; userCredentials) {
    return userCredentials.stream().map(UserCredentials::getAccountId).collect(Collectors.toList());
  }
</code></pre>

<p>And the test method to.</p>

<pre><code>        when(
        this.userCredentialsUtil.userCredentialsGetter(
            userCredentials)).thenReturn(accountIds);
</code></pre>

<p>This works fine. I am guessing I need to pass something else then the method reference as parameter for my first test, but I have been unfortunate in finding someone else going into this case even though it seems pretty common.</p>
",https://stackoverflow.com/questions/53196851/unit-testing-method-with-method-reference-as-parameter,"['java', 'unit-testing', 'mockito']",2881,TRUE,0,1
Unit Testing Using embedded Cassandra in Spring Boot,"<p>I am trying to test a Spring Boot Application which includes saving into cassandra DB.
For unit testing I used EmbeddedCassandra.</p>

<p>These are the dependencies.</p>

<pre><code>compile group: ""com.datastax.cassandra"", name: ""cassandra-driver-core"", version:""2.1.7""
    compile group: ""com.datastax.cassandra"", name: ""cassandra-driver-dse"", version:""2.1.7""
    testCompile('org.springframework.boot:spring-boot-starter-test')
    testCompile  (""org.cassandraunit:cassandra-unit-spring:2.1.9.2""){
        exclude group:""org.cassandraunit"",module:""cassandra-unit""
    }
</code></pre>

<p>These are annotations I have used</p>

<pre><code>@RunWith(SpringRunner.class)
@WebMvcTest(value = MyController.class)
@Import(value = {MyDao.class})
@ContextConfiguration
@TestExecutionListeners(listeners = {
        CassandraUnitDependencyInjectionTestExecutionListener.class,
        CassandraUnitTestExecutionListener.class,
        ServletTestExecutionListener.class,
        DependencyInjectionTestExecutionListener.class,
        DirtiesContextTestExecutionListener.class}
)
@EmbeddedCassandra(timeout = 60000)
@CassandraDataSet(keyspace = ""test"", value = {""test.cql""})
</code></pre>

<p>But the values saved in unit testing is populated original cassandra db .
Can anyone help me to resolve this?</p>
",https://stackoverflow.com/questions/53503146/unit-testing-using-embedded-cassandra-in-spring-boot,"['spring-boot', 'testing', 'junit', 'cassandra']",2481,FALSE,0,1
Angular 2 Unit Testing Services with HTTP requests,"<p>I am new to testing services with Angular 2 and I am trying to test a service with Http basic requests (Get and GetBYId). 
- How works my service? : I have a getAllMyProducts method which consumes a REST Api exposed in a Spring boot Backend application .this web api query the products and return products for the current user.(The http request is sent with headers ).
- What I want to do? : Now I have to test this GetAll method with Jasmine and I am not sure how to do that especially regarding the current user…</p>

<ol>
<li>My GetAllMethod in my Service:</li>
</ol>

<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>getAll(): Observable&lt;Product[]&gt; {
    return this.baseapiService.getAll('/product/userProducts');
    }</code></pre>
</div>
</div>
</p>

<ol start=""2"">
<li>my baseapiService that attachs header to the request:</li>
</ol>

<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>getAll(link){
    this.header = this.createHeader();
    return this.http.get(this.apiurl+link, this.header)
      .map(this.extractData);
  }</code></pre>
</div>
</div>
</p>

<p>Any examlpes or suggestions would be great. Thanks in advance</p>
",https://stackoverflow.com/questions/51081773/angular-2-unit-testing-services-with-http-requests,"['testing', 'jasmine', 'angular2-services']",46,FALSE,0,0
Live unit testing stuck and cannot be stopped,"<p>Using Visual Studio 2017, with one of our solutions, live unit testing frequently gets stuck. In Test Explorer, it appears to be running tests (progress bar moving from left to right, ""run"" button is disabled), however, there is no ""Cancel"" button to stop the tests, and no actual progress is being made (a couple of dozen tests passed and then no more progress). The only way I found to get the test control back is to restart visual studio and reload the solution. It will become stuck again after while - do not know how or when because it runs in the background. The problem is only noticed when I want to run some tests and the ""run test/debug test"" context menu is disabled.</p>

<p>Is there a way to disable live unit testing completely (per solution or otherwise)?</p>
",https://stackoverflow.com/questions/51105211/live-unit-testing-stuck-and-cannot-be-stopped,"['.net', 'azure', 'visual-studio-2017', 'live-unit-tests']",328,FALSE,0,1
unit testing removeAt function on AbstractControl and FormBuilder,"<p>I have a function that takes in an AbstractControl FormArray and an index and removes an entry from the FormArray, however I cannot seem to test the function correctly?</p>

<p><strong>This is the function that currently works when using my app</strong></p>

<pre><code>remove(data: AbstractControl, index: number) {
   data['controls'].myArray.removeAt(index);
}
</code></pre>

<p><strong>Here is my test</strong></p>

<pre><code>it('Should delete item from array', () =&gt; {
    const fb = new FormBuilder();
    const something= fb.group(exampleData);

    component.remove(something, 0);
 expect(component.myFormGroup.controls['myArray'].value.myArray.size).toEqual(0);
  });
</code></pre>

<p>I am getting an error message of:</p>

<blockquote>
  <p>'removeAt' is not a function associated with AbstractControl type...</p>
</blockquote>
",https://stackoverflow.com/questions/53851097/unit-testing-removeat-function-on-abstractcontrol-and-formbuilder,"['angular', 'typescript', 'unit-testing']",265,FALSE,0,0
Jasmine Unit Testing: Error: Cannot find module &#39;parser.js&#39;,"<p>I am new to unit testing and I just installed jasmine and wrote this test program.</p>

<pre><code>   var grabNums = require('parser')

describe(""parsenpmr test"", function(){
    it("" .3grabs possible phone and conference numbers"", function(){
        expect(grabNums.grabNums(""the phone number is (914)-817-3535 and the conference code is 5852753333 please call in at 6:00AM"").toBe(['(914)8173535','5852753333']))
    })
})
</code></pre>

<p><a href=""https://i.stack.imgur.com/3LiXg.png"" rel=""nofollow noreferrer"">My Directory organization looks like this at the moment</a></p>

<p>and this is the error I am getting</p>

<pre><code>&gt; outlookparser2@1.0.0 test C:\Users\kaizert\eclipse-workspaceREAL\client_S4B\src\outlookParser2
&gt; jasmine

module.js:549
    throw err;
    ^

Error: Cannot find module 'parser.js'
    at Function.Module._resolveFilename (module.js:547:15)
    at Function.Module._load (module.js:474:25)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at Object.&lt;anonymous&gt; (C:\Users\kaizert\eclipse-workspaceREAL\client_S4B\src\outlookParser2\spec\parserspec.js:1:78)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
npm ERR! Test failed.  See above for more details.
</code></pre>

<p>What do I need to change? Again I am new to unit testing so I apologize if there is an easy solution to this, I could not find anything online.</p>
",https://stackoverflow.com/questions/51193149/jasmine-unit-testing-error-cannot-find-module-parser-js,"['javascript', 'unit-testing', 'jasmine']",958,FALSE,-1,2
Angular unit-testing components with protected @Input fields,"<p>We got used to make variables <code>protected</code> which are only used in a component and its subclasses but not in the template. </p>

<p>That's especially an advantage if you have like 10 many variables in your class and with <code>protected</code> <code>private</code> and <code>public</code> it's very easy to know which variables are used in the template.</p>

<pre><code>@Input() public disablePlus: boolean = false;
@Input() public disableMinus: boolean = false;

@Input() protected jumpSize: number = 1000;
</code></pre>

<p>now I'm about to create some unit-test for this component. But i cannot activly change those values inside my <code>it</code> method:</p>

<pre><code>it('should change jumpSize to 5000', () =&gt; {
    component.jumpSize= 5000; 
    // ts2445: Property `jumpSize` is protected and only accessible within class and its subclasses
    ...
});

it('plus should be disabled', () =&gt; {
    component.disablePlus= true; // no error
    ...
});
</code></pre>

<p>Is there a way to leave jumpSize <code>protected</code> or do we have to change it to <code>public</code>?</p>

<p>Or do you event think that our approach with <code>protected @Input</code> fields is anyway stupid and not very useful?</p>

<p>I'm thankful for any advice.</p>
",https://stackoverflow.com/questions/52964597/angular-unit-testing-components-with-protected-input-fields,"['angular', 'typescript', 'unit-testing', 'karma-jasmine', 'concept']",682,TRUE,0,1
SQLite existing database unit testing error using robolectric,"<p>In my app, I have the SQLite database which I have put into assets folder. I successfully use it in my app, but now I want to test methods in database ""provider"" class which has several methods for CRUD operations. I tried to follow up this tutorial <a href=""https://medium.com/@elye.project/android-sqlite-database-unit-testing-is-easy-a09994701162"" rel=""nofollow noreferrer"">https://medium.com/@elye.project/android-sqlite-database-unit-testing-is-easy-a09994701162</a> but my test class fails with the exception</p>

<pre><code>android.database.sqlite.SQLiteException: Cannot open SQLite connection, base error code: 14

at org.robolectric.shadows.ShadowSQLiteConnection.rethrow(ShadowSQLiteConnection.java:56)
at org.robolectric.shadows.ShadowSQLiteConnection.access$500(ShadowSQLiteConnection.java:33)
at org.robolectric.shadows.ShadowSQLiteConnection$Connections.execute(ShadowSQLiteConnection.java:466)
at org.robolectric.shadows.ShadowSQLiteConnection$Connections.open(ShadowSQLiteConnection.java:353)
at org.robolectric.shadows.ShadowSQLiteConnection.nativeOpen(ShadowSQLiteConnection.java:61)
at android.database.sqlite.SQLiteConnection.nativeOpen(SQLiteConnection.java)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
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.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:669)
at com.education.frogtravel.ege4task.database.DBHelper.openDataBase(DBHelper.java:78)
at com.education.frogtravel.ege4task.database.DBProvider.&lt;init&gt;(DBProvider.kt:22)
at com.education.frogtravel.ege4task.database.DBProviderTest.setup(DBProviderTest.kt:23)
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.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:251)
at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:188)
at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:54)
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:152)
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)
at com.intellij.rt.execution.application.AppMainV2.main(AppMainV2.java:131)

Caused by: com.almworks.sqlite4java.SQLiteException: [14] unable to open database file
at com.almworks.sqlite4java.SQLiteConnection.open0(SQLiteConnection.java:1353)
at com.almworks.sqlite4java.SQLiteConnection.open(SQLiteConnection.java:258)
at com.almworks.sqlite4java.SQLiteConnection.open(SQLiteConnection.java:269)
at org.robolectric.shadows.ShadowSQLiteConnection$Connections$1.call(ShadowSQLiteConnection.java:360)
at org.robolectric.shadows.ShadowSQLiteConnection$Connections$1.call(ShadowSQLiteConnection.java:353)
at org.robolectric.shadows.ShadowSQLiteConnection$Connections$6.call(ShadowSQLiteConnection.java:452)
at org.robolectric.shadows.ShadowSQLiteConnection$Connections$6.call(ShadowSQLiteConnection.java:446)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
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>

<p>It fails in the method </p>

<pre><code> public void openDataBase() throws SQLException {

    //Open the database
    String myPath = DB_PATH + DBScheme.DB_NAME;
    myDatabase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

}
</code></pre>

<p>in line with <code>openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);</code> </p>

<p>My whole SQLiteOpenHelper class</p>

<pre><code>import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class DBHelper extends SQLiteOpenHelper {
    private static String DB_PATH = ""/data/data/my.package.path/databases/"";
    private SQLiteDatabase myDatabase;
private final Context context;


public DBHelper(Context context) {
    super(context, DBScheme.DB_NAME, null, 1);
    this.context = context;
}

public void createDatabase() throws IOException{
    boolean dbExist = checkDataBase();

    if(!dbExist){//If database doesn't exist
        this.getReadableDatabase();

        try{
            copyDatabase();
        }catch(IOException e){
            throw new Error(""Error copying database"");
        }
    }
}


private boolean checkDataBase() {
    SQLiteDatabase checkDB = null;

    try{
        String myPath = DB_PATH + DBScheme.DB_NAME;
        checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
    }catch (SQLiteException e){
        //Database doesn't exist
    }

    return checkDB != null;
}

private void copyDatabase() throws IOException{
    InputStream inputStream = context.getAssets().open(DBScheme.DB_NAME);
    String outFileName = DB_PATH + DBScheme.DB_NAME;
    OutputStream outputStream = new FileOutputStream(outFileName);

    byte[] buffer = new byte[1024];
    int length;
    while((length = inputStream.read(buffer)) &gt; 0){
        outputStream.write(buffer, 0, length);
    }

    outputStream.flush();
    outputStream.close();
    inputStream.close();
}

public void openDataBase() throws SQLException {

    //Open the database
    String myPath = DB_PATH + DBScheme.DB_NAME;
    myDatabase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

}

@Override
public synchronized void close() {

    if(myDatabase != null)
        myDatabase.close();

    super.close();

}


@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {

}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

}

}
</code></pre>

<p>My testing class </p>

<pre><code>@RunWith(RobolectricGradleTestRunner::class)
@Config(constants = BuildConfig::class, sdk = intArrayOf(LOLLIPOP), packageName = ""my.pachage.path.database"")

class DBProviderTest {
    lateinit var dbHelper: DBProvider

    @Before
    fun setup() {
        dbHelper = DBProvider(RuntimeEnvironment.application)
        dbHelper.clearStatistics()
    }

//commented to test because crashed in this line before
//    @After
//    fun tearDown(){
//        dbHelper.clearStatistics()
//    }

    @Test
    fun testDBUpdate(){
        dbHelper = DBProvider(RuntimeEnvironment.application)

        val wordId = 1
        val isRight = true

        dbHelper.updateWordStatistics(wordId, isRight)

        assertEquals(dbHelper.getStatisticsForWord(wordId), Statistics(wordId, 1, 1))
    }
}
</code></pre>

<p>DBHelper is in Java and testing class is in Kotlin. I guess this happens because I don't make the DB on the go, but use already existing one. I can write additional logic for testing purposes, but as I understood it will be wrong, to change the logic of application just for testing. So my question is how to test DB which is not created but simply opened from android assets folder.\?</p>
",https://stackoverflow.com/questions/52576283/sqlite-existing-database-unit-testing-error-using-robolectric,"['android', 'sqlite', 'robolectric']",1054,TRUE,0,1
Unit testing express route callback - mock res object,"<p>I'm struggling to understand how to unit test a simple express get request which renders a html file.</p>

<p>In my setup when i'm receiving an error about view engine not being set, when i run my code.</p>

<p>All I want to do is simply check if the 'res.render' function has been called and mock this so it doesn't actually do what it supposed to do.</p>

<p>route.js</p>

<pre><code>module.exports = function(router) {

    router.get('/test', function(req, res, next) {
        console.log(""Hi"");
        res.render('test/test', { current: ""current""});
    });
};
</code></pre>

<p>test.js</p>

<pre><code>const request = require('supertest');
const sinon = require('sinon');
const express = require('express');
const app = express();
const routes = require('../../routes/route')(app);
describe('My routes', function () {

    before(function() {
        return this.spy = sinon.spy(app, 'render');
    });

    after(function() {
        return this.spy.restore();
    });

    it('should render to /test', function(done) {

        var res = { render: sinon.spy() };

        request(app)
            .get('/test')
            .expect(200, done)
    });
});
</code></pre>

<p>its failing on the res.render('test/test') line, i dont acutally want this line to execute i want to mock it somehow?</p>

<p>I think i'm missing something obvious!</p>

<p>Thanks all
Joey</p>
",https://stackoverflow.com/questions/48911666/unit-testing-express-route-callback-mock-res-object,"['javascript', 'node.js', 'unit-testing', 'express', 'mocha.js']",1513,TRUE,0,2
When to use Spring Framework while unit testing,"<p>I am new to Junit and Mockito and Spring. I am trying to understand when to use Spring when Unit Testing. I am able to unit test below code without using Spring. I read many articles saying one of the benefits of Spring is when unit testing. I am confused since I was successfully able test my code using JUnit and Mockito then where and why use Spring?</p>

<p>Class <code>Product</code></p>

<pre><code>public class Product {

}
</code></pre>

<p>Interface <code>ProductDao</code></p>

<pre><code>public interface ProductDao {

    int getAvailableProducts(Product product);

    int orderProduct(Product product, int orderedQuantity);

}
</code></pre>

<p>Class <code>ProductServiceTest</code></p>

<pre><code>public class ProductService {

    private ProductDao productDao;

    public void setProductDao(ProductDao productDao) {
        this.productDao = productDao;
    }

    public boolean buy(Product product, int orderedQuantity) throws InsufficientProductsException {
        boolean transactionStatus = false;
        int availableQuantity = productDao.getAvailableProducts(product);
        if (orderedQuantity &gt; availableQuantity) {
            throw new InsufficientProductsException();
        }
        productDao.orderProduct(product, orderedQuantity);
        transactionStatus = true;
        return transactionStatus;
    }

}
</code></pre>

<p>Class <code>ProductServiceTest</code></p>

<pre><code>import org.junit.Before;
import org.junit.Test;
import org.mockito.InOrder;

import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class ProductServiceTest {

    private ProductService productService;
    private ProductDao productDao;
    private Product product;
    private int purchaseQuantity = 15;

    @Before
    public void setupMock() {
        productService = new ProductService();
        product = mock(Product.class);
        productDao = mock(ProductDao.class);
        productService.setProductDao(productDao);
    }

    @Test
    public void testBuy() throws InsufficientProductsException {
        int availableQuantity = 30;
        System.out.println(""Stubbing getAvailableProducts(product) to return "" + availableQuantity);
        when(productDao.getAvailableProducts(product)).thenReturn(availableQuantity);
        System.out.println(""Calling ProductService.buy(product,"" + purchaseQuantity + "")"");
        productService.buy(product, purchaseQuantity);
        System.out.println(""Verifying ProductDao(product, "" + purchaseQuantity + "") is called"");
        verify(productDao).orderProduct(product, purchaseQuantity);
        System.out.println(""Verifying getAvailableProducts(product) is called at least once"");
        verify(productDao, atLeastOnce()).getAvailableProducts(product);
        System.out.println(""Verifying order of method calls on ProductDao: First call getAvailableProducts() followed by orderProduct()"");
        InOrder order = inOrder(productDao);
        order.verify(productDao).getAvailableProducts(product);
        order.verify(productDao).orderProduct(product, purchaseQuantity);
    }

}
</code></pre>

<p>The difference between JUnit and Mockito?</p>

<p>If we mock everything (For example, everything inside buy method in <code>ProductService</code>) are we really unit testing. Mock everything setup everything how it is expected to behave. Then what is the point unit testing?</p>
",https://stackoverflow.com/questions/50071925/when-to-use-spring-framework-while-unit-testing,"['java', 'spring-mvc', 'junit', 'mockito', 'spring-mvc-test']",327,FALSE,0,1
Vertx: how to create Message for unit-testing?,"<p>I need to create a Message for unit-testing. How to create Message in Vertx?</p>
",https://stackoverflow.com/questions/52431839/vertx-how-to-create-message-for-unit-testing,"['message', 'vert.x', 'creation']",351,TRUE,0,1
Rxjs Observable delay stream unit testing in Angular,"<p>I am trying to write a unit test of an Angular service that returns an Observable</p>

<pre><code>// MainService
export class MainService {
  connect(): Observable&lt;IData&gt; {
    return this.depService.subscribe().pipe(
      map(res =&gt; JSON.parse(res.body))
    );
  }
}

// depService
export class depService {

  subscribe(): Observable&lt;string&gt; {
    return of(data1, data2, data3).pipe(delay(500));
  }
}
</code></pre>

<p>I tried to write a unit test like this,</p>

<pre><code>  it('Testing Delayed Observable', () =&gt; {
    const service = TestBed.get(MainService);
    service.connect().subscribe(res =&gt; {
      expect(res).toEqual([data1, data2, data3]);
    });
  });
</code></pre>

<p>I know this is wrong, but the test is always passing because I the test shuts down even before expect logic.
What is the best way to test a service that has dependency on another service that returns a stream????</p>
",https://stackoverflow.com/questions/52562750/rxjs-observable-delay-stream-unit-testing-in-angular,"['angular', 'rxjs', 'observable', 'karma-jasmine']",1872,FALSE,0,1
Django-like unit testing database in plain python,"<p>I have a python project that uses Postgresql. I would like to use django-like unit tests where the database is created and destroyed at every test. However, I don't want to use sqlalchemy.
I tried something along these lines:</p>

<pre><code>pg = psycopg2.connect(
""host={} dbname={} user={} password={}"".format(
POSTGRES_HOST, 'postgres', POSTGRES_USER, POSTGRES_PASSWORD))

pg.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
cur = pg.cursor()




def reset_db():
    cur.execute('DROP DATABASE IF EXISTS {} '.format(POSTGRES_DB))
    cur.execute('CREATE DATABASE {}'.format(POSTGRES_DB))

    newconn = psycopg2.connect(
    ""host={} dbname={} user={} password={}"".format(
    POSTGRES_HOST, POSTGRES_DB, POSTGRES_USER, POSTGRES_PASSWORD))

    newcur =  newconn.cursor()

    # SCHEMAS is an imported dict containing schema creation instructions
    for schema in SCHEMAS:
        newcur.execute(SCHEMAS[schema])

    return newcur

class Test(TestCase):
    def setUp(self):
        os.environ['testing'] = 'true'
        self.cur = reset_db()
</code></pre>

<p>Then the setUp method sets an environmental variable that informs my database layer to use the testing db.</p>

<p>This seems to work fine. The only problem is the reset_db() takes about 0.8 seconds, which is far too much.</p>

<p>Are there better approaches or ways to optimise my approach?</p>
",https://stackoverflow.com/questions/51079104/django-like-unit-testing-database-in-plain-python,"['python', 'django', 'postgresql', 'unit-testing']",47,TRUE,0,2
Unit testing using Mocha with Express Rest API,"<p>I'm learning unit testing. So far I was able to run simple tests like ""Add two numbers and test if they are above 0"", but I want to build a REST API using TDD. So far I have this:</p>

<p>My <code>routes/index.js</code> file:</p>

<pre><code>var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function (req, res, next) {
    res.send({val: true});
});

module.exports = router;
</code></pre>

<p>My <code>index.test.js</code> file:</p>

<pre><code>var mocha = require('mocha');
var assert = require('chai').assert;
var index = require('../routes/index');

describe('Index methods', () =&gt; {
    it('Returns true', done =&gt; {
        index
            .get('http://localhost:3000')
            .end(function (res) {
                expect(res.status).to.equal(200);
                done();
            })
    })
});
</code></pre>

<p>I user a tutorial to do this, but when I try to run this I get:</p>

<pre><code>TypeError: index.get(...).end is not a function
</code></pre>

<p>So I'm guessing there is something wrong, but have no idea what. That's my first day learning TDD so if you see anything stupid please let me know.</p>

<p>Doing this:</p>

<pre><code>it('Returns true', done =&gt; {
    var resp = index.get('http://localhost:3000/');
    assert.equal(resp.val === true);
    done();
})
</code></pre>

<p>Also results in an error:</p>

<pre><code>AssertionError: expected false to equal undefined
</code></pre>
",https://stackoverflow.com/questions/51137217/unit-testing-using-mocha-with-express-rest-api,"['javascript', 'node.js', 'express', 'mocha.js', 'tdd']",2002,TRUE,0,4
"PHP Laravel Unit Testing, Custom Assert failure messages","<p>I am new to Laravel and also unit testing in general.</p>

<p>I have written a simple test using the <a href=""https://laravel.com/docs/5.6/http-tests#response-assertions"" rel=""nofollow noreferrer"">guide from Laravel</a>, </p>

<pre><code>public function testGet(){
    $this-&gt;get('/api/accounts/1')-&gt;assertStatus(200)-&gt;assertJsonStructure([
        'status','data'
    ]);
}
</code></pre>

<p>When the test is run, it generates the following failure (which is intended):</p>

<pre><code>Time: 127 ms, Memory: 12.00MB
There was 1 failure:

1) Tests\Unit\AccountApiTest::testGet
Invalid JSON was returned from the route.
</code></pre>

<p>My question is, is there any way we can customize the message generated when a test fails for all the available assertion in Laravel? For this case, the message</p>

<pre><code>Invalid JSON was returned from the route.
</code></pre>
",https://stackoverflow.com/questions/51169298/php-laravel-unit-testing-custom-assert-failure-messages,"['php', 'laravel', 'phpunit']",1433,TRUE,0,1
Unit testing a method that returns different values,"<p>If a method returns each time different different values,how to do unit testing for that method</p>

<p>i m trying </p>

<pre><code>result=someObject.someMethod()
expected_result=someValue
asertEqual(result,expected_result)
</code></pre>

<p>but in each time the result is different ,so some time the test is clear and some times it fails</p>
",https://stackoverflow.com/questions/51473428/unit-testing-a-method-that-returns-different-values,"['django', 'unit-testing']",49,FALSE,0,1
Unit testing API endpoints that needs access tokens,"<p>I am trying to write a unit tests suite to test all end points of an API. But some of my API end points are protected and need access tokens. I understand that unit tests shall be independent and all prerequisites shall be mocked, but how can I mock an <code>access_token</code>?</p>

<p>I am using <code>Node JS</code> with <code>Sails JS</code> for backend development and <code>Mocha</code> framework for testing along with <code>Chai</code> assertion library. I am also using <code>jwt auth</code></p>

<p>Any help would be appreciated.  </p>
",https://stackoverflow.com/questions/49670859/unit-testing-api-endpoints-that-needs-access-tokens,"['unit-testing', 'mocha.js', 'access-token']",361,FALSE,0,0
Module.exports for unit-testing inside a route/controller,"<p>I'm pretty new to NodeJS and unit testing. </p>

<p>I use <code>Jest</code>, but it should be the same ""issue"" with <code>Mocha</code> or <code>Ava</code>, or <code>whatever</code>...Because my problem seems to be about <code>export</code>/<code>import</code>...</p>

<p>I have a file <code>learning.js</code> with some functions</p>

<pre><code>// learning.js

function sum(a, b) {
  return a + b
}

const multiply = (a, b) =&gt; a * b

module.exports = { sum: sum, multiply: multiply }
</code></pre>

<p>...and a <code>some.test.js</code> file:</p>

<pre><code>// some.test.js

const { sum, multiply } = require('./learning')
// const { sum, multiply } = require('./another')

test('adds 1 + 2 to equal 3', () =&gt; {
  expect(sum(1, 2)).toBe(3)
})

test('multiplies 2 x 2 to equal 4', () =&gt; {
  expect(multiply(2, 2)).toBe(4)
})
</code></pre>

<p>At this point, everything is perfect, my tests run and pass.</p>

<p>However, I've a third file named <code>another.js</code> structured that way (I use <code>express</code>):</p>

<pre><code>router.get('/another', async function(req, res) {

  // TESTS
  function sum(a, b) {
    return a + b
  }

  const multiply = (a, b) =&gt; a * b

  // DO SOME OTHER STUFF...

  res.status(200).send('ok')
})

module.exports = { sum: sum, multiply: multiply }
//module.exports = router
</code></pre>

<p>When I try to run the same tests from <code>some.test.js</code> (changing only the <code>require</code> statement to map to <code>another.js</code>), I can't make it works. My tests fail: <code>TypeError multiply is not a function</code>.</p>

<p>I tried to move <code>export</code>somewhere else, to rename some stuff with <code>dot.notation</code>... I can't make it work.</p>

<p>Any clue? Thanks!</p>
",https://stackoverflow.com/questions/49467724/module-exports-for-unit-testing-inside-a-route-controller,"['javascript', 'unit-testing', 'express', 'export', 'jestjs']",1694,TRUE,0,1
AngularJS - How To Architect Services For Unit Testing,"<p>I have a service that have one public method and several private methods (which the public method uses). I would like to unit test this service but the only method I can test is my public method. For the sake of unit testing, should I make my private methods public so I can unit test the methods?</p>

<p>Here is quick pseudo code of my service:</p>

<pre><code>WeatherService {
    return getWeather;

    getWeather(location) {
        return fetchWeather(location).then(processData);
    }

    fetchWeather(location) {
        return $http(config);
    }

    processData(data) {
        data.temp = convertTemp(data.temp);
        data.location = convertLatLong(data.location);
        return data;
    }

    convertTemp(temp) {...}
    convertLatLong(location) {...}
}
</code></pre>
",https://stackoverflow.com/questions/48493638/angularjs-how-to-architect-services-for-unit-testing,"['angularjs', 'unit-testing', 'jasmine']",30,FALSE,0,2
Unit Testing Azure Function with Change Feed Trigger,"<p>I'm trying to write a unit test for an Azure Function with Change Feed Trigger.</p>

<p>Is it possible to trigger the function using document db emulator?</p>

<p>or </p>

<p>Should I call onto the function directly?</p>

<p>e.g., FunctionClass.Run(documents, null);</p>

<p>Also, is there any example on creating unit test for azure function?</p>

<p>I wasn't able to find any examples for similar cases.</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/50615122/unit-testing-azure-function-with-change-feed-trigger,"['unit-testing', 'azure', 'azure-functions', 'azure-cosmosdb']",587,TRUE,-2,1
Unit testing cordova &#39;deviceready&#39; event in angular application,"<p>Unit testing cordova 'deviceready' event in angular application - I am using cordova to convert my angular 5 application to mobile app and I am able to do that. I am getting app version and build number details via cordova plugin once the deviceready event fired from cordova. I would like to test this scenario in unit testing. I have a route guard service in my app which will determine to allow user to login or redirect to different page based on the version. so in my guard I have the below code.</p>

<p>canActivate(): Observable | Promise | boolean {</p>

<pre><code>if (this.utils.isMobile()) {
  return new Observable((observer) =&gt; {
    this.utils.getSomeData().subscribe((d) =&gt; {
      document.addEventListener('deviceready', () =&gt; {
        if (this.utils.compareData('5', '55')) {
          observer.next(true);
          observer.complete();
        } else {
          observer.next(false);
          observer.complete();
        }
      });
    });
  });
}

return true;
</code></pre>

<p>}</p>

<p>I had to use custom observer here in order to make my canActivate wait till the device ready event fire and comparison have completed. I am facing difficulties testing this. How do I fire this event and test the observer at the same time?</p>
",https://stackoverflow.com/questions/49984969/unit-testing-cordova-deviceready-event-in-angular-application,"['angular', 'unit-testing', 'cordova', 'jasmine', 'observers']",242,FALSE,0,1
How to avoid overusing interfaces when unit testing,"<p>In an attempt to make my code friendly for unit testing, it seems wise to utilize depenency injection. This requires that any dependent class must implement an interface with the exact same set of methods. </p>

<p>I also see advice saying that I shouldn't have an interface for every class, but I don't see how I could possibly follow both pieces of advice. If I want unit testing, every single useful class must adhere to an interface.</p>

<p>Proof: Suppose there exists a class that does not implement any interfaces. If I am able to unit test my entire program, then no other code depends on this class. Therefore this class is useless and might as well be deleted.</p>

<p>Is there something I am misunderstanding? Is there a way to unit test without copy/pasting all of my classes into equivalently structured interfaces?</p>
",https://stackoverflow.com/questions/48970287/how-to-avoid-overusing-interfaces-when-unit-testing,"['unit-testing', 'dependency-injection']",227,TRUE,0,3
unit testing angular 2(ionic 2) custom directive,"<p>I made a custom directive for text masking in my ionic application. The directive is for input text masking for the phone number.
It uses <code>ngControl</code> to get and set the values of the input field.</p>

<pre><code>@HostListener('keyup', ['$event'])
onKeyUp($event: any) {
        var inputValue = this.ngControl.control.value;   
        this.ngControl.control.setValue(this.getMaskedValue(inputValue));
    }
}
</code></pre>

<p>I tried many approaches to test it but I was unable to set the value. I was able to get <code>ngControl</code> by importing the <code>FormsModule</code> and binding the input.</p>

<p>But I still can't get value as <code>this.ngControl.control.value</code>. When I type in the input field, it works fine but unable to define test case.</p>

<p>here is the test case snippet</p>

<pre><code>it('should have masked value', () =&gt; {
  fixture.detectChanges();
  let element = inputEl.nativeElement;
  element.value = '999';
  inputEl.nativeElement.dispatchEvent(new Event('keyup', key));
  fixture.detectChanges();
  fixture.whenStable().then(() =&gt; {
    expect(element.value).toEqual('(999)');
  });
}
</code></pre>

<p>This is my test component :</p>

<pre><code>@Component({
  template: `&lt;input type=""text"" [(ngModel)]=""val""   customDirective=""(999)-999-9999""&gt;`
})
class TestCustomDirectiveComponent {
  constructor(public formBuilder: FormBuilder) {}
  val = '';
}
</code></pre>

<p>I want to write a test case like this <code>expect(element.value).toEqual('(999)-999-9999</code>. How can I test it?</p>
",https://stackoverflow.com/questions/49410426/unit-testing-angular-2ionic-2-custom-directive,"['javascript', 'angular', 'unit-testing', 'ionic2', 'testbed']",117,TRUE,0,1
Unit Testing Concrete Methods in an Abstract Class,"<p>Suppose I want to unit test the following abstract class:</p>

<pre class=""lang-java prettyprint-override""><code>abstract class Fruit {

  private int calories;

  public Fruit(int calories) {
    this.calories = calories;
  }

  int getCalories() {
    return this.calories;
  }

  double getKilojoules() {
    return this.calories * 4.184;
  }
}
</code></pre>

<p>I agree that abstract classes and interfaces should not be tested - their implementations should, but what about concretely defined methods like simple getters like <code>getCalories()</code>?</p>

<p>Now some say that simple methods like getters should not be tested, but even then: what about methods like <code>getKilojoules()</code>?</p>
",https://stackoverflow.com/questions/52919271/unit-testing-concrete-methods-in-an-abstract-class,"['java', 'unit-testing', 'oop']",200,FALSE,0,0
Handling exceptions during unit testing and code coverage,"<p>I have try-catch structure in my node.js code which looks like:</p>

<pre><code>try {
  //do some code
}
catch(e) {
  logError(e);
}
</code></pre>

<p>I have a feeling that this approach is not very good, but the most biggest problem is the unit testing (mocha and chai) and code coverage (nyc). I can test catch section only by provoking exception just in work code, but in this case I will need come flag structure just inside the code to manage the flow like:</p>

<pre><code>try {
  if(testingFlag)
    throw new Error('Test error');
//do some code
}
catch(e) {
  logError(e);
}
</code></pre>

<p>Only in this case I will be able to change the script direction and test this section.
Basically the questions is: is there any best practice to handle exceptions, semantic and code errors in a proper way to be able to do unit testing and code coverage without any problems?
Thanks.</p>
",https://stackoverflow.com/questions/51555573/handling-exceptions-during-unit-testing-and-code-coverage,"['javascript', 'node.js', 'unit-testing', 'code-coverage']",418,FALSE,0,0
Unit testing: Emulate that user has specific calendar,"<p>I need to write tests for initialising <code>Date</code> objects, when user has, for example, <em>Buddhist</em> calendar and my formatter will have <em>Gregorian</em> calendar. </p>

<p>Date init function: </p>

<pre><code>internal let calendar = Calendar(identifier: .gregorian)
private let formatter = DateFormatter()

init?(dateValue: String?, format: String) {
    guard let dateValue = dateValue else {
        return nil
    }

    formatter.dateFormat = format
    formatter.calendar = calendar
    guard let date = formatter.date(from: dateValue) else {
        return nil
    }

    self.init(timeIntervalSince1970: date.timeIntervalSince1970)
}
</code></pre>

<p>How can I setup user environment (calendar)? Like user has other than <em>Gregorian</em> calendar? Is it possible?</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/51080619/unit-testing-emulate-that-user-has-specific-calendar,"['ios', 'swift', 'unit-testing', 'swift4']",431,FALSE,0,1
How to configure properly unit testing with Errbot?,"<p>I tried to follow this guide <a href=""http://errbot.io/en/latest/user_guide/plugin_development/testing.html"" rel=""nofollow noreferrer"">http://errbot.io/en/latest/user_guide/plugin_development/testing.html</a></p>

<p>I installed <code>pytest</code> and launch it with</p>

<pre><code>pytest --rootdir='./srv/plugins'
</code></pre>

<p>but I have this following error:</p>

<pre><code>Traceback (most recent call last):
  File ""./errbot/app/venv/lib/python3.4/site-packages/errbot/backends/graphic.py"", line 19, in &lt;module&gt;
    from PySide import QtCore, QtGui, QtWebKit
ImportError: No module named 'PySide'
2018-06-11 16:30:44,930 CRITICAL errbot.backends.graphic    To install graphic support use:
    pip install errbot[graphic]
</code></pre>

<p>It looks like <code>pytest</code> tries to run Errbot in graphical mode whereas I am using Errbot with a text backend just fine.</p>

<p>As the plugins might need at some point to use the configuration file given to Errbot, I wonder how to do the same while using <code>pytest</code>...</p>

<p>I reproduce on the host the arboresence found on a <a href=""https://github.com/rroemhild/docker-errbot"" rel=""nofollow noreferrer"">Docker image</a></p>

<pre><code>errbot
    app
        venv
        config.py
        requirements.txt
    srv
        data
        errbackends
        plugins
            Samples
                samples.plug
                samples.py
    run.sh
</code></pre>

<p>Then, I run <code>errbot</code> with a my backend - in my case Mattermost - like this:</p>

<pre><code>./run.sh -c ./app/config.py
</code></pre>

<p>And for the <code>text</code> as backend</p>

<pre><code>./run.sh -c ./app/config.py --text
</code></pre>

<p>In <code>run.sh</code>, I inject some environment variables and activate <code>venv</code> before calling <code>errbot</code>.</p>

<p>Actually, I could reproduce my issue on the unit testing by launching <code>errbot</code> in graphical mode</p>

<pre><code>./run.sh -c ./app/config.py --graphic
</code></pre>

<p>Therefore, I wonder how to inject the right config for the unit tests as I can do while running <code>errbot</code>.</p>
",https://stackoverflow.com/questions/50800498/how-to-configure-properly-unit-testing-with-errbot,"['python', 'unit-testing', 'testing', 'plugins', 'errbot']",164,FALSE,0,0
Php unit testing pass config file from command,"<p>I am implementing some Integration tests by using unit testing. I am using the <code>setUp()</code> method to set a config file. My config file consists of some <code>Api keys</code> <code>API secret</code> etc. This is working good.</p>

<pre><code>public function setUp()
{
    $this-&gt;_pipeline = new Pipline($this);
    $this-&gt;_pipeline-&gt;setConfig(\Api\Models\ConfigModel::createFromFile(__DIR__ . '/test/integration/assets/config'));
    $users = $this-&gt;_pipeline-&gt;users-&gt;listUsers();
    $this-&gt;_userId = $users-&gt;result-&gt;data[0]-&gt;user_id;

    parent::setUp(); 
}
</code></pre>

<p>This method is working good in this way.</p>

<p><strong>Problem</strong>
But I want to pass the config file from command. Currently i am using this command </p>

<blockquote>
  <p>php ./vendor/phpunit/phpunit/phpunit -c ./test/integration/phpunit.xml</p>
</blockquote>

<p>Is there a way i can pass this from command something like this </p>

<blockquote>
  <p>php ./vendor/phpunit/phpunit/phpunit -c ./test/integration/phpunit.xml
  -c2 /test/integration/assets/config</p>
</blockquote>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/51779789/php-unit-testing-pass-config-file-from-command,"['php', 'unit-testing', 'integration-testing']",755,TRUE,0,1
Unit testing a function that depends on database,"<p>I am running tests on some functions. I have a function that uses database queries. So, I have gone through the blogs and docs that say we have to make an in memory or test database to use such functions. Below is my function,</p>

<pre><code>def already_exists(story_data,c):
    # TODO(salmanhaseeb): Implement de-dupe functionality by checking if it already
    # exists in the DB.
    c.execute(""""""SELECT COUNT(*) from posts where post_id = ?"""""", (story_data.post_id,))
    (number_of_rows,)=c.fetchone()
    if number_of_rows &gt; 0:
        return True
    return False
</code></pre>

<p>This function hits the production database. My question is that, when in testing, I create an in memory database and populate my values there, I will be querying that database (test DB). But I want to test my <code>already_exists()</code> function, after calling my <code>already_exists</code> function from test, my production db will be hit. How do I make my test DB hit while testing this function?</p>
",https://stackoverflow.com/questions/52300270/unit-testing-a-function-that-depends-on-database,"['python', 'unit-testing', 'python-unittest', 'database-testing']",5114,TRUE,0,2
Simulate / Mock a MySql Database for Unit Testing,"<p>For our applications we have created a series of healthchecks. One of these health checks checks whether or not a MySql database is up and running. In order to unit test this functionality I need to mock or simulate a database and run the health check against it. </p>

<p>To establish a connection to the MySql database being checked, we are using <code>DriverManager.getConnection()</code>. So we first tried to mock the return value of <code>getConnection()</code>. However, that is a static method and Mockito is unable to mock it. Then we turned to Powermock because it is able to mock static methods. Unfortunately, we found it to be poorly supported with JUnit5 and we had to clutter up our pom with a lot of dependencies. Not to mention the code was becoming overly complicated. In the end, we decide to look for other options besides mocking. </p>

<p>Basically, our health check just needs to make sure that the MySQL url, username, and password are correct and the database will accept a connection. Ideally, our unit tests would reflect these requirements. </p>

<p>So, our next idea is to use an In-Memory database, like this <a href=""https://www.baeldung.com/spring-jpa-test-in-memory-database"" rel=""nofollow noreferrer""><strong>one</strong></a> from Baeldung. This seems like a great option but I'm worried it won't behave in the same way a real MySQL database will. Is there a way to create an In-memory MySQl database and establish a connection with <code>DriverManager.getConnection()</code>? This would effectively simulate our real life health check</p>
",https://stackoverflow.com/questions/51757805/simulate-mock-a-mysql-database-for-unit-testing,"['java', 'mysql', 'unit-testing', 'mockito', 'powermock']",1626,FALSE,0,1
Unit testing RxJava code with multiple external calls,"<p>Here is some RxJava code that I want to test:</p>

<pre><code>public void triggerCancelOrderJob() {
        couchConnector()
            .findAbandonedOpenOrders()
            .flatMap(results -&gt; results.rows())
            .flatMap(
                row -&gt;
                    Observable.just(row)
                        .subscribeOn(Schedulers.io())
                        .map(
                            s -&gt; return s.value())
                        .flatMap(
                            orderId -&gt; {
                              return RxReactiveStreams.toObservable(
                                  serviceTokenCache
                                     .get(OrderApiConstants.SERVICE_TOKEN_CACHE_KEY)
                                      .flatMap(
                                          issueToken -&gt; {
                                            return cancelOrderApiConnector()
                                                .invokeAPI(
                                                    RequestInputModel.builder().build(),
                                                    RequestInputModel.RequestBodyModel.builder().build());
                                          }));
                            }))
            .subscribe(//additional code)
</code></pre>

<p>So what's happening is that I  run an async CB query, get an <code>Observable&lt; AsyncN1qlQueryResult &gt;</code>, then for each row I call call two external services one after the another (first call to the <code>serviceTokenCache</code> and second call to the <code>cancelOrderApiConnector</code>). Each row runs in a separate <code>IO</code> thread.</p>

<p>Note: <code>serviceTokenCache.get()</code> and <code>cancelOrderApiConnector().invokeAPI()</code> return a <code>Mono</code> respectively.</p>

<p>I cannot figure out how to test this code. What all components need to be tested? Since each row will run in its separate thread, I cannot wrap my head around how to test such asynchronous code.</p>
",https://stackoverflow.com/questions/53425283/unit-testing-rxjava-code-with-multiple-external-calls,"['java', 'unit-testing', 'mocking', 'rx-java', 'reactive-programming']",50,FALSE,0,0
angularjs unit testing unable to inject a service,"<p>I have a really simple service:</p>

<pre><code>'use strict';

angular.module('sapphire.orders').service('deliveryDatesService', service);

function service() {
    return {
        clearAddressReason: clearAddressReason,
        getMinDate: getMinDate
    };

    //////////////////////////////////////////////////

    function clearAddressReason(model, dateReasons, reasons) {
        if (model.manualAddress) {
            model.overrideDates = true;
            reasons.date = dateReasons.filter(function (item) {
                return item.value === 'D4';
            })[0];
        } else {
            reasons.address = null;
            if (!reasons.date || reasons.date.value === 'D4') {
                reasons.date = null;
                model.overrideDates = false;
            }
        }
    };

    function getMinDate(model) {
        var now = new Date();

        // If we are not overriding dates, set to today
        if (!model.overrideDates) return now;

        // If dates are overriden, then the min date is today + daysToDispatch
        return new Date(now.setDate(now.getDate() + model.daysToDispatch));
    };
};
</code></pre>

<p>It has no dependencies, so I want to test the methods.
So I have tried to create a spec like this:</p>

<pre><code>'use strict';

describe('Service: deliveryDatesService', function () {
    beforeEach(module('sapphire.orders'));

    var service,
        reasons,
        dateReasons;

    beforeEach(inject(function (deliveryDatesService) {
        console.log(deliveryDatesService);
        service = deliveryDatesService;
        reasons = {};
        dateReasons = [{ value: 'D4' }];
    }));

    it('can create an instance of the service', function () {
        expect(service).toBeDefined();
    });

    it('if manual delivery address is true, then override dates should be true', function () {
        var model = { manualDeliveryDate: true };
        service.clearAddressReason(model, dateReasons, reasons);
        expect(model.overrideDates).toBe(true);
    });

    it('if manual delivery address is false, then override dates should be false', function () {
        var model = { manualDeliveryDate: false };
        service.clearAddressReason(model, dateReasons, reasons);
        expect(model.overrideDates).toBe(false);
    });

    it('minimum date cannot be less than today', function () {
        var model = { };
        var minDate = service.getMinDate(model);
        var now = new Date();
        expect(minDate).toBeGreaterThan(now);
    });
});
</code></pre>

<p>But my service is always undefined. Can someone tell me what I am doing wrong please?</p>

<hr>

<p><strong><em>Update</em></strong></p>

<p>So, it turns out this is to do with one or more services interfering somehow.
In my <strong>karma.conf.js</strong> I had declared all my bower applications and then this:</p>

<pre><code>'src/app/app.module.js',
'src/app/**/*module.js',
'src/app/**/*constants.js',
'src/app/**/*service.js',
'src/app/**/*routes.js',
'src/app/**/*.js',
'test/spec/**/*.js'
</code></pre>

<p>I created a test service in the root of my scripts directory and then created a spec file to see if it was created. It moaned at me about a reference error in a file that was not related at all. It moaned about this bit of code:</p>

<pre><code>angular.module('sapphire.core').factory('options', service);

function service($rootScope) {
    return {
        get: get,
        save: save
    };

    //////////////////////////////////////////////////

    function get() {
        if (Modernizr.localstorage) {
            var storageData = angular.fromJson(localStorage.options);
            if (storageData) {
                return angular.fromJson(storageData);
            }
        }

        return {
            background: {
                enabled: true,
                enableSnow: true,
                opacity: 0.6
            }
        };
    };

    function save(options) {
        if (Modernizr.localstorage) {
            localStorage.options = angular.toJson(options);
            $rootScope.$options = get();
        }
    };
};
</code></pre>

<p>stating that Modernizr is not defined.
I changed the code to this:</p>

<pre><code>angular.module('sapphire.core').factory('options', service);

function service($rootScope) {
    return {
        get: get,
        save: save
    };

    //////////////////////////////////////////////////

    function get() {
        if (typeof Modernizr == 'object' &amp;&amp; Modernizr.localstorage) {
            var storageData = angular.fromJson(localStorage.options);
            if (storageData) {
                return angular.fromJson(storageData);
            }
        }

        return {
            background: {
                enabled: true,
                enableSnow: true,
                opacity: 0.6
            }
        };
    };

    function save(options) {
        if (typeof Modernizr == 'object' &amp;&amp; Modernizr.localstorage) {
            localStorage.options = angular.toJson(options);
            $rootScope.$options = get();
        }
    };
};
</code></pre>

<p>and it started working. But my other test was not.
So I changed my references in <strong>karma.conf.js</strong> to this:</p>

<pre><code>'src/app/app.module.js',
'src/app/orders/orders.module.js',
'src/app/orders/shared/*.js',
'test/spec/**/*.js'
</code></pre>

<p>and it started working.
That leads me to believe there is something wrong with my application somewhere. Maybe another reference like <strong>Modernizr</strong>. I still have an outstanding question though. How can services that are not dependant on another service interfere?
I think it's worth noting that each service, controller, directive is in it's own file and they all follow this structure:</p>

<pre><code>(function () {
    'use strict';

    angular.module('sapphire.core').factory('options', service);

    function service($rootScope) {
        return {
            get: get,
            save: save
        };

        //////////////////////////////////////////////////

        function get() {
            if (typeof Modernizr == 'object' &amp;&amp; Modernizr.localstorage) {
                var storageData = angular.fromJson(localStorage.options);
                if (storageData) {
                    return angular.fromJson(storageData);
                }
            }

            return {
                background: {
                    enabled: true,
                    enableSnow: true,
                    opacity: 0.6
                }
            };
        };

        function save(options) {
            if (typeof Modernizr == 'object' &amp;&amp; Modernizr.localstorage) {
                localStorage.options = angular.toJson(options);
                $rootScope.$options = get();
            }
        };
    };
})();
</code></pre>

<p>I am wondering that because I wrap them in anonymous functions that execute themselves, is that what is causing this problem?</p>

<hr>

<p><strong>* Solution *</strong></p>

<p>So in the end I found out exactly what was causing this issue. It was indeed to do with the <strong>file</strong> in <strong>karma.conf.js</strong>. I had told it to load all files and somewhere in there was something it didn't like.
After a bit of playing I finally found what it was and thought I would share it just in case someone else gets here.</p>

<p>The issue was routes. I am using <strong>ui.router</strong> and it appears that having them in your tests fail.
I changed my files section to this:</p>

<pre><code>'src/app/app.module.js',
'src/app/**/*module.js',
'src/app/**/*constants.js',
'src/app/**/*service.js',
'src/app/**/*controller.js',
//'src/app/**/*routes.js',

'test/spec/**/*.js'
</code></pre>

<p>As you can see I have a <strong>routes</strong> file(s) commented out. If I bring them back in, everything fails.</p>
",https://stackoverflow.com/questions/49297272/angularjs-unit-testing-unable-to-inject-a-service,"['angularjs', 'jasmine', 'karma-jasmine']",42,TRUE,0,1
Unable to Modify Application Settings when Unit Testing,"<p>I am trying to change some Application Settings that live within the Settings of a Windows Service which would be set during installation. The settings I want to set for a Unit Test.</p>

<p>Now, the assemblyinfo file has the InternalsVisibleTo to the Unit Test Project.</p>

<p>In my Test Method I can go drill down to Settings.Default on the Project I want to test and I can see all the settings. However, when I go for instance:</p>

<pre><code>   dummy.PropertyValues[""MySetting""].PropertyValue = ""SomeValue"";
</code></pre>

<p>I get a null reference exception.</p>

<p>dummy is set as:</p>

<pre><code>    var dummy = MyProject.Properties.Settings.Default;
</code></pre>

<p>Is there away I can set the Application Settings I want for a unit test?</p>
",https://stackoverflow.com/questions/51047656/unable-to-modify-application-settings-when-unit-testing,['c#'],70,TRUE,0,2
Unit Testing with the Entity Framework change tracker,"<p>How do I test/simulate/use the change tracker of Entity Framework when testing? </p>

<p>For my example below I would like to verify that the fake list of LogEntries starts out one way and by the time the <code>SaveChanges</code> is called, is modified to match my expectations. </p>

<p>I was initially thinking of something like exposing a public property in the <code>FakeLogRepo</code> that would show me the fake list of LogEntries so that I can easily compare the before/after, but I still can't figure out how to update it without passing in something from the <code>LogInteraction</code> (since in production Entity Framework handles that through its change tracker).</p>

<p>For a simplified example of what I have:</p>

<pre><code>public class LogInteraction : ILogInteraction
{
    private readonly ILogRepo _logRepo;

    public LogInteraction(ILogRepo logRepo)
    {
        _logRepo = logRepo;
    }

    public void UpdateLog(IEnumerable&lt;Detail&gt; details)
    {
        foreach (var detail in details)
        {
            var record = _logRepo.GetById(detail.Id);
            record.Status = detail.Status;
            record.Message = detail.Message;
        }

        _logRepo.UpdateLogEntries();
    }
}

public class LogRepo : ILogRepo
{
    private readonly LogContext _logContext;

    public LogRepo()
    {
        _logContext = new LogContext();
    }

    public LogEntry GetById(int id)
    {
        return _logContext.LogEntries.Single(r =&gt; r.Id == id);
    }

    public void UpdateLogEntries()
    {
        _logContext.SaveChanges();
    }
}

public class LogContext : DbContext
{
    public DbSet&lt;LogEntry&gt; LogEntries {get; set;}
}
</code></pre>

<p>When in production the <code>_logContext.SaveChanges()</code> does what it's supposed to and update the changed records through the magic of Entity Framework's change tracker. However in testing I'm not using a DB, I'd like to use a fake list of LogEntry to simulate this. Since <code>List</code> doesn't have a change tracker, I thought about having it inherit from <code>IObservableCollection</code> but couldn't figure out how to use it without a substantial refactor of my code. In fact any idea I have involves a substantial rewrite of my code just to work with a test (and will leave unused/extraneous code in production).</p>

<p>Am I barking up the wrong tree and need to change my mindset overall or am I just not seeing something that I'm close to?</p>
",https://stackoverflow.com/questions/50218873/unit-testing-with-the-entity-framework-change-tracker,"['c#', 'entity-framework', 'unit-testing']",1267,FALSE,0,0
Unit testing store procedure calls with Entity Framework,"<p>I need to add unit tests and increase code coverage of an application that is based o store procedure calls using Entity Framework. </p>

<p>Example 1:</p>

<pre><code>    public virtual DbSet&lt;Person&gt; Persons { get; set; }

    public virtual IEnumerable&lt;Person&gt; PersonsFromSP()
    {
        return Persons.SqlQuery(""spGetPersons"").ToList();
    }
</code></pre>

<p>Example 2:</p>

<pre><code>    public virtual IEnumerable&lt;Animal&gt; AnimalsFromSP()
    {
        return Database.SqlQuery&lt;Animal&gt;(""spGetAnimals"").ToList();
    }
</code></pre>

<p>There's also code with business logic and other stuff, but it's all based on these calls.</p>

<p>Whats a good approach at testing this? </p>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/49497384/unit-testing-store-procedure-calls-with-entity-framework,"['visual-studio', 'entity-framework', 'unit-testing', 'stored-procedures']",182,TRUE,0,1
Unit testing in Android Studio gives an error,"<p>I am trying to write a unit test for my class, but I am getting the following error</p>

<pre><code>java.lang.RuntimeException: Method isEmpty in android.text.TextUtils not mocked. See http://g.co/androidstudio/not-mocked for details.

at android.text.TextUtils.isEmpty(TextUtils.java)
at com.mvvm.testmvvm.Model.User.isValidUser(User.java:37)
at com.mvvm.testmvvm.LoginViewModelTest.isValidUser_Test(LoginViewModelTest.java:15)
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.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)
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.AppMainV2.main(AppMainV2.java:131)
</code></pre>

<p>this is my class </p>

<pre><code>public class User {

    private String  mEmail;
    private String  mPassword;

    public User() {
    }

    public User(String mEmail, String mPassword) {
        this.mEmail = mEmail;
        this.mPassword = mPassword;
    }

    public String getEmail() {
        return mEmail;
    }

    public void setEmail(String mEmail) {
        this.mEmail = mEmail;
    }

    public String getPassword() {
        return mPassword;
    }

    public void setPassword(String mPassword) {
        this.mPassword = mPassword;
    }

    public int isValidUser () {

        if (TextUtils.isEmpty(getEmail()) == true)
            return 0;
        else if (!Patterns.EMAIL_ADDRESS.matcher(getEmail()).matches())
            return 1;
        else if (TextUtils.isEmpty(getPassword()) == true)
            return 2;
        else if (getPassword().length() &lt; 6)
            return 3;
        else
            return -1;
    }
}
</code></pre>

<p>and this is my test class</p>

<pre><code>public class LoginViewModelTest {

    @Test
    public void isValidUser_Test() {

        User user = new User(""a.elsayed2010@gmail.com"", ""amira123"");
        int result = user.isValidUser();
        assertEquals(4, 2 + 2);
    }

}
</code></pre>

<p>Can anyone please tell me what the problem is?</p>

<p><strong>EDIT</strong></p>

<pre><code>@Test
    public void isValidUser_happyCase() {

        User user = new User(""a.elsayed2010@gmail.com"", ""amira123"");
        int result = user.isValidUser();
        assertEquals(-1, result);
    }

    @Test
    public void isValidUser_emptyEmail() {

        User user = new User("""", ""amira123"");
        int result = user.isValidUser();
        assertEquals(0, result);
    }

    @Test
    public void isValidUser_invalidEmail() {

        User user = new User(""aaaaaaa"", ""amira123"");
        int result = user.isValidUser();
        assertEquals(1, result);
    }

    @Test
    public void isValidUser_emptyPassword() {

        User user = new User(""a.elsayed2010@gmail.com"", """");
        int result = user.isValidUser();
        assertEquals(2, result);
    }

    @Test
    public void isValidUser_invalidPassword() {

        User user = new User(""a.elsayed2010@gmail.com"", ""111"");
        int result = user.isValidUser();
        assertEquals(3, result);
    }
</code></pre>
",https://stackoverflow.com/questions/50739736/unit-testing-in-android-studio-gives-an-error,"['android', 'unit-testing', 'android-studio', 'junit']",1627,TRUE,0,1
Error: Cannot instantiate interface symfony when unit testing,"<p>I'm trying to do a unit test for a signup method and im following this <a href=""https://symfony.com/doc/master/testing/database.html#mocking-the-repository-in-a-unit-test"" rel=""nofollow noreferrer"">guide</a>. I'm fairly new to unit testing. </p>

<p>i keep getting </p>

<blockquote>
  <p>1) App\Tests\Controller\SignUpControllerTest::testSignUp Error: Cannot
  instantiate interface
  Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface</p>
  
  <p>/Applications/MAMP/htdocs/my_project/tests/Controller/SignUpControllerTest.php:19</p>
</blockquote>

<p>I just don't think im doing this unit test right. Here is what i have. I'm not sure on what im doing. All i want to do is test the signup method. </p>

<p><strong>UserController.php</strong></p>

<pre><code>public function signup(Request $request, UserPasswordEncoderInterface $passwordEncoder )
{
    $user = new User();

    $entityManager = $this-&gt;getDoctrine()-&gt;getManager();

    $user-&gt;setEmail($request-&gt;get('email'));
    $user-&gt;setPlainPassword($request-&gt;get('password'));
    $user-&gt;setUsername($request-&gt;get('username'));
    $password = $passwordEncoder-&gt;encodePassword($user, $user-&gt;getPlainPassword());
    $user-&gt;setPassword($password);

    $entityManager-&gt;persist($user);
    $entityManager-&gt;flush();

    return $this-&gt;redirectToRoute('login');



}
</code></pre>

<p><strong>SignUpControllerTest.php</strong> </p>

<pre><code>namespace App\Tests\Controller;

use App\Entity\Product;
use App\Controller\UserController;
use App\Entity\User;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\Persistence\ObjectRepository;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

class SignUpControllerTest extends WebTestCase
{

    public function testSignUp()
    {   
        $passwordEncoder = new UserPasswordEncoderInterface();
        $user = new User();
        $user-&gt;setEmail('janedoe123@aol.com');
        $user-&gt;setPlainPassword('owlhunter');
        $user-&gt;setUsername('BarnMan');
        $password = $passwordEncoder-&gt;encodePassword($user, $user-&gt;getPlainPassword());
        $user-&gt;setPassword($password);

        $userRepository = $this-&gt;createMock(ObjectRepository::class);
        $userRepository-&gt;expects($this-&gt;any())
            -&gt;method('find')
            -&gt;willReturn($user);


        $objectManager = $this-&gt;createMock(ObjectManager::class);
        // use getMock() on PHPUnit 5.3 or below
        // $objectManager = $this-&gt;getMock(ObjectManager::class);
        $objectManager-&gt;expects($this-&gt;any())
            -&gt;method('getRepository')
            -&gt;willReturn($userRepository);

        $userController = new UserController($objectManager);
        $this-&gt;assertEquals(2100, $userController-&gt;signupTest());

    }


}
</code></pre>
",https://stackoverflow.com/questions/52011762/error-cannot-instantiate-interface-symfony-when-unit-testing,"['php', 'symfony']",4026,TRUE,0,2
Azure AD B2C get token programatically for unit testing,"<p>My scenario is simple I have a simple Azure Function with B2C authentication on it and I'm writing unit tests but I found an issue, I'm not able to authenticate to the azure functions programmatically. </p>

<p>I'm able to access through the browser and even I can grab the token and put it into the unit test and it works fine, but when I try to generate a token using the ClientID, TenantID, etc. I get a token, but 401 Unauthorized response on the Azure functions.</p>

<p><strong>Is there a way to generate a valid B2C token programmatically (without login in the browser?</strong></p>

<p>The approach I'm using so far:</p>

<pre><code>public static async  Task&lt;AuthenticationResult&gt; GetAccessToken(string resourceUri, string clientId, string clientSecret)
{
        ClientCredential clientCredential = new ClientCredential(clientId, clientSecret);

        string aadInstance = ""https://login.microsoftonline.com/"";
        string tenant = ""&lt;mytenant&gt;.onmicrosoft.com"";
        string authority = string.Concat(aadInstance, tenant);
        AuthenticationContext authContext = new AuthenticationContext(authority);

        return await authContext.AcquireTokenAsync(resourceUri, clientCredential);
}
</code></pre>

<p>I'm getting a token (EY.......) but is not valid, when I passed to the Azure Function request, it returns 401 Unauthorized. </p>

<p>Thanks in advance!
Ivan</p>
",https://stackoverflow.com/questions/49307985/azure-ad-b2c-get-token-programatically-for-unit-testing,"['c#', 'unit-testing', 'azure', 'azure-functions', 'azure-ad-b2c']",4204,TRUE,6,2
Unit Testing in XCode (Obj C) With MVVM,"<p>I'm testing out some MVVM pattern stuff and seem to have gotten myself confused. Hoping someone here can clarify things for me. </p>

<p>So, what I did was set up a project and added a class that is a subclass of NSObject and called it RootViewModel. </p>

<p>Gave it one method:</p>

<pre><code>- (void) rootTest {
    NSLog(@""Booyeah!"");
}
</code></pre>

<p>In ViewController I imported RootViewModel and made an IBOutlet for it. </p>

<pre><code>#import ""ViewController.h""
#import ""RootViewModel.h""

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIButton *btnRunModel;
@property IBOutlet RootViewModel* myModel;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.myModel rootTest];
}

@end
</code></pre>

<p>Then in Storyboard I dragged an Object into the ViewController scene, named it RootModel and connected it to the myModel property in ViewController. </p>

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

<p>Run the app and it works as expected, Booyeah gets logged. </p>

<p>So now here's where I got messed up. I wanted to set up a unit test. So working in the default unit test file I imported ViewController and made it a property and instantiated it in the set up. </p>

<pre><code>#import &lt;XCTest/XCTest.h&gt;
#import ""ViewController.h""

@interface ObjectiveVMMVTests : XCTestCase

@property (nonatomic, strong) ViewController* myViewController;

@end

@implementation ObjectiveVMMVTests

- (void)setUp {
    [super setUp];

    self.myViewController = [[ViewController alloc] init];
}
</code></pre>

<p>Then I tried to create a test where I call the rootTest method.</p>

<pre><code>- (void) testRootModel {

    [self.myViewController.myModel rootTest];
}
</code></pre>

<p>But I get a compiler error saying myViewController has no property myModel. I assumed it would be there, not sure where I messed this up.</p>
",https://stackoverflow.com/questions/51444761/unit-testing-in-xcode-obj-c-with-mvvm,"['objective-c', 'xcode', 'unit-testing', 'dependency-injection', 'viewmodel']",395,TRUE,0,2
Unit testing RxJava in MVP presenter in android,"<p>I am new to TDD. Also new to MVP and Rxjava. I just dive into it and It is worth it. But I stuck at the testing part. I understand the basis of unit testing. It is a little bit difficult for me in beginning. But I stuck here and So how can test the presenter?</p>

<p>Here is the Presenter class - </p>

<pre><code>public class NewsPresenter {

private final RxjavaService service;
private final MainView view;
private CompositeSubscription subscriptions;

public NewsPresenter(RxjavaService service, MainView view) {
    this.service = service;
    this.view = view;
    subscriptions = new CompositeSubscription();
}

public void getNewsList(String urlQ){
    view.showWait();

    Subscription subscription = service.getNews(urlQ ,new RxjavaService.GetNewsCallback() {
        @Override
        public void onSuccess(Articles articles) {
            view.removeWait();
            view.getNewsListSuccess(articles);
        }

        @Override
        public void onError(NetworkError networkError) {
            view.removeWait();
            view.onFailure(networkError.getAppErrorMessage());
            Log.i(""huh"",networkError.getMessage());
        }
    });

    subscriptions.add(subscription);
}

public void onStop(){
    subscriptions.unsubscribe();
}
</code></pre>

<p>}</p>

<p>Here is the View Interface -</p>

<pre><code>public interface MainView {

void showWait();

void removeWait();

void onFailure(String appErrorMessage);

void getNewsListSuccess(Articles articles);
</code></pre>

<p>}</p>

<p>Here is the RxJavaService class -</p>

<pre><code>public class RxjavaService {

private final NewsRestService newsRestService;

public RxjavaService(NewsRestService newsRestService) {
    this.newsRestService = newsRestService;
}


public interface GetNewsCallback {
    void onSuccess(Articles articles);

    void onError(NetworkError networkError);
}


public Subscription getNews(String q, final GetNewsCallback getNewsCallback) {
    Log.i(""stuck"",""service called"");
    return newsRestService.getNewsBySearch(q,""8dca7dea475e41e49518b2c61131e118"",100)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .onErrorResumeNext(new Func1&lt;Throwable, Observable&lt;? extends Articles&gt;&gt;() {
                @Override
                public Observable&lt;? extends Articles&gt; call(Throwable throwable) {
                    return Observable.error(throwable);
                }
            })
            .subscribe(new Subscriber&lt;Articles&gt;() {
                @Override
                public void onCompleted() {
                    Log.i(""stuck"",""complete"");
                }

                @Override
                public void onError(Throwable e) {
                    getNewsCallback.onError(new NetworkError(e));
                    Log.i(""stuck"",e.getMessage());
                }

                @Override
                public void onNext(Articles articles) {
                    getNewsCallback.onSuccess(articles);
                    Log.i(""stuck"",""Onnext"");
                }
            });
}
</code></pre>

<p>}</p>

<p>Here is the Test class where I am stuck-</p>

<pre><code>@RunWith(MockitoJUnitRunner.class)

public class NewsListTest {

private NewsPresenter newsPresenter;

@Mock
private RxjavaService rxjavaService;
@Mock
private MainView mainView;

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

    newsPresenter = new NewsPresenter(rxjavaService,mainView);
}

@After
public void tearDown() throws Exception {
    mainView = null;
    newsPresenter.onStop();
}

@Test
public void Testing_The_Result() {

}
</code></pre>

<p>}</p>
",https://stackoverflow.com/questions/49743749/unit-testing-rxjava-in-mvp-presenter-in-android,"['unit-testing', 'tdd', 'rx-java', 'integration-testing', 'rx-java2']",1130,TRUE,0,1
Unit testing RxJava + Retrofit call inside the method,"<p>The method I want to test contains of two calls to the retrofit service:</p>

<pre><code> internal fun poll(): Completable {
    return presenceService.askForFrequency(true).toObservable()
            .flatMap { it -&gt; Observable.interval(it.frequency, TimeUnit.SECONDS, Schedulers.io()) }
            .flatMapCompletable { _ -&gt; presenceService.sendHeartbeat() }
            .subscribeOn(Schedulers.io())
            .retry()
}
</code></pre>

<p>The <code>presenceService</code> is injected in the class, so I provide the mocked one for the test:</p>

<pre><code>val frequency = PublishSubject.create&lt;Presence&gt;()
val heartbeat = PublishSubject.create&lt;Unit&gt;()
val mockPresenceService = mock&lt;PresenceService&gt; {
    on { askForFrequency(any()) } doReturn frequency
    on { sendHeartbeat() } doReturn heartbeat
}
</code></pre>

<p>The test, that checks that <code>askForFrequency</code> method is called works correctly, but test that checks that the polling request is sent never works:</p>

<pre><code>@Test
fun presenceService_sentHeartbeat() {
    RxJavaPlugins.setIoSchedulerHandler { scheduler }

    frequency.onNext(Presence(1)) //polls with 1s interval
    heartbeat.onNext(Unit)
    presenceMaintainer.onActivityResumed(any())
    scheduler.advanceTimeBy(2, TimeUnit.SECONDS)
    verify(mockPresenceService).askForFrequency(true) //works correctly
    verify(mockPresenceService).sendHeartbeat() //never works
}
</code></pre>

<p>The logs from the unit test run are:</p>

<pre><code>Wanted but not invoked:
presenceService.sendHeartbeat();

However, there was exactly 1 interaction with this mock:
presenceService.askForFrequency(true);
</code></pre>

<p>The question is: <strong>how to test that the second method (<code>sendHeartbeat</code>) is also called (possibly several times)</strong>? </p>

<p>Meanwhile I found out that the problem lies in the second flatmap, because the test for this method works correctly (verifies that method was called 60 times):  </p>

<pre><code> internal fun pollTest(): Observable&lt;Presence&gt; {
    return Observable.interval(1, TimeUnit.SECONDS, Schedulers.io())
            .subscribeOn(Schedulers.io())
            .flatMap { it -&gt; presenceService.askForFrequency(true).toObservable() }
}

@Test
fun presenceService_sentHeartbeat() {
    frequency.onNext(Presence(1))
    val result = arrayListOf&lt;Unit&gt;()
    presenceMaintainer.pollTest().subscribe({ t -&gt; result.add(Unit) })
    Thread.sleep(60*1000)
    println(result.size)
    verify(mockPresenceService, Times(60)).askForFrequency(true)
}
</code></pre>

<p>But when I change the order of the calls to <code>askForFrequency -&gt; map to interval -&gt; map each tick to poll call</code>, test stops working and mock is called only once. </p>
",https://stackoverflow.com/questions/48707080/unit-testing-rxjava-retrofit-call-inside-the-method,"['android', 'unit-testing', 'mockito', 'retrofit2', 'rx-java2']",374,TRUE,0,1
Flask-Reatful unit testing response 404 Not Found,"<p>I use Flask-Reatful to build Flask Restful. But when I did a unit test, I was able to get the hello response, and the login returned a response of 404.</p>

<p>Am I doing something wrong?</p>

<p>Code:
 <a href=""https://gist.github.com/LuGuoHuas/3578cf0c8681638afb288b5d796760a4"" rel=""nofollow noreferrer"">https://gist.github.com/LuGuoHuas/3578cf0c8681638afb288b5d796760a4</a></p>
",https://stackoverflow.com/questions/50751972/flask-reatful-unit-testing-response-404-not-found,"['python', 'flask', 'python-3.6', 'flask-restful']",541,FALSE,-1,1
Mock boto3 batch write for unit testing in python,"<p>I would like to test the batch_write method using unit test. </p>

<pre><code>class DataService:
    def __init__(self, table):
        dynamodb = boto3.resource('dynamodb', region_name='us-west-2')
        self.db = dynamodb.Table(self.table)


    def batch_write(self, items):
        with self.db.batch_writer() as batch:
            for item in items:
                batch.put_item(Item=item)
</code></pre>

<p>I want to mock the batch_writer(). I have seen usage of  mock_open used to mock file open methods. But I don't really understand can i mock this streaming batch_writer() call.</p>
",https://stackoverflow.com/questions/51551417/mock-boto3-batch-write-for-unit-testing-in-python,"['python', 'unit-testing', 'mocking', 'boto3']",2099,TRUE,5,2
Spock unit testing assert log calls and see output,"<p>I am using spock to test Java Spring Boot code. It gets a logback logger over the lombok @Slf4j annotation.</p>

<p><strong>Dummy class</strong> with log call</p>

<pre><code>import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class Clazz {

  public void method() {
    // ... code
    log.warn(""message"", new RuntimeException());
  }
}
</code></pre>

<p><strong>The Spock Spec</strong></p>

<pre><code>import groovy.util.logging.Slf4j
import org.junit.Rule
import org.slf4j.Logger
import spock.lang.Specification

@Slf4j
class LogSpec extends Specification {

  Clazz clazz = new Clazz()

  private Logger logger = Mock(Logger.class)

  @Rule
  ReplaceSlf4jLogger replaceSlf4jLogger = new ReplaceSlf4jLogger(Clazz, logger)

  def ""warning ia logged""() {

    given: ""expected message""

    when: ""when calling the method""
    clazz.method()

    then: ""a warning is logged""
    1 * logger.warn(_, _) &gt;&gt; {
      msg, ex -&gt; log.warn(msg, ex)
    }
  }
}
</code></pre>

<p><strong>Helper</strong> to switch the real with the mock logger taken from <a href=""https://stackoverflow.com/a/25031713/3573038"">this answer</a>.</p>

<pre><code>import org.junit.rules.ExternalResource
import org.slf4j.Logger

import java.lang.reflect.Field
import java.lang.reflect.Modifier

/**
 *  Helper to exchange loggers set by lombok with mock logger
 *
 * allows to assert log action.
 *
 * Undos change after test to keep normal logging in other tests.
 *
 * code from this  &lt;a href=""https://stackoverflow.com/a/25031713/3573038""&gt;answer&lt;/a&gt; answer
 */
class ReplaceSlf4jLogger extends ExternalResource {
  Field logField
  Logger logger
  Logger originalLogger

  ReplaceSlf4jLogger(Class logClass, Logger logger) {
    logField = logClass.getDeclaredField(""log"")
    this.logger = logger
  }

  @Override
  protected void before() throws Throwable {
    logField.accessible = true

    Field modifiersField = Field.getDeclaredField(""modifiers"")
    modifiersField.accessible = true
    modifiersField.setInt(logField, logField.getModifiers() &amp; ~Modifier.FINAL)

    originalLogger = (Logger) logField.get(null)
    logField.set(null, logger)
  }

  @Override
  protected void after() {
    logField.set(null, originalLogger)
  }
}
</code></pre>

<p><strong>I would like to test log calls, but still see the log message.</strong></p>

<p>I am using the solution from <a href=""https://stackoverflow.com/a/25031713/3573038"">this answer</a>, it works for the assertion but I don't see the log because it is a mock call.</p>

<p>I came up with this solution, which does a the call with the logger of the groovy spec.</p>

<pre><code> 1 * logger.warn(_ , _) &gt;&gt; {
   msg, ex -&gt; log.warn(msg, ex)
 }
</code></pre>

<p>But I find it verbose, any idea how I could create a helper function for it. I am not very familiar with functional groovy and moving this code into a function is not working.</p>

<p>I also tried a Spy instead of a Mock but that gets me an error because the logger class is final.</p>

<pre><code>  import ch.qos.logback.classic.Logger  

  private Logger logger = Spy(Logger.class)

&gt;&gt; org.spockframework.mock.CannotCreateMockException: Cannot create mock 
for class ch.qos.logback.classic.Logger because Java mocks cannot mock final classes. 
If the code under test is written in Groovy, use a Groovy mock.
</code></pre>

<p>Logger class at runtime</p>

<pre><code>package ch.qos.logback.classic;

public final class Logger implements org.slf4j.Logger, LocationAwareLogger, AppenderAttachable&lt;ILoggingEvent&gt;, Serializable {
</code></pre>

<p>Thanks</p>
",https://stackoverflow.com/questions/49771913/spock-unit-testing-assert-log-calls-and-see-output,"['unit-testing', 'logging', 'groovy', 'functional-programming', 'spock']",8605,TRUE,5,2
Unit testing error: java.util.NoSuchElementException: No value present at java.util.Optional.get,"<p>I'm trying to implement unit testing of my Object service below:</p>

<pre><code>@Service
public class ObjectServiceImpl implements ObjectService{

  private final ObjectDao objectDao;

  @Autowired
  public ObjectServiceImpl(ObjectDao objectDao){
    this.objectDao = objectDao;
  }

  @Override
    public Object getById(Long ObjectId) throws RecordNotFoundException {
        Optional&lt;Object&gt; Object = ObjectDao.findById(ObjectId);
        if (!Object.isPresent()) {
            throw new RecordNotFoundException(String.format(
                    MessageConstants.ObjectID_NOT_FOUND, ObjectId));
        }
        return Object.get(); 
    }
</code></pre>

<p>However I get an error: <code>No value present at java.util.Optional.get</code> when I tried to implement my JUnit below:</p>

<pre><code>@RunWith(MockitoJUnitRunner.Silent.class)
public class ObjectServiceTest {

    @InjectMocks
    private ObjectServiceImpl objectServiceImpl;

    @Mock
    private ObjectDao objectDao;

    private ObjectService objectService;

    @Test
    public void getById() throws RecordNotFoundException{
        Object object = new Object();
        Long objectId = 1L;
        Optional&lt;Object&gt; objectList =
            objectDao.findById(objectId);
        given(objectDao.findById(
                    objectList.get().getId())).willReturn(objectList);
        objectServiceImpl.getById(Mockito.anyLong());
        Mockito.verify(objectDao).findById(objectId);
        assertNotNull(objectServiceImpl.getById(objectId));
    }
}
</code></pre>

<p>Is there anything that I missed or that I need to update?</p>
",https://stackoverflow.com/questions/50716941/unit-testing-error-java-util-nosuchelementexception-no-value-present-at-java-u,"['java', 'spring', 'junit', 'mockito', 'option-type']",11302,TRUE,4,2
Unit testing Laravel password reset email - mailable not queued,"<p>I am using the auth that came with Laravel. I am testing the page where you put in your email and when you hit the submit button a password reset email will be sent to your email.</p>
<p>The password reset email is sent when I do it manually. But I created this test to make sure the password reset email is sent but it's not working.</p>
<blockquote>
<p>There was 1 failure:</p>
<p>1)
The expected [Illuminate\Foundation\Auth\ResetPassword] mailable was not queued.
Failed asserting that false is true.</p>
</blockquote>
<p>I am following this code:</p>
<p><a href=""https://github.com/JeffreyWay/council/blob/master/tests/Feature/Auth/RegisterUserTest.php"" rel=""nofollow noreferrer"">https://github.com/JeffreyWay/council/blob/master/tests/Feature/Auth/RegisterUserTest.php</a></p>
<pre><code>&lt;?php

namespace Tests\Controllers\Unit;

use Tests\TestCase;
use Illuminate\Support\Facades\Mail;
use Illuminate\Auth\Notifications\ResetPassword;
use Illuminate\Foundation\Testing\RefreshDatabase;

class ResetPasswordEmailTest extends TestCase
{

    use RefreshDatabase;


    public function setUp()
    {
        parent::setUp();
        
        Mail::fake();
    }


    /** @test */
    public function does_send_password_reset_email()
    {
        $user = factory('App\User')-&gt;create();

        $this-&gt;post(route('password.email'), ['email' =&gt; $user-&gt;email])
             
        Mail::assertQueued(ResetPassword::class);
    }

}
</code></pre>
",https://stackoverflow.com/questions/50383016/unit-testing-laravel-password-reset-email-mailable-not-queued,"['php', 'laravel', 'unit-testing', 'laravel-5', 'phpunit']",2441,TRUE,4,1
LiveData unit testing error when using postValue in init block,"<p>I'm trying to write a unit test for a view model using live data.</p>

<p><strong>LoginViewModel.kt</strong></p>

<pre><code>class LoginViewModel @Inject constructor(
    val context: Context
): ViewModel() {
    val username = MutableLiveData&lt;String&gt;()
    val password = MutableLiveData&lt;String&gt;()
    val isLoginButtonEnabled = MediatorLiveData&lt;Boolean&gt;().apply {
        fun combineLatest(): Boolean {
            return !(username.value.isNullOrEmpty() || password.value.isNullOrEmpty())
        }
        addSource(username) { this.value = combineLatest() }
        addSource(password) { this.value = combineLatest() }
    }

    init {
        username.postValue(""test"")
        password.postValue(""test"")
    }
}
</code></pre>

<p><strong>LoginViewModelTest.kt</strong></p>

<pre><code>@RunWith(MockitoJUnitRunner::class)
class LoginViewModelTest {
    @Rule
    @JvmField
    val instantTaskExecutorRole = InstantTaskExecutorRule()

    private val context = mock(Context::class.java)
    private val loginViewModel = LoginViewModel(context)

    @Test
    fun loginButtonDisabledOnEmptyUsername() {
        val observer = mock&lt;Observer&lt;Boolean&gt;&gt;()
        loginViewModel.isLoginButtonEnabled.observeForever(observer)
        loginViewModel.username.postValue("""")

        verify(observer).onChanged(false)
    }
}
</code></pre>

<p>My unit test throws the following exception at the line <code>username.postValue(""test"")</code>:</p>

<pre><code>java.lang.RuntimeException: Method getMainLooper in android.os.Looper not mocked. See http://g.co/androidstudio/not-mocked for details.
</code></pre>

<p>The <code>InstantTaskExecutorRule</code> should provide an execution context when using live data, however it doesn't work when initializing live data in the <code>init</code>-block. When omitting the <code>init</code>-block it works as desired, but i need the possibility to initialize live data variables.</p>

<p>Is there any way to make the live data initialization work when unit testing view models?</p>
",https://stackoverflow.com/questions/52762418/livedata-unit-testing-error-when-using-postvalue-in-init-block,"['android', 'kotlin', 'android-architecture-components', 'android-livedata', 'android-viewmodel']",7755,TRUE,10,3
Django Unit Testing in Visual Studio 2017 or 2019:,"<p>Django needs setup code so unit tests on models that need a database will work. Standard Django unit test do that silently in the background but not with Visual Studio. I have not found a good way to provide setup code that will work for starting test runs from both the Visual Studio Test Explorer and with <code>django manage.py test</code>. Visual Studio Test Explorer does not call setUpModule/tearDownModule nor tearDownClass. The following code works from within VS, but I find it ugly, AND it doesn't work with nose/django-nose: </p>

<pre><code>import os
import django
import unittest
from django.test.utils import setup_test_environment, teardown_test_environment
from django.test.utils import setup_databases, teardown_databases

try:
    os.environ[""DJANGO_SETTINGS_MODULE""] = ""config.settings.test""
    setup_test_environment()
    print(""Called setup_test_environment()"")
    django.setup()
    old_config=setup_databases(1,False)
except:
    old_config=None

def tearDownModule():
    try:
        global old_config
        if old_config:
            teardown_test_environment()
            print(""Called teardown_test_environment()"")
            teardown_databases(old_config,1,False)
    except:
        pass

from unittest import TestCase # This needs to be called after django.setup 
from konsenser.models import Poll   

class PollTest(TestCase):

    @classmethod
    def setUpClass(cls):
        print(""Setting up class"")
        return super().setUpClass()

    @classmethod
    def tearDownClass(cls):
        print(""Tearing down class"")
        return super().setUpClass()


    def setUp(self):
        Poll.objects.create(name='Test Poll', description='for testing')

    def test_content(self):
        poll=Poll.objects.get(id=1)
        name=f'{poll.name}'
        description=f'{poll.description}'
        self.assertDictEqual({'name':name,'description':description },
                             {'name':'Test Poll','description':'for testing'})


if __name__ == '__main__':
    unittest.main()
</code></pre>

<p>When run by VS Test Explorer, the output is </p>

<pre><code>Called setup_test_environment()
Creating test database for alias 'default'...
Setting up class
</code></pre>

<p>So it doesn't tear down via my functions/methods. I cannot stick django.setup() into setUpClass because the model import needs django setup already. I wouldn't want to either because I want to create the test database just once and not repeatedly for all test classes.</p>

<p>Anbody any insight? I can't help but thinking I am doing this completely wrong...</p>
",https://stackoverflow.com/questions/53678954/django-unit-testing-in-visual-studio-2017-or-2019,"['python', 'django', 'visual-studio-2017', 'django-unittest', 'visual-studio-2019']",568,FALSE,4,0
Unit Testing Angular 5 scroll event triggers after whenStable,"<p>I have not been able to find out why this test does not work. Given my sample code below. When I am unit testing changes made when scrolling a child DIV element in a component. The event handler triggers as expected but the async\whenStable does not wait for the Zone task to complete, and the task triggers when the test is complete.</p>

<p>I have tried assigning the event with Renderer2.listen with exactly the same result.</p>

<p><strong>App.Component.ts</strong></p>

<pre><code>import { Component, Renderer2, ViewChild } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  @ViewChild('message') messageBox: HTMLDivElement;
  constructor(private renderer: Renderer2) {}

  onScroll() {
     this.renderer.setStyle(this.messageBox, 'color', 'blue');
  }
}
</code></pre>

<p><strong>App.Component.html</strong></p>

<pre><code>&lt;div class=""scrollWindow"" (scroll)=""onScroll($event)""&gt;
  &lt;div class=""scrollContent""&gt;Bacon ipsum dolor amet short ribs jowl ball tip turkey sirloin meatloaf ground round capicola pork belly pork chop doner
    flank brisket boudin. Pork chop sausage alcatra meatloaf pork belly meatball bacon tongue tenderloin pastrami hamburger
    pork ribeye andouille biltong. Doner bresaola biltong chicken cupim ham. Beef ribs drumstick ground round bresaola prosciutto
    andouille, pork belly beef flank. Bacon beef cupim turkey, buffalo sausage ham tongue rump ground round doner swine pastrami
    chuck.
  &lt;/div&gt;
&lt;/div&gt;
&lt;p #message&gt;This is a message&lt;/p&gt;
</code></pre>

<p><strong>App.Component.css</strong></p>

<pre><code>.scrollWindow {
  position: relative;
  width: 100px;
  height: 100px;
  overflow: auto;
}

.scrollContent {
  position: relative;
  width: 200px;
  height: 200px;
  background-color: aquamarine;
}
</code></pre>

<p><strong>App.Component.spec.ts</strong></p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { By } from '@angular/platform-browser';

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('should create the app', async(() =&gt; {
    const container = fixture.debugElement.query(By.css('.scrollWindow'));

    container.nativeElement.scrollLeft = 50;
    expect(container.nativeElement.scrollLeft).toEqual(50);

    container.nativeElement.scroll();
    fixture.detectChanges();

    fixture.whenStable().then(() =&gt; {
      const message = fixture.debugElement.query(By.css('p'));
      expect(message.styles.color).toEqual('blue');
    });
  }));
});
</code></pre>
",https://stackoverflow.com/questions/50264090/unit-testing-angular-5-scroll-event-triggers-after-whenstable,"['angular', 'unit-testing', 'scroll', 'dom-events']",10077,TRUE,3,2
Unit testing a value passed to a static method,"<p>Example code:</p>

<pre><code>class MyClass {
    public void myMethod(Request request) {
        Item item = getItem();
        ItemUtilHelper.setCertainProperties(newProperty, item);
        differentClass.staticMethod(item);
    }
}
</code></pre>

<p>The <code>ItemUtilHelper</code> already has a unit test class to verify item gets properly updated.</p>

<p>How would I go about unit testing that <code>differentClass.staticMethod</code> gets called with an updated <code>item</code> parameter?</p>
",https://stackoverflow.com/questions/50892214/unit-testing-a-value-passed-to-a-static-method,"['java', 'unit-testing', 'mockito', 'static-methods']",1321,TRUE,3,3
Swift4 unit testing: ViewController not found when type casting,"<p>I am currently writing test on a <code>MyViewController</code> class with the following code:</p>

<pre><code>let viewController = UIStoryboard(name: ""Main"", bundle: Bundle.main).instantiateViewController(withIdentifier: ""MyViewController"")
XCTAssertNotNil(viewController.view)
XCTAssertNotNil(viewController as? MyViewController)
</code></pre>

<p>This test does not work, the second assert always fails. When I debug, I can see my <code>viewController</code> has the correct type, but it looks like the type casting is always failing.</p>

<pre><code>(lldb) po viewController

MyProject.MyViewController: 0x7f900c835600

(lldb) po viewController as? MyViewController

nil
</code></pre>

<p>The code of <code>MyViewController</code> and the storyboard are correctly included inside the Test project. There is also Cocoapods included.</p>

<p>I tested on an empty project and the issue remains present.</p>

<p>Does anyone has the same issue? Am I missing something?</p>

<p><strong>Edit</strong>. I change the code to this:</p>

<pre><code>let viewController = UIStoryboard(name: ""Main"", bundle: Bundle.main).instantiateViewController(withIdentifier: ""MyViewController"") as? MyViewController
XCTAssertNotNil(viewController)
</code></pre>

<p>But the issue is still present.</p>
",https://stackoverflow.com/questions/48788994/swift4-unit-testing-viewcontroller-not-found-when-type-casting,"['ios', 'swift', 'unit-testing', 'swift4']",240,TRUE,3,2
How to Mock Elasticsearch NEST&#39;s IGetMappingResponse for Unit Testing,"<p>Myself and my colleges have built a data access module which does CRUD and search operations to a ElasticeSearch(6.2.0) NoSQL database.  We are using NEST(6.2.0), a high level client to map to the Elasticsearch query DSL.  The module has been coded in C#, in a class library in a targeted framework .NET Standard 2.0.</p>

<p>In some methods it is necessary to retrieve the index mapping of indices stored in ElasticSearch so that field information such as field types and text properties can be used to build search queries to the Elasticsearch database.  We are able to do this by using Nest’s GetMapping method (returns Nest.IGetMappingResponse).</p>

<p>We are not having issues executing code.  Everything works fine.  However, when we go to build a Unit Test for methods that uses the GetMapping method, we are not able to mock up the response it returns (IGetMappingResponse). I originally used FakeItEasy to fake it, and then inserted some of the data I needed in the object.  However, to explain my issue a little better, I have created a class that implements IGetMappingResponse to mock my response.  The problem comes when I try to create an instance of <strong>TypeMappings</strong> for the Mapping property of IndexMapping (In return is for property Indices for the mock).  I Get an error saying <strong>“’TypMappings’ does not contain a constructor that takes 0 arguments.</strong></p>

<pre class=""lang-cs prettyprint-override""><code>public class MockedGetMappingResponse : IGetMappingResponse
{
    public IReadOnlyDictionary&lt;IndexName, IndexMappings&gt; Indices
    {
        get
        {
            return new ReadOnlyDictionary&lt;Nest.IndexName, Nest.IndexMappings&gt;(new Dictionary&lt;Nest.IndexName, Nest.IndexMappings&gt;
                {
                    [""statuses""] = new IndexMappings
                    {
                        Mappings = new TypeMappings() //Error happens here!!
                    }                      

                });
        }
        set { }
    }

    public IReadOnlyDictionary&lt;IndexName, IndexMappings&gt; Mappings
    {
        get { return null; }
        set { }
    }

    public void Accept(IMappingVisitor visitor)
    {
        // Just a test
    }

    public bool IsValid
    {
        get { return true; }
    }

    public ServerError ServerError
    {
        get { return null; }
    }

    public Exception OriginalException
    {
        get { return null; }
    }

    public string DebugInformation
    {
        get { return """"; }
    }

    public IApiCallDetails ApiCall
    {
        get { return null; }
        set { //do nothing }
    }

    public bool TryGetServerErrorReason(out string reason)
    {
        reason = """";
        return false;
    }
}      
</code></pre>

<p>When I look up the definitions for the Nest type <strong>TypeMappings</strong> I don’t see a constructor built.  Therefore, I assume that it should be using the default, a constructor with no arguments.  But apparently it doesn’t.  I need to know how to go about mocking TypeMappings in IGetMappingResponse. If there is no way of creating an instance of TypeMappings, I need to know how to create a mocked IGetMappingResponse to my expected response so that I can test my code.</p>
",https://stackoverflow.com/questions/53505548/how-to-mock-elasticsearch-nests-igetmappingresponse-for-unit-testing,"['c#', 'unit-testing', 'elasticsearch', 'nest']",1869,TRUE,3,1
Unit testing async rendering in ReactJS component with Jest,"<p>I have a react component (16.2):</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 externalLibrary from 'wherever';

class MyComponent extends React.Component {
    componentDidMount() {
      externalLibrary.doStuff().then((data) =&gt; {
        this.setState({ ...this.state,
          data: data
        });
      });
    }

    render() {
        return ( 
          &lt;div&gt; 
            {this.state.data.map((d) =&gt; &lt;SubComponent key={d.id}
              data={d} /&gt;)} 
          &lt;/div&gt;
        );
    }
}</code></pre>
</div>
</div>
</p>

<p>I want to unit test this (using Jest), lets say I want to write a test that checks that checks that a ""SubComponent"" is rendered for each item in the array ""data"". How can I do this? All of React's code samples for async code assume I want to test the async code, but in this case I want to test that it rendered correctly. You can assume that ""externalLibrary"" is mocked correctly, and we know doStuff() will resolve a data array with three items in it. How do I tell the Jest code to wait until the promise inside componentDidMount (doStuff()) resolves, then check the rendered component and count the elements?</p>

<p>(I'm using Enzyme too if that changes anything)</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 { shallow } from 'enzyme';
import MyComponent from './MyComponent';
import SubComponent from './SubComponent';

describe(""&lt;MyComponent /&gt;"", () =&gt; {
  it(""Renders the correct number of SubComponents"", done =&gt; {
    wrapper = shallow(&lt;MyComponent /&gt;);
    // This fails because it runs before the subcomponents are rendered
    expect(wrapper.find(SubComponent)).toHaveLength(3);
  });
});</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/48693714/unit-testing-async-rendering-in-reactjs-component-with-jest,"['reactjs', 'jestjs']",634,FALSE,3,1
NullInjectorError: No provider for HttpClient! Unit Testing a service,"<p>I have been trying to unit test a basic service today and I keep getting this error: 
<code>Error: StaticInjectorError[HttpClient]: 
  StaticInjectorError[HttpClient]: 
    NullInjectorError: No provider for HttpClient! ""Error: StaticInjectorError"".</code> </p>

<p>I have been searching SO and Google for answers and all I find is people suggesting to add HttpClient to your import section of your test bed.</p>

<p>When I add HttpClient to the import section of my test bed I get this error: <code>Error: Unexpected value 'HttpClient' imported by the module 'DynamicTestModule'. Please add a @NgModule annotation.</code></p>

<p>Here is my code below</p>

<p>Unit Test File:</p>

<pre><code>import { VisitsIngestedService } from '../../../xxxx.App/src/app/Services/GetVisitsIngestedService';
import { HttpModule, BaseRequestOptions } from '../../../xxxx.App/node_modules/@angular/http';
import { MockBackend } from '@angular/http/testing';
import { JsonpModule } from '@angular/http';
import { Jsonp } from '@angular/http';
import { TestBed, getTestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { HttpClient } from '@angular/common/http';


describe('VisitsIngestedService', () =&gt; {
  let injector: TestBed;
  let service: VisitsIngestedService;
  let httpMock: HttpTestingController;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [VisitsIngestedService]
    });
    injector = getTestBed();
    service = injector.get(VisitsIngestedService);
    httpMock = injector.get(HttpTestingController);
  });

  describe('#getVisits', () =&gt; {
    it('should return an Observable&lt;Vists[]&gt;', () =&gt; {
      const dummyVisits = [
        { login: 'John' },
        { login: 'Doe' }
      ];

      service.getVisitsIngested(""faketen"", ""fakedate1"", ""fakedate2"").subscribe(visits =&gt; {
        expect(visits.length).toBe(2);
        expect(visits).toEqual(dummyVisits);
      });
    });
  });
});
</code></pre>

<p>Service File:</p>

<pre><code>import { Injectable } from '@angular/core';
import { Visit } from '../Models/Visit';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { HttpClient, HttpParams } from '@angular/common/http';


@Injectable()
export class VisitsIngestedService {

  constructor(private _httpService: HttpClient) { }

  public getVisitsIngested(tenant: string, start: string, end: string): Observable&lt;any&gt; {
    return this._httpService.get('/api/appInsights/query/' + tenant + '/' + start + '/' + end);
  }

}
</code></pre>

<p>App.module.ts file:</p>

<pre><code>import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HttpClient } from '@angular/common/http';
import { VisitsIngestedService } from '../../../../CloudMedOps.App/src/app/Services/GetVisitsIngestedService';



@NgModule({
  imports: [BrowserModule, FormsModule, MatFormFieldModule, MatInputModule, BrowserAnimationsModule, HttpClient],
  providers: [VisitsIngestedService, HttpClient],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }
</code></pre>

<p>I am new to Angular and would appriciate any help. Thanks!</p>
",https://stackoverflow.com/questions/49890001/nullinjectorerror-no-provider-for-httpclient-unit-testing-a-service,"['angular', 'unit-testing', 'karma-jasmine']",8802,TRUE,3,1
How to avoid race conditions with PHP Unit testing,"<p>Let's start from the <em>proof</em> that it's a race condition I'm facing here:</p>

<h1>Failed Test Case ❌</h1>

<pre><code>phpunit --filter testMethod testlass path/to/testFile.php
PHPUnit 5.7.26 by Sebastian Bergmann and contributors.

F                                                                   1 / 1 (100%)

You should really fix these slow tests (&gt;500ms)...
 1. 6441ms to run testClass::testMethod


Time: 6.49 seconds, Memory: 22.00MB

There was 1 failure:

1) ≈
Unable to find row in database table [orders] that matched attributes 
[{""collect_cash"":104,""id"":1728,""final_total"":100}].
Failed asserting that 0 is greater than 0.

project/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithDatabase.php:24
path/to/testFile.php:78

FAILURES!
Tests: 1, Assertions: 2, Failures: 1.
</code></pre>

<p>here is the same test running and succeeding, <em>without</em> any code changes:</p>

<h1>Successful Test Case ✅</h1>

<pre><code>$ phpunit --filter method class path/to/testFile.php
PHPUnit 5.7.26 by Sebastian Bergmann and contributors.

.                                                                   1 / 1 (100%)

You should really fix these slow tests (&gt;500ms)...
 1. 1631ms to run testClass::testMethod

Time: 1.68 seconds, Memory: 22.00MB
</code></pre>

<h1>Where the failure is happening 🤔</h1>

<p>the failure happens where where it's checking for a database record:</p>

<pre><code>    $this-&gt;shopperPut(""/some/api/call"")
        -&gt;seeApiSuccess();

    $this-&gt;seeInDatabase('orders', [
        'collect_cash'  =&gt; $order-&gt;final_total + $chargeFare,
        'id'            =&gt; $order-&gt;id,
        'final_total'   =&gt; $order-&gt;final_total,
</code></pre>

<p>inside the <code>/some/api/call</code> we do this</p>

<pre><code>    .. some logic

    $order-&gt;save();

    .. more logic

    return response()-&gt;success(compact('order'));
</code></pre>

<h1>What I have tried</h1>

<p>I have tried putting sleep commands.. but that's hacky, slows down the tests, and most importantly doesn't always work. </p>

<p>What else can I do?</p>

<p>note: this question isn't about many developers using the same database.. This is strictly on my localhost and in fact I'm using a testDatabase that's specifically made for unit tests.</p>
",https://stackoverflow.com/questions/48403252/how-to-avoid-race-conditions-with-php-unit-testing,"['php', 'laravel', 'testing', 'laravel-5', 'phpunit']",1022,FALSE,3,1
How to test boost logger output in unit testing?,"<p>My application uses <code>BOOST_LOG_TRIVIAL</code> to log messages. I thought it's good to check in test (gtest) that correct messages are written there in given scenarios.</p>

<p>Is there a way to somehow access what was written there after code was called? Or does it first have to be mocked in some way?</p>

<p>I have googled a lot for this and haven't found any instructions, so either I am asking wrong questions or no one thinks it should be done.</p>
",https://stackoverflow.com/questions/53372078/how-to-test-boost-logger-output-in-unit-testing,"['c++', 'logging', 'boost', 'googletest', 'boost-log']",2576,TRUE,3,2
Unit testing for property which has sytem.DateTime value C#,"<p>How to write unit testing for following code block where the </p>

<pre><code>public class Hotel
{
    DateTime CLOSING_TIME // imported from somewhere else
    public bool IsOpen
    {
        get
        {
            return DateTime.Now &lt;= CLOSING_TIME
        }
    }
}
</code></pre>

<p>I tried following either one will fail all the time, how can i make sure that both unit test case will pass every time:</p>

<pre><code>[TestFixture]
public void ShouldBeOpen()
{
    var Hot= new Hotel();
    Assert.True(Hot.IsOpen); 
}

[TestFixture]
public void ShouldBeOpen()
{
    var Hot= new Hotel();
    Assert.False(Hot.IsOpen); 
}
</code></pre>

<p>Can someone please help?</p>
",https://stackoverflow.com/questions/51539115/unit-testing-for-property-which-has-sytem-datetime-value-c,"['c#', 'vs-unit-testing-framework']",613,TRUE,3,2
Swift unit-testing: simple object conforming to Decoder protocol,"<p>I'm writing unit test for something that has a required initializer that takes a <code>Decoder</code> as parameter, the decoder isn't used in my test and the object is also only a dummy placeholder for something else, however I need to provide some instance that conforms to <code>Decoder</code> protocol, I checked <code>JSONDecoder</code> but it doesn't conform to the protocol, then I thought about creating a lightweight class that conforms to <code>Decoder</code> and basically has empty protocol methods / properties. Now, having to implement functions like:</p>

<pre><code>func container&lt;Key&gt;(keyedBy type: Key.Type) throws -&gt; KeyedDecodingContainer&lt;Key&gt; where Key : CodingKey

func singleValueContainer() throws -&gt; SingleValueDecodingContainer

func unkeyedContainer() throws -&gt; UnkeyedDecodingContainer
</code></pre>

<p>feels to me like an overkill since I still have to construct objects to return, is there any existing/native class that conforms to <code>Decoder</code> so I can use as a dummy object for unit test?</p>

<p>Thanks!</p>

<p>Edit:
The reason for using this, is that I have an object (the one with initializer takes a <code>Decoder</code>, say ObjA), the object itself is a non-nil property of another object (say ObjB) and the unit test is to do with the other object, as a result I need a dummy ObjA which need a decoder to initialize.</p>
",https://stackoverflow.com/questions/49215767/swift-unit-testing-simple-object-conforming-to-decoder-protocol,"['swift', 'unit-testing', 'mocking', 'decoder']",801,FALSE,2,0
Django unit testing: How should one test abstract models?,"<p>In my Django Project I have an app called 'core' which contains all my reusable model mixins / abstract models (behaviors.py), models (models.py), views (views.py) and helpers functions (utils.py):</p>

<pre><code>core/
    __init__.py
    behaviors.py  
    models.py
    utils.py
    views.py
</code></pre>

<p>I now want to write tests for these files. For models, utils and views I just wrote unit tests like I'm used to. </p>

<p>I'm now uncertain how I should test the abstract models contained in behaviors.py. For example, I have this model mixin:</p>

<pre class=""lang-py prettyprint-override""><code>import uuid as uuid_lib

from django.db import models


class UniversallyUniqueIdentifiable(models.Model):
    uuid = models.UUIDField(
    db_index=True,
    default=uuid_lib.uuid4,
    editable=False
        )

    class Meta:
        abstract = True
</code></pre>

<p>How can you test an abstract model?
In <a href=""http://blog.kevinastone.com/django-model-behaviors"" rel=""nofollow noreferrer"">one of the articles</a> I used to learn about fat models, the author just tests the models in which he used the abstract models. But that feels not very DRY to me since that would mean I would have to test the adding of the UUID in each model I use it in.
Is there a better way to do it?</p>
",https://stackoverflow.com/questions/50248330/django-unit-testing-how-should-one-test-abstract-models,"['django', 'unit-testing', 'django-models', 'django-testing', 'django-tests']",1812,TRUE,2,2
How to use Microsoft.Extensions.Configuration.IConiguration in my XUnit unit testing,"<p>In my Asp.net Core 2.0 application, I am trying to unit test my data service layer (.Net Standard Class Library) that uses the <em>Microsoft.Extensions.Configuration.IConfiguration</em> dependency injection. 
I am using XUnit and don't know how to pass <code>IConfiguration</code> from my unit test class. I tried the following implementation and getting the error</p>

<blockquote>
  <p>Message: The following constructor parameters did not have matching fixture data: IConfiguration configuration.</p>
</blockquote>

<p>I am really new to the testing frameworks and don't even know if dependency injection can be used as I am trying to do in my code snippet.</p>

<p>My Unit test class is as follow</p>



<pre class=""lang-cs prettyprint-override""><code>public class SqlRestaurantDataCLUnitTest
{
    private readonly IConfiguration configuration;
    public SqlRestaurantDataCLUnitTest(IConfiguration configuration)
    {
        this.configuration = configuration;
    }
    [Fact]
    public void AddTest()
    {
        var restaurantDataCL = new SqlRestaurantDataCL(configuration);
        var restaurant = new Restaurant
        {
            Name = ""TestName"",
            Cuisine = CuisineType.None
        };

        var result = restaurantDataCL.Add(restaurant);

        Assert.IsNotType(null, result.Id);    
    }
}
</code></pre>

<p>My data service layer is as follow</p>

<pre class=""lang-cs prettyprint-override""><code>public class SqlRestaurantDataCL : IRestaurantDataCL
{
    private readonly IConfiguration configuration;
    public SqlRestaurantDataCL(IConfiguration configuration)
    {
        this.configuration = configuration;
    }
    public Restaurant Add(Restaurant restaurant)
    {
        using (var db = GetConnection())
        {
            string insertSql = @""INSERT INTO [dbo].[RESTAURANTS]([Cuisine], [Name]) 
                                OUTPUT INSERTED.*
                                VALUES (@Cuisine, @Name)"";

            restaurant = db.QuerySingle&lt;Restaurant&gt;(insertSql, new
            {
                Cuisine = restaurant.Cuisine,
                Name = restaurant.Name
            });

            return restaurant;
        }
    }

    private IDbConnection GetConnection()
    {
        return new SqlConnection(configuration.GetSection(Connection.Name).Value.ToString());
    }
}

public class Connection
{
    public static string Name
    {
        get { return ""ConnectionStrings: OdeToFood""; }
    }
}
</code></pre>
",https://stackoverflow.com/questions/51403132/how-to-use-microsoft-extensions-configuration-iconiguration-in-my-xunit-unit-tes,"['unit-testing', 'asp.net-core-mvc', 'asp.net-core-2.0', 'xunit', 'xunit.net']",1669,TRUE,2,1
import error when unit testing flask application with nmslib,"<p>Hello I have unit test that are running fine when I run on console but when packaged with docker fail with the following error</p>

<pre><code>import nmslib
ImportError: dlopen: cannot load any more object with static TLS
</code></pre>

<p>I googled for this and they say to get rid of it you have to order your imports</p>

<p>I have tried all the possible orders but still get the error
I have the following imports </p>

<pre><code>import nmslib 
import numpy as np
import time, math_utils, os, urllib, tables, math
from math import cos, sin, acos, asin

from sklearn.neighbors import NearestNeighbors
from sklearn.neighbors import LSHForest
from sklearn.preprocessing import normalize
</code></pre>

<p>Any idea how to get rid of this error?</p>
",https://stackoverflow.com/questions/50398358/import-error-when-unit-testing-flask-application-with-nmslib,"['python', 'unit-testing', 'docker']",199,TRUE,2,1
Unit testing connected higher-order components in React/Enzyme,"<p>In normal <code>connect</code>ed React components, in order to make unit testing easier, I've seen the pattern of <a href=""https://hackernoon.com/unit-testing-redux-connected-components-692fa3c4441c"" rel=""nofollow noreferrer""><code>export</code>ing the base component, while <code>export default</code>ing the connected component</a>. It works well for simple tests that handle the actual functionality of the component without getting cluttered with redux stores and router mocking.</p>

<p>I'm looking for an analog for higher-order components. For instance, given a trivial higher-order component:</p>



<pre><code>export default function exampleHoc(Wrapped) {
  const ExampleHoc = props =&gt; (
    &lt;Wrapped {...props.reduxStore} hoc={true} /&gt;
  );

  return connect(
    state =&gt; ({
      reduxStore: state.example.reduxStore,
    }))(ExampleHoc);
}
</code></pre>

<p>I'd like to verify that <code>props.hoc === true</code> in a unit test, without having to wire up the other higher-order components that <code>&lt;ExampleHoc&gt;</code> strings along.</p>

<p>My best design is passing along a flag:</p>



<pre><code>export default function exampleHoc(Wrapped, exportUnconnectedForTest) {
  const ExampleHoc = props =&gt; (
    &lt;Wrapped {...props.reduxStore} hoc={true} /&gt;
  );

  if (exportUnconnectedForTest) {
    return ExampleHoc;
  }

  return connect(
    state =&gt; ({
      reduxStore: state.example.reduxStore,
    }))(ExampleHoc);
}
</code></pre>

<p>This makes it easy to test</p>



<pre><code>const DummyComponent = () =&gt; &lt;div /&gt;;
const Sut = exampleHoc(DummyComponent, true);

...

test('props value should be passed', () =&gt; {
  const sut = shallow(&lt;Sut /&gt;);
  const childProps = sut.find(DummyComponent).props();
  expect(sut.childProps.hoc).to.equal(true);
});
</code></pre>

<p>while still happily passing along the wrapped output to any regular callers of the method.</p>

<p>It works, but it seems clunky to me. Is there a better/established pattern for delivering the unwrapped interior of a higher-order component?</p>
",https://stackoverflow.com/questions/52288049/unit-testing-connected-higher-order-components-in-react-enzyme,"['javascript', 'reactjs', 'react-redux', 'mocha.js', 'enzyme']",660,FALSE,2,0
Unit testing ionic function which returns or uses a promise - TS2304: Cannot find name &#39;done&#39; - Jasmine / Karma for unit testing ionic apps,"<p>I'm trying to unit test a simple data access function with mocked Storage that simply uses a dictionary in memory.</p>

<p>When I try to use the <code>done()</code> function I get the error: <code>TS2304: Cannot find name 'done'</code> despite jasmine and karma seemingly being installed correctly.</p>

<p>Things I've done that have not fixed this issue:</p>

<ol>
<li>Verified Jasmine is in packages.json</li>
<li>Added **/*.spec.ts to excludes section of tsconfig.json?</li>
<li>Changed target from ""e5"" to ""e6"" in tsconfig.json</li>
</ol>

<p>data.ts:</p>

<pre><code>export class DataProvider {
  private foo;
  public readonly fooKey
  public getFoo() { return this.foo; }
  public setFoo(bar: number) {
        this.foo = bar;
        this.storage.ready().then(() =&gt; {
            this.storage.set(this.fooKey, JSON.stringify(this.foo));
        });
    }
}
</code></pre>

<p>data.spec.ts:</p>

<pre><code>include StorageMock;
include DataProvider;

 it('should have correct values after loading data',
       function() {
           comp.storage.set(comp.fooKey, JSON.stringify(0.1234));
           comp.storage.get(comp.fooKey).then(result =&gt; {
               expect(JSON.parse(result)).toEqual(0.1234);
               done(); // Error - TS2304: Cannot find name 'done'
           });
});
</code></pre>

<p>StorageMock:</p>

<pre><code>export class StorageMock {
    private internal = [];

    public driver(): any {
        return '';
    }

    public ready(): Promise&lt;any&gt; {
        return new Promise(function(resolve: Function): void {
            resolve({});
        });
    }

    public get(key: string): Promise&lt;any&gt; {
        let getval = this.internal[key];
        return new Promise(function(resolve: Function): void {
            resolve(getval);
        });
    }

    public set(key: string, value: any): Promise&lt;any&gt; {
        this.internal.push({key : value});
        return new Promise(function(resolve: Function): void {
            resolve();
        });
    }

    public remove(key: string): Promise&lt;any&gt; {
        let index = this.internal.indexOf(key);
        if(index !== -1) {
            this.internal.splice(index,1);
        }
        return new Promise(function(resolve: Function): void {
            resolve();
        });
    }

    public clear(): Promise&lt;any&gt; {
        this.internal = [];
        return new Promise(function(resolve: Function): void {
            resolve();
        });
    }

    public length(): Promise&lt;any&gt; {
        let length = this.internal.length;
        return new Promise(function(resolve: Function): void {
            resolve(length);
        });
    }

    public keys(): Promise&lt;any&gt; {
        let keys = Object.keys(this.internal);
        return new Promise(function(resolve: Function): void {
            resolve(keys);
        });
    }

    public forEach(i: any): Promise&lt;any&gt; {
        return new Promise(function(resolve: Function): void {
            resolve();
        });
    }
</code></pre>
",https://stackoverflow.com/questions/50615559/unit-testing-ionic-function-which-returns-or-uses-a-promise-ts2304-cannot-fin,"['angular', 'unit-testing', 'typescript', 'ionic-framework', 'karma-jasmine']",1396,TRUE,2,1
Mocking NPM dependencies in Node.js for jasmine unit testing,"<p>I want to unit test my login flow in a node.js module. I think that every time it encounter any NPM dependency like here I used stitching. It never goes inside stitching.auth() and I get response undefined. Here is my code..</p>

<pre><code>     module.exports.login = function(req, res) {
    const stitching = require(""stitching"");
        // User email/password
        const email = req.body.email;
        const password = req.body.password;
        var msg;
        // Login using the given email/password
        stitching.auth
        .login(email, password)
        .then((credentials) =&gt; {
           console.log('Login authenticated ...');  
            res.send(""authenticated"");
        },
        function failureHandler(error) {
        if(error=='Error: Wrong email/password')
        {
            console.log(error);
            res.send(""error"");
        }

      //handle
     }).catch(console.error);
    }
</code></pre>

<p>and my jasmine unit test is..</p>

<pre><code> describe(""POST /"",function(){
it(""The function should authenticate the user"",function() {
       const loginTest  =   require('../login_controller');
        const mocks = require('node-mocks-http');
        var req = {};
        var res = {};
        req = mocks.createRequest();
        res = mocks.createResponse();
        req.body.email = ""mongo.sitch@gmail.com"";
        req.body.password = ""abcd34"";
        value   =   loginTest.login(req,res);
        console.log(value);
        expect(value).toBe(""authenticated"");
});
});
</code></pre>
",https://stackoverflow.com/questions/51595208/mocking-npm-dependencies-in-node-js-for-jasmine-unit-testing,"['node.js', 'unit-testing', 'npm', 'jasmine', 'node-stitch']",191,FALSE,2,0
Whats the best approach for Unit Testing with braintree,"<p>I'm currently using the .NET SDK to process payments on my asp.net core project. I would like to automate tests using Unit Tests but it is proving difficult.</p>

<p>All the classes being used by the library - specifically ""Subscription"" and much more- have internal contructors or expect other internal instances. Options such as creating an instance from json to pass the it through a function is out.</p>

<p>It also not possible to construct an instance your self since the classes properties are all getters an with only the ""*request"" classes having setters but these arent't of much help since the application won't have to process them.</p>

<p>The Webhook test class is completely useless since the instance it gives is empty with only the id and status set. My application requires more data from a subscription such as the Transaction instance, Addons, Billing dates and more; all of which aren't populated.</p>

<p>I have several classes that require testing and having to do them manually is simply impracticle and wastes a lot of time. Is there another approach i am missing?</p>

<p>Why is the library designed like this, it doesn't seem very practicle in my opinion keeping the library so closed.</p>
",https://stackoverflow.com/questions/52210951/whats-the-best-approach-for-unit-testing-with-braintree,"['.net', 'braintree']",982,FALSE,2,1
How to mock mongodb for unit testing graphql resolver,"<p>I am learning graphql and want to do the unit testing for my resolver ( i.e. the query to get ""answers"").The problem is my resolver use mongoose to query data from mongodb behind the scene and I dont know how to mock these calls.</p>

<p>Could anyone help me with this ? Thank you.</p>

<p>The resolver for my query is sth like this:</p>

<pre><code>const { Book, Author } = require('../models')    

module.exports = {
  answers: async ( parent, { searchText } ) =&gt; {        
    let authors = null;
    let books = null;
    try {
        authors = await Author.find({});            
        books = await Book.find({}); 
        return getAnswers(authors,books, searchText);
    }catch (err) {
        console.log(err);
    }        
    return null;
 }
}

function getAnswers(books,authors,text) {
    &lt;!-- process data here --&gt;
}
</code></pre>
",https://stackoverflow.com/questions/52388777/how-to-mock-mongodb-for-unit-testing-graphql-resolver,"['node.js', 'mongodb', 'unit-testing', 'mongoose', 'graphql']",940,TRUE,2,2
Unit testing viewmodel in android using mockito MVVM pattern,"<p>This is my repository class </p>

<pre><code>class UserRepository (private val apiInterface: ApiInterface, private val utils: Utils) {

fun makeLoginOnServer(userName: String , password : String): Single&lt;UserResponse&gt;? {
    val hasConnection = utils.isConnectedToInternet()
    var observableFromApi: Single&lt;UserResponse&gt;? = null
    if (hasConnection) {
        observableFromApi = loginUser(userName,password)
    }
    return if (hasConnection)
        observableFromApi!!
    else
        null
}

private fun loginUser(userName: String , password : String): Single&lt;UserResponse&gt; {
    return apiInterface.makeLoginOnServer(userName,password)
}

}
</code></pre>

<p>This is my Viewmodel</p>

<pre><code>class LoginViewModel(private val userRepository: UserRepository) : ViewModel() {

var userResult: MutableLiveData&lt;UserResponse&gt; = MutableLiveData()
var userError: MutableLiveData&lt;String&gt; = MutableLiveData()
var userLoader: MutableLiveData&lt;Boolean&gt; = MutableLiveData()
private lateinit var disposableObserver: DisposableSingleObserver&lt;UserResponse&gt;

fun userResult(): LiveData&lt;UserResponse&gt; {
    return userResult
}

fun userError(): LiveData&lt;String&gt; {
    return userError
}

fun userLoader(): LiveData&lt;Boolean&gt; {
    return userLoader
}

fun makeLoginOnServer(userName: String , password: String) {
    disposableObserver = object : DisposableSingleObserver&lt;UserResponse&gt;() {
        override fun onSuccess(t: UserResponse) {
            userResult.postValue(t)
            userLoader.postValue(false)
        }
        override fun onError(e: Throwable) {
            userError.postValue(Constants.getErrorMessage(e))
            userLoader.postValue(false)
        }
    }
    userRepository.makeLoginOnServer(userName, password)
            ?.subscribeOn(Schedulers.io())
            ?.observeOn(AndroidSchedulers.mainThread())
            ?.subscribe(disposableObserver)
}

fun disposeElements() {
    if (!disposableObserver.isDisposed) disposableObserver.dispose()
}

}
</code></pre>

<p>I want to write unit test cases for my code.
I have written a sample test class here</p>

<pre><code> @RunWith(MockitoJUnitRunner::class)
 class GithubActivityViewModelTest {

@Rule
@JvmField
var rule = InstantTaskExecutorRule()

companion object {
    @ClassRule
    @JvmField
    val schedulers = RxImmediateSchedulerRule()
}

@Mock
lateinit var userRepository: UserRepository

@Mock
lateinit var observer: Observer&lt;UserResponse&gt;

lateinit var loginViewModel: LoginViewModel


@Before
fun setUp() {
    loginViewModel = LoginViewModel(userRepository)
}

@Test
fun shouldShowGithubAccountLoginName() {
    val githubAccount = UserResponse()
    Mockito.`when`(userRepository.makeLoginOnServer(""sdemo"",""sdemo""))
        .thenReturn(Single.just(githubAccount))
    loginViewModel.userResult.observeForever(observer)
    loginViewModel.makeLoginOnServer(""sdemo"",""sdemo"")
    assert(loginViewModel.userResult.value == githubAccount)

}
}
</code></pre>

<p>Now i need some clarification here what happens is that when the parameters are <code>""sdemo"" &amp;&amp; ""sdemo""</code> i get test pass for the cases but if i change any single value at one place i get a null pointer exception and my test fails.
I want to know how to assert that exception with mockito.
Please help</p>

<p>This is the log i get when i change sdemo to sdem</p>

<pre><code>java.lang.AssertionError: Assertion failed

at com.connect.viewmodels.GithubActivityViewModelTest.shouldShowGithubAccountLoginName(LoginViewModelTest.kt:54)
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.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
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 com.connect.RxImmediateSchedulerRule$apply$1.evaluate(RxImmediateSchedulerRule.kt:39)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
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)
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.AppMainV2.main(AppMainV2.java:131)
</code></pre>
",https://stackoverflow.com/questions/53629611/unit-testing-viewmodel-in-android-using-mockito-mvvm-pattern,"['android', 'unit-testing', 'junit', 'kotlin', 'mockito']",4506,TRUE,2,1
Unit testing subscribe method using jasmine in angular project,"<p>I'm trying to  test <code>ngOnInit()</code> method for the component that has a <code>subscribe</code> method:</p>

<p><strong>Component:</strong></p>

<pre><code> import { Component, OnInit} from '@angular/core';
 import { SharedDataService } from './../services/shared-data.service';

     @Component({
        selector: 'app-root',
        templateUrl: './app.component.html',
        styleUrls: ['./app.component.scss']
    })
    export class AppComponent implements OnInit {
        constructor(private sharedDataService: SharedDataService,) { }
        this.subscriptions = [];

        ngOnInit() {      

   this.subscriptions.push(this.sharedDataService.getModel().subscribe(model =&gt; {
             this.message=model.message
        }));
            }
        }   
    }
</code></pre>

<p><strong>Test Suite</strong></p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import {  XHRBackend } from '@angular/http';

describe('AppComponent Test', () =&gt; {
    let component: any;
    let fixture: ComponentFixture&lt;AppComponent&gt;;

    beforeEach(async(() =&gt; {
         TestBed.configureTestingModule({
            declarations: [AppComponent],
        providers: [SharedDataService , { provide: XHRBackend, useClass: MockBackend }]

        })
            .compileComponents();
    }));
    beforeEach(() =&gt; {
        fixture = TestBed.createComponent(AppComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });
    it('should be created', () =&gt; {
        expect(component).toBeTruthy();
    });
    it('test onInit function', () =&gt; {
        component.ngOnInit();
        spyOn(component.subscriptions,""push"");
        expect(component.subscriptions).toHaveBeenCalledWIth(component.sharedDataService.getModel());
    });
});
</code></pre>

<p>But throwing error as ""cannot spy on subscriptions"".Is this is the procedure to test subscribe method. Please suggest.</p>
",https://stackoverflow.com/questions/48642641/unit-testing-subscribe-method-using-jasmine-in-angular-project,"['angular', 'unit-testing', 'jasmine', 'subscribe']",8462,TRUE,2,1
Unit Testing Model Binding in Angular 5 with Jasmine,"<p>I am trying to write a unit test that tests that the JSON data returned from the components method call successfully binds to a typescript model.</p>

<p>My model looks like the following:</p>

<pre><code>export interface IPlayerAccount {
  playerId: number;
  name: string;
  phone: number;
  street: string;
  postcode: string;
  state: string;
  country: string;
}
</code></pre>

<p>This array of IPlayerAccount is populated on ngOnInit with method definition:</p>

<pre><code>getPlayerAccounts(playerId: number)
</code></pre>

<p>Here is my Jasmine Unit Test to test that the json data successfully finds to the typescript IPlayerAccount model.</p>

<pre><code> it('check that array of players successfully bind to component accounts players array', async () =&gt; {
          fixture.detectChanges();

          IPlayerAccount accounts = new IPlayerAccount();

          var account1 = new IPlayerAccount();
          account1.playerId = 1;
          account1.name = 'Ben';
          account1.phone = 12345;
          account1.street = 'Cloud Street';
          account1.postcode = 111;
          account1.state = 'VIC'
          account1.country = 'AU';

          var account2 = new IPlayerAccount();
          account2.playerId = 2;
          account2.name = 'James';
          account2.phone = 6789;
          account2.street = 'Jamming Street';
          account2.postcode = 2323;
          account2.state = 'VIC'
          account2.country = 'AU';

          component.accounts.push(account1);
          component.accounts.push(account2);

          IPlayerAccount[] returnedAccounts = component.getPlayerAccounts(1);

          // Need test methods here, such as expect. Not really sure how to simulate the method being called in Angular front-end testing
          // Is the above a good way to asynchronously test the getPlayerAccounts method of the component
        });
</code></pre>

<p>Note that I also have the following Mock that is used for the component.</p>

<pre><code> public GetPlayerAccounts(successCallback: (data) =&gt; void, errorCallback: (data) =&gt; void, playerId: number): void {
    let data = [{ ""playerId"": 1, ""name"": ""Ben"", ""phone"":""12345"" ""street"": ""Cloud Street"", ""postcode"": ""111"", ""state"": ""VIC"", ""country"": ""AU"" },{ ""playerId"": 2, ""name"": ""James"", ""phone"":""6789"" ""street"": ""Jamming Street"", ""postcode"": ""2323"", ""state"": ""VIC"", ""country"": ""AU"" }];
    successCallback(data);
  }
</code></pre>

<p>How do I match the data from the mock to the json data to then the IPlayerAccount? Is my approach good so far? Any better alternatives to solving this unit test?</p>

<p>Any help would be great!</p>
",https://stackoverflow.com/questions/50295168/unit-testing-model-binding-in-angular-5-with-jasmine,"['angular', 'unit-testing', 'model', 'jasmine']",2306,FALSE,2,1
How to resolve &quot;arguments are different&quot; error - unit testing,"<p>I wanted to write unit test for my <strong>addTask</strong> method with mockito. 
Here is the class that contains this method.</p>

<pre><code>package controller;

import model.Task;
import model.User;
import repository.TaskActions;
import repository.UserActions;

import java.sql.SQLException;
import java.util.List;

public class ToDoEngine {
private TaskActions taskActions;
private UserActions userActions;
private User connectedUser;

public ToDoEngine(UserActions userStorage, TaskActions taskStorage) {
    this.taskActions = taskStorage;
    this.userActions = userStorage;
}

public boolean signIn(String username, String password) throws SQLException {
    connectedUser = new User(username, password);
    if (!userActions.signIn(connectedUser)) {
        return false;
    }
    connectedUser.setID(retrieveConnectedUserID(connectedUser));
    return true;
}

private int retrieveConnectedUserID(User connectedUser) throws SQLException {
    return userActions.retrieveUserID(connectedUser);
}

public void addTask(String taskName) throws SQLException {
    taskActions.addTask(new Task(taskName), connectedUser);
}

}
</code></pre>

<p>Here are my attempts. Unfortunately, I've got error. Below, I am gonna present you stacktrace:</p>

<pre><code>package controller;

import model.Task;
import model.User;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import repository.TaskActions;
import repository.UserActions;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class ToDoEngineTest {

@Mock
TaskActions taskActionsMock;
@Mock
UserActions userActionsMock;
private ToDoEngine toDoEngine;


@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
    toDoEngine = new ToDoEngine(userActionsMock, taskActionsMock);
}

@Test
public void addTask() throws SQLException {
    Task taskName = new Task(""wash"");
    User user = new User(""admin"",""123"");
    toDoEngine.addTask(""wash"");
    verify(taskActionsMock).addTask(taskName,user);
}
}
</code></pre>

<p><strong>stacktrace</strong>:</p>

<pre><code>Argument(s) are different! Wanted:
taskActionsMock.addTask(
    Task(taskName=wash),
    model.User@1b71f500
);
-&gt; at controller.ToDoEngineTest.addTask(ToDoEngineTest.java:68)
Actual invocation has different arguments:
taskActionsMock.addTask(
    Task(taskName=wash),
    null
);
-&gt; at controller.ToDoEngine.addTask(ToDoEngine.java:40)

Comparison Failure:  &lt;Click to see difference&gt;

Argument(s) are different! Wanted:
taskActionsMock.addTask(
    Task(taskName=wash),
    model.User@1b71f500
);
-&gt; at controller.ToDoEngineTest.addTask(ToDoEngineTest.java:68)
Actual invocation has different arguments:
taskActionsMock.addTask(
    Task(taskName=wash),
    null
);
-&gt; at controller.ToDoEngine.addTask(ToDoEngine.java:40)
at controller.ToDoEngineTest.addTask(ToDoEngineTest.java:68)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
...
</code></pre>

<p>User and Task class contains hashCode and Equals method.</p>

<p><strong>Task</strong></p>

<pre><code>package model;

import lombok.*;

@Getter
@Setter
@AllArgsConstructor
@ToString
@NoArgsConstructor
@EqualsAndHashCode
public class Task {
private String taskName;
}
</code></pre>

<p><strong>User</strong>:</p>

<pre><code>package model;

import lombok.*;

@RequiredArgsConstructor
@Getter
@Setter
@EqualsAndHashCode

public class User {

private final String name;
private final String password;
private int ID;
}
</code></pre>

<p>Thanks in advance for help. :D</p>
",https://stackoverflow.com/questions/52205905/how-to-resolve-arguments-are-different-error-unit-testing,"['java', 'junit', 'mockito']",607,TRUE,2,2
Asp.Net Core get culture that support also unit testing,"<p>I have a web application in asp.net core that uses MVC and RequestLocalization. Some of the controllers require the culture and I used solution from 
<a href=""https://stackoverflow.com/questions/41289737/get-the-current-culture-in-a-controller-asp-net-core"">Get the current culture in a controller asp.net-core</a></p>

<p>The application also has to have unit tests. But I can not mock the RequestCulture.</p>

<p>What is the solution to get the culture that also supports unit testing?</p>

<p>PS: I do not want to use the CultureInfo.CurrentCulture or any solution that uses static classes or properties in the development code.</p>

<p>EDIT for Nkosi -  here is some code from memory:</p>

<pre><code>var mockContext = new Mock&lt;HttpContext&gt;();
var mockFeatures = new Mock&lt;IFeaturesCollection&gt;();
var mockRequestFeature = new Mock&lt;IRequestCultureFeature&gt;();
var mockRequestCulture = new Mock&lt;RequestCulture&gt;();
mockRequestCulture.Setup(rc =&gt; rc.UICulture).Returns(mockCulture.Object);
// If I remember corectly this does not work
mockRequestFeature.Setup(rf =&gt; rf.RequestCulture).Returns(mockRequestCulture.Object); 
mockFeatures.Setuo(f =&gt; f.Get&lt;IRequestCultureFeature&gt;()).Returns(mockRequestFeature.Object);
mockContext.Setup(r =&gt; r.Features).Return(mockFeatures.Object);
</code></pre>
",https://stackoverflow.com/questions/49575089/asp-net-core-get-culture-that-support-also-unit-testing,"['unit-testing', 'asp.net-core-mvc', 'moq', 'vs-unit-testing-framework']",606,FALSE,2,0
Mocking local imports when unit-testing Lua code with Busted,"<p>I'm very new to Lua and I'm trying to test a script I have running with an Nginx server. I've been recommended Busted but I can't seem to figure out how to mock some of the local imports.</p>

<p>The Lua code imports the following:</p>

<pre><code>local http = require ""resty.http""
</code></pre>

<p>And in the test _spec file, I start off like this:</p>

<pre><code>package.path = ""files/?.lua;spec/?.lua;"" .. package.path

_G.http = require('resty.fake_http')
local app = require('app')
</code></pre>

<p>I created a <code>fake_http.lua</code> file inside <code>spec/resty/http</code>.</p>

<p>But when I run a dummy test, I get the following error:</p>

<pre><code>suite spec/app_spec.lua
files/app.lua:3: module 'resty.http' not found:No LuaRocks module found for resty.http
</code></pre>

<p>Any Idea what I'm doing wrong here? </p>
",https://stackoverflow.com/questions/48409979/mocking-local-imports-when-unit-testing-lua-code-with-busted,"['unit-testing', 'lua', 'lua-busted']",1718,TRUE,8,1
Unit Testing with karma in Angular 4 with Webpack,"<p>Here is my karma.config.js file -</p>

<pre><code>module.exports = function (config) {

config.set({
basePath: '',
frameworks: ['jasmine'],

plugins: [
  require('karma-jasmine'),
  require('karma-chrome-launcher'),
  require('karma-jasmine-html-reporter'),
  'karma-webpack',
  'karma-babel-preprocessor',
  // 'babel-preset-es2015'
],

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']
  }
},
mime: {
  'text/x-typescript': ['ts']
},
files: [
  './src/client/app/phone/component/nokia.component.ts',
  './src/client/app/phone/component/nokia.spec.ts'
],

// Proxied base paths for loading assets
proxies: {
  // required for component assets fetched by Angular's compiler
  ""/app/"": appAssets
},
// webpack: configureWebpack(),
exclude: [],
preprocessors: {
  './src/client/app/phone/component/nokia.component.spec.ts': ['babel', 'webpack'],
},
// babelPreprocessor: {
//   options: {
//     ""presets"": [""es2015""]
//   }
// },
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
});


 };

function configureWebpack() {
var webpackConfig = require('./webpack.config');
webpackConfig.entry = undefined; // karma will pass the proper 
argument for entry
return webpackConfig;
}
</code></pre>

<p>The Problem I am facing is I can not Access component from spec file.
karma throws err-</p>

<blockquote>
  <p>ERROR in ./src/client/app/phone/component/nokia.component.spec.ts
  Module not found: Error: Can't resolve './nokia.component' in '/media/folder/New Volume/.....<strong>path</strong>'
   @ ./src/client/app/phone/component/nokia.component.spec.ts 1:0-61</p>
</blockquote>

<p>What I get -</p>

<p>Basically i can not Access Import statements from spec file. As Our components are using ES6 things but my karma Configuration can not understand that ES6 things.</p>

<p>Is their any way that can tell or convert my ES6 things to ES5 So that my browser can understand this.</p>

<p>On this I found this thing <strong>'babel-preset-es2015'</strong> but i can not fit this into my config file of karma.</p>

<p>Or is their any alternate way - in karma config so that i can test my all components with Karma Jasmine in Angular 4 .</p>

<p>NOTE - I am using webpack directly (Not angular cli).</p>

<p>Please answer for webpack</p>
",https://stackoverflow.com/questions/49384805/unit-testing-with-karma-in-angular-4-with-webpack,"['javascript', 'angular', 'typescript', 'webpack', 'karma-jasmine']",294,FALSE,2,0
Problems deleting file in fileManager(FileManager.default.removeItem) while unit testing,"<p>Currently there are issues with files not being deleted.  I've looked at other posts like: <a href=""https://stackoverflow.com/questions/43651481/filemanager-default-removeitem-not-removing-file"">FileManager.default.removeItem not removing file [duplicate]
</a> and <a href=""https://stackoverflow.com/questions/41974312/error-deleting-contents-in-directory-domain-nscocoaerrordomain-code-4-domain"">Error deleting contents in directory - Domain=NSCocoaErrorDomain Code=4 | Domain=NSPOSIXErrorDomain Code=2 “No such file or directory”</a></p>

<p>I'm getting the same error “No such file or directory”. This is happening with this function when it's being unit tested:</p>

<pre><code> internal func getCacheFolderPath() -&gt; String {
    var folderPath = """"
    guard let path = self.urls(for:.cachesDirectory , in: .userDomainMask).last?.path else { return folderPath }
    folderPath = path + ""/NetworkCache""
    if !self.fileExists(atPath: folderPath) {
        do {
          try  self.createDirectory(atPath: folderPath, withIntermediateDirectories: false, attributes: nil)
        }
        catch {
            print(error.localizedDescription)
        }
}
    return folderPath
}


internal func filePathForFileName(name: String) -&gt; String {
    let cyptoName = name.md5()
    return getCacheFolderPath() + ""/"" + (cyptoName ?? """")
}



func deleteFile(forFile fileName: String){
        let path = self.filePathForFileName(name: fileName)

        if self.fileExists(atPath: path) {
            do {
                try self.removeItem(atPath: path)
              //  print(path)
            } catch  {
                print(error.localizedDescription)
            }
        }
    }
</code></pre>

<p>This is what the unit test looks like:</p>

<pre><code>func test_deleteFile(){

    let path = sut!.filePathForFileName(name: fileName)

    sut?.deleteFile(forFile: fileName)
    print(path)

    if sut!.fileExists(atPath: path){

    let filemanager = FileManager.default

           do {
    try filemanager.removeItem(atPath: path)

           } catch {
            print (""The file could not be removed: \(error)"")
        }
    }
}
</code></pre>

<p>FYI I am using a mockFileSystem that is subclassed from FileManager. Even when I try and delete the path manually in the do, try, catch block it still returns the error “No such file or directory”.</p>
",https://stackoverflow.com/questions/49539251/problems-deleting-file-in-filemanagerfilemanager-default-removeitem-while-unit,"['ios', 'swift', 'caching', 'xctest', 'nsfilemanager']",747,FALSE,2,0
Unit-testing adding to a collection without contains() method,"<p>Consider this class:</p>

<pre><code>public class Customer {

    private final List&lt;Rental&gt; rentals;

    public Customer() {
        this.rentals = new ArrayList&lt;&gt;();
    }

    public void addRental(Rental rental) {
        if (rental != null) {
            this.rentals.add(rental);
        }
    }

    public BigDecimal sumRentals() {
        return rentals.stream()
                .map(r -&gt; r.getPrice())
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }
}
</code></pre>

<p>I want to create a unit test on the <code>addRental()</code> method, yet I don't want to publish a getter to the <code>rental</code> member, nor do I plan on publishing a <code>consists()</code> method and writing it just for the sake of tests seems a bad practise.</p>

<p>So the question is: how do I go about testing <code>addRental()</code>? Do I make use of the <code>sumRentals()</code> method, even if the test is indirect (I would be checking if the sum of elements changed correctly and not if the element was actually added to the collection)? Do I forget about testing <code>addRental()</code> altogether since it's so trivial? What if it wasn't though and there was some more logic to it? </p>
",https://stackoverflow.com/questions/48216484/unit-testing-adding-to-a-collection-without-contains-method,"['java', 'unit-testing', 'collections']",189,TRUE,1,2
Angular Directive function not being called in Unit Testing,"<p>I built a new directive in Angular (1.2.29) and I am trying to test it using karma, however I am having some problems when checking if the field is invalid, it seems it's always valid.</p>

<p><strong>Here is my directive:</strong></p>

<pre><code>var EmailOrUrlValidation = function emailOrUrlValidation() {

        console.log(""on directive 0"");

        return {
            require: 'ngModel',
            restrict: 'A',
            scope: {
                checkDirty: '=validationCheckDirty'
            },
            link: function (scope, element, attrs, ctrl) {

                console.log(""on directive 1"");

                scope.$watch(function () {
                    scope.checkDirty = scope.checkDirty ? true : false;
                    element.attr('maxlength', 50);
                    ctrl.$parsers.unshift(validateEmailOrUrl);
                    ctrl.$formatters.unshift(validateEmailOrUrl);
                });

                function validateEmailOrUrl(value) {
                    console.log(""on directive 2"");
                    var urlRegexp = ""myurlregex"";
                    var emailPattern = ""myemailregex"";

                    if (!value) { 
                        ctrl.$setValidity(""valid"", true);

                    } else if (scope.checkDirty &amp;&amp; !ctrl.$dirty) { 
                        ctrl.$setValidity(""valid"", true);

                    } else { 
                        var emailRegex = new RegExp(emailPattern);

                        var emailOrUrlValid = urlRegexp.test(value) || emailRegex.test(value);
                        ctrl.$setValidity(""valid"", emailOrUrlValid);
                    }
                    return value;
                }
            }
        };
    };

 this.app = angular.module('shared.validations', [])
                     .directive('emailOrUrlValidation', [emailOrUrlValidation])
</code></pre>

<p><strong>Here is my unit testing (I followed this example <a href=""https://stackoverflow.com/a/22772504/1031021"">https://stackoverflow.com/a/22772504/1031021</a>):</strong></p>

<pre><code>describe('EmailOrUrlValidation tests', function () {
    var $scope, form, element;
    beforeEach(module(""shared.validations""));
    beforeEach(inject(function ($compile, $rootScope) {
        $scope = $rootScope;
        element = angular.element(
            '&lt;form name=""form""&gt;' +
                '&lt;input data-ng-model=""model.emailorurl"" name=""emailorurl"" email-or-url-validation data-ng-required=""true"" validation-check-dirty=""true"" /&gt;' +
            '&lt;/form&gt;'
        );
        $scope.model = { emailorurl: null }
        $compile(element)($scope);
        form = $scope.form;
    }));
    describe('invalid url', function () {
        it('should pass with valid url', function () {

            form.emailorurl.$setViewValue('www.google.pt');
            $scope.$digest();

            expect(form.emailorurl.$invalid).to.be.false;
        });
        it('should not pass with invalid url', function () {

            form.emailorurl.$setViewValue('testing');
            $scope.$digest();

            expect(form.emailorurl.$invalid).to.be.true;
        });
    });
});
</code></pre>

<p>However one of the assertions fail, because $invalid is always false... </p>

<p>I inserted some logs inside the function <strong>validateEmailOrUrl</strong> and its never shown on my console, however logs outside of function appear, I assume the function its not being triggered.</p>

<p>Can someone help me? What is wrong here?</p>
",https://stackoverflow.com/questions/48287209/angular-directive-function-not-being-called-in-unit-testing,"['javascript', 'angularjs', 'unit-testing', 'angularjs-directive']",285,FALSE,1,1
Unit testing for getting random Number in angular 4,"<p>I have a method in my ts file to create random list as below.</p>

<pre><code>list = [];

createItem(index, random_boolean) {
    return { id: index, name: `Item ${index}`, details: `Item ${index} occured`, selected : random_boolean };
}
createRandomItem() {
    const int = parseInt((Math.random() * 100) + '', 10);
    const random_boolean  = Math.random() &gt;= 0.5;
    return this.createItem(int, random_boolean);
  } 

for (var i = 0; i &lt; 10; i++) {
    list.push(this.createRandomItem(i));
}
</code></pre>

<p>How to write unit test case for createRandomItem() method.</p>

<p>Thanks for the help.</p>
",https://stackoverflow.com/questions/51971036/unit-testing-for-getting-random-number-in-angular-4,"['javascript', 'angular', 'unit-testing']",989,TRUE,1,1
Is it possible to use QCustomPlot in unit testing?,"<p>I need to create a family of plots during a test of my program. I want to use <code>QCustomPlot</code> for such purposes, but I have a problem. For creating and saving my plot in the file,  I have to create <code>QApplication</code>, after I need to reimplement my class from <code>QMainWindow</code> and after that, I can Use my <code>QCustomPlot</code> in the function that creates all needed plots and saves them in to file. Is it possible to avoid creating <code>QApplication</code> instance or <code>QMainWindow</code> instance or them both?   </p>

<p>See code of my function below: </p>

<pre><code>void MainWindow::print_image(std::vector&lt;double&gt; az, std::vector&lt;double&gt; el, std::vector&lt;double&gt; za, char *image_path){

QVector&lt;double&gt; azFunct;// =// QVector&lt;double&gt;::fromStdVector(az);
QVector&lt;double&gt; elFunct;// =// QVector&lt;double&gt;::fromStdVector(el);
QVector&lt;double&gt; zFunct = QVector&lt;double&gt;::fromStdVector(za);
QVector&lt;double&gt; xAxisValue(az.size());

//Filling axes of x with values
std::iota(xAxisValue.begin(),xAxisValue.end(),0);

QCustomPlot customPlot;

customPlot.setLocale(QLocale(QLocale::English, QLocale::UnitedKingdom)); // period as decimal separator and comma as thousand separator
customPlot.legend-&gt;setVisible(true);
QFont legendFont = font();  // start out with MainWindow's font..
legendFont.setPointSize(9); // and make a bit smaller for legend
customPlot.legend-&gt;setFont(legendFont);
customPlot.legend-&gt;setBrush(QBrush(QColor(255,255,255,230)));
// by default, the legend is in the inset layout of the main axis rect. So this is how we access it to change legend placement:
customPlot.axisRect()-&gt;insetLayout()-&gt;setInsetAlignment(0, Qt::AlignTop|Qt::AlignRight);

//Adding new graph for displaying, all on the same plot.
customPlot.addGraph(customPlot.yAxis, customPlot.xAxis);
customPlot.graph(0)-&gt;setPen(QPen(QColor(255, 100, 0)));
customPlot.graph(0)-&gt;setName(""Azimuth function"");

//Adding new graph for displaying, all on the same plot.
customPlot.addGraph();
customPlot.graph(1)-&gt;setPen(QPen(Qt::red));
customPlot.graph(1)-&gt;setName(""Elevation function"");

//Adding new graph for displaying, all on the same plot.
customPlot.addGraph();
customPlot.graph(2)-&gt;setPen(QPen(Qt::green));
customPlot.graph(2)-&gt;setName(""Z-axis function"");


for(int i = 0; i &lt; az.size(); ++i){
    azFunct[i] = sin(az[i]*M_PI/180);
    elFunct[i] = cos(el[i]*M_PI/180);
}

double minZ = *std::min_element(zFunct.constBegin(), zFunct.constEnd());
double maxZ = *std::max_element(zFunct.constBegin(), zFunct.constEnd());

// pass data points to graphs:
customPlot.graph(0)-&gt;setData(xAxisValue, azFunct);
customPlot.graph(1)-&gt;setData(xAxisValue, elFunct);
customPlot.graph(2)-&gt;setData(xAxisValue,zFunct);

customPlot.xAxis-&gt;setVisible(true);
customPlot.xAxis-&gt;setTickLabels(false);
customPlot.xAxis2-&gt;setVisible(true);
customPlot.xAxis2-&gt;setTickLabels(false);
customPlot.yAxis2-&gt;setVisible(true);
// set ranges appropriate to show data:
customPlot.yAxis-&gt;setRange(-1, 1);
customPlot.yAxis2-&gt;setRange(minZ, maxZ);

customPlot.plotLayout()-&gt;insertRow(0);
//customPlot.plotLayout()-&gt;addElement(0, 0, new QCPTextElement(customPlot, ""Z axis"", QFont(""sans"", 12, QFont::Bold)));

// set labels:
customPlot.yAxis-&gt;setLabel(""sin/cos value"");
customPlot.yAxis2-&gt;setLabel(""Z - axis"");
//Under big question have to be tested!
customPlot.replot();
customPlot.savePng(QString(image_path),1500,500,1);}
</code></pre>
",https://stackoverflow.com/questions/51336336/is-it-possible-to-use-qcustomplot-in-unit-testing,"['c++', 'qt', 'qcustomplot']",183,FALSE,1,1
Unit testing a code that uses Azure Cloud Services,"<p>I have got a code for which I have to write unit tests.
Since I am new to unit tests, I am reaching out to your assistance.
I want to test the method IsAdmin, which gets as an input a CloudTableClient and a string, but I don't really know how to approach it.
I tried the code below, but it failed with the message:</p>

<blockquote>
  <p>Message: Test method UnitTestMatan.UserControllerTests.IsAdmin_NotOnTheList_ReturnFalse threw exception: 
  System.MethodAccessException: Attempt by method 'MatanWebServer.Controllers.UserController.IsAdmin(Microsoft.WindowsAzure.Storage.Table.CloudTableClient, System.String)' to access method 'Microsoft.WindowsAzure.Storage.Table.CloudTable.ExecuteQuery(Microsoft.WindowsAzure.Storage.Table.TableQuery, Microsoft.WindowsAzure.Storage.Table.TableRequestOptions, Microsoft.WindowsAzure.Storage.OperationContext)' failed.</p>
</blockquote>

<p>Basically, the first thing that I want to test is that IsAdmin will return false when it gets an email which is not in the table or just a random String.
In the test part, I want to use the table generated in UserController and not build a new one.</p>

<p>The following is the class I need to test:</p>

<pre><code>using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using ParseMatanDataWebJob;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace MatanWebServer.Controllers
{    
    public class UserController : ApiController
    {
        // GET: api/user
        [AdminAuthorizeAttribute]
        public IEnumerable&lt;string&gt; Get()
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(""DefaultEndpointsProtocol=http;AccountName=matandata;AccountKey=myconnectionstringthatidontwantyoutoknow"");
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

            IEnumerable&lt;string&gt; EmailsList = GetAllEmails(tableClient);

            return (EmailsList);
        }

        // GET: api/user/5
        [UserAuthorizeAttribute]        
        public ReturnObjectValuescontroller Get(string email)
        {            
            // Retrieve the storage account from the connection string.p
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(""myconnectionstringthatidontwantyoutoknow"");

            // Create the table client.
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();

            var result = new ReturnObjectValuescontroller();

            result.isAdmin = IsAdmin(tableClient, email);

            // Create the CloudTable object that represents the ""people"" table.
            CloudTable donationsTable = tableClient.GetTableReference(""userdonationsdata"");

            // Create the table query.
            TableQuery&lt;DonationData&gt; userDonationsQuery = new TableQuery&lt;DonationData&gt;().Where(
            TableQuery.GenerateFilterCondition(""PartitionKey"", QueryComparisons.Equal, email.ToString()));

            var DonationsResult = donationsTable.ExecuteQuery(userDonationsQuery).ToList();

            result.DonationsList = DonationsResult;

            return result;
        }

        public static bool IsAdmin(CloudTableClient tableClient, string email)
        {
            CloudTable AdminsTable = tableClient.GetTableReference(""matanadminusers"");

            TableQuery AdminsListQuery = new TableQuery();

            AdminsListQuery.SelectColumns = new List&lt;string&gt;() { ""AdminEmail"" };

            var TableEntityAdminsList = AdminsTable.ExecuteQuery(AdminsListQuery).ToList();

            List&lt;string&gt; AdminsEmailList = new List&lt;string&gt;();
            foreach (var item in TableEntityAdminsList)
            {
                AdminsEmailList.Add(item.Properties[""AdminEmail""].StringValue);
            }

            return (AdminsEmailList.Contains(email, StringComparer.OrdinalIgnoreCase));
        }

        private IEnumerable&lt;string&gt; GetAllEmails(CloudTableClient tableClient)
        {            
            CloudTable donationsTable = tableClient.GetTableReference(""useremails"");

            TableQuery EmailsListQuery = new TableQuery();

            EmailsListQuery.SelectColumns = new List&lt;string&gt;() { ""RowKey"" };

            var DynamicEntityEmailsList = donationsTable.ExecuteQuery(EmailsListQuery).ToList();

            List&lt;string&gt; EmailList = new List&lt;string&gt;();
            foreach (var item in DynamicEntityEmailsList)
            {
                EmailList.Add(item.RowKey);
            }
            return EmailList.Distinct();
        }

        // POST: api/Rony
        public void Post([FromBody]string value)
        {
        }

        // PUT: api/Rony/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE: api/Rony/5
        public void Delete(int id)
        {
        }
    }
}
</code></pre>

<p>And this is the test I tried for IsAdmin:</p>

<pre><code>using System;
using MatanWebServer.Controllers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;

namespace UnitTestMatan
{
    [TestClass]
    public class UserControllerTests
    {
        [TestMethod]
        public void IsAdmin_NotOnTheList_ReturnFalse()
        {
            var userController = new UserController();

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(""myconnectionstringthatidontwantyoutoknow"");
            CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
            var result = UserController.IsAdmin(tableClient, ""str"");

            Assert.IsFalse(result);       
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/51878840/unit-testing-a-code-that-uses-azure-cloud-services,"['c#', 'visual-studio', 'azure', 'unit-testing', 'azure-cloud-services']",2249,TRUE,1,2
How do I pass parameters in PHP unit testing,"<p>I am trying to learn how to create unit tests for my custom ""framework"" and here is a method that verifies the email address when user is registering. </p>

<pre><code>private function verifyEmail()
{
    if(empty($this-&gt;email) || empty($this-&gt;email_repeat)) {
        throw new \Exception('please enter email');
    }
    if($this-&gt;email != $this-&gt;email_repeat) {
        throw new \Exception('emails don\'t match');
    }
    if(!filter_var($this-&gt;email, FILTER_VALIDATE_EMAIL)) {
        throw new \Exception('E-mail is invalid');
    }

    $isTaken = $this-&gt;db-&gt;getRow(""SELECT COUNT(*) as count FROM users WHERE email = ?"", [$this-&gt;email]);
    if($isTaken-&gt;count &gt; 0){
        throw new \Exception('E-mail is taken');
    }
}
</code></pre>

<p>And here is the unit test </p>

<pre><code>class RegisterTest extends \PHPUnit\Framework\TestCase
{
    public function testVerifyEmail() {
        // what do i type here?
    }
}
</code></pre>

<p>So, what do I type in the <code>testVerifyEmail()</code> method to pass an email to be tested? I am going through the documentation but as a newbie the information is overwhelming and I can't find a solution. </p>
",https://stackoverflow.com/questions/50370182/how-do-i-pass-parameters-in-php-unit-testing,"['php', 'unit-testing']",4583,TRUE,1,1
Is there a point in unit testing Mongoose schema,"<p>For purpose of demonstration assume that I have the following schema + model:</p>

<pre><code>const UserSchema = mongoose.Schema({
  userName: {
    type: String,
    required: true,
    unique: true
  }
});

const UserModel = mongoose.model(""User"", UserSchema);
</code></pre>

<p>I intend to have a large schema, so for easier maintenance I have it defined in <strong>user.schema.js</strong>, whereas the corresponding <strong>user model</strong> is in a separate file.</p>

<p>I covered the model with unit tests and began contemplating doing the same for the schema module, except... I am not sure if there is a point?</p>

<p>I have seen people test their models/schemas using an actual test database connection, but that is not a unit test IMO, it resembles an integration test more, and that is a different concept. For a unit test of a <strong>schema</strong> only I don't care if MongoDB itself works correctly.</p>

<p>The Internet (including SO) has also revealed code, which tests Mongoose's validation. This is closer to what I wanted to do as the basic idea is to check whether all expected props and restrictions are in the schema. It would look like this:</p>

<pre><code>it('should be invalid if username is empty', function(done) {
  new UserModel().validate(function(err) {
    expect(err.errors.name).to.exist;
    done();
  });
});
</code></pre>

<p>If testing with a live DB one could change <code>.validate</code> to <code>.save</code> too.</p>

<p>Then it dawned upon me that I would be doing two things here:</p>

<ol>
<li>Testing the behaviour of Mongoose, which I also don't care/intend/want to do.</li>
<li>Essentially duplicating my schema. If I later decide to change anything in it, I would have to change the unit test too.</li>
</ol>

<p>This seems like unit testing a configuration object, and that is pointless, aside from maybe making sure that I wrote my regexes correctly and stuff like that.</p>

<h2>Questions</h2>

<ol>
<li>I have thus decided not to test the schema at all. Does that make sense or am I missing something?</li>
<li>As a side question, do you believe there is a point in writing tests with a DB connection? This would test my schema + mongoose + mongo and somehow I find it redundant.</li>
</ol>
",https://stackoverflow.com/questions/52202245/is-there-a-point-in-unit-testing-mongoose-schema,"['unit-testing', 'mongoose', 'schema']",583,FALSE,2,0
WPF project - unable to set up unit testing (C#),"<p>I'm attempting to set up unit tests for a WPF project I have.  I have a public method called MoveSelectionOutOfSelectedBox in a project called WPFTester.  Here is the method...</p>

<pre><code>  public void MoveSelectionOutOfSelectedBox(object sender, RoutedEventArgs e)
    {
        if (testSelectedBox.Items.Count == 1 &amp;&amp; testSelectedBox.SelectedItem == null)
        {
            testSelectedBox.Items.Clear();
            testSelectedBox2.Items.Clear();
            spOptionsAcceptableRangeMax.Visibility = spOptionsAcceptableRangeMin.Visibility = spOptionsLabel.Visibility = spOptionsValue.Visibility = Visibility.Hidden;
            xmlData2.Clear();
        }
        else
        {
            xmlData2.RemoveAt(testSelectedBox.SelectedIndex);
            testSelectedBox.Items.RemoveAt(testSelectedBox.SelectedIndex);

            if (testSelectedBox.Items.Count == 0)
            {
                spOptionsAcceptableRangeMax.Visibility = spOptionsAcceptableRangeMin.Visibility = spOptionsLabel.Visibility = spOptionsValue.Visibility = Visibility.Hidden;
                xmlData2.Clear();
            }
            else
            {
                LoadOptionsForCertainIndex(0);
            }
        }
        UpdateTestEstimate();
    }
</code></pre>

<p>I then set up a separate project in the same solution called ORCTests.  Within a class in ORCTests called UnitTest1.cs, I have the following test...</p>

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

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Reflection;
using System.Windows.Media.Imaging;
using System.Xml;


namespace ORCTests          
{
    [TestClass]
    public class UnitTest1 
    {
        [TestMethod]
        public void TestMethod1()
        {
            var wpf = new MainWindow();            
            wpf.LoadDeviceBox();
            Assert.IsTrue(WpfTester.MainWindow.xmlData.Count &gt; 0);
        }
    }
}
</code></pre>

<p>When I debug this I step into MainWindow() but get an error on the first line of MainWindow which simply sets up dynamic paths.  Here is the first line of MainWindow()...</p>

<p>string binaryDocumentPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + ""/Documents/"";</p>

<p>In debug mode I get this following error on this line....</p>

<pre><code>System.NullReferenceException
  HResult=0x80004003
  Message=Object reference not set to an instance of an object.
  Source=WpfTester
  StackTrace:
   at WpfTester.MainWindow..ctor() in C:\Users\StarkS02\source\repos\WpfTester\WpfTester\MainWindow.xaml.cs:line 26
   at ORCTests.UnitTest1.TestMethod1() in C:\Users\StarkS02\source\repos\WpfTester\ORCTests\UnitTest1.cs:line 24
</code></pre>

<p>When I run this method normally, not in a unit test, I do not get an error on this line.  Any ideas why I get this error?</p>
",https://stackoverflow.com/questions/51199150/wpf-project-unable-to-set-up-unit-testing-c,"['c#', 'wpf', 'unit-testing']",329,TRUE,1,2
Unit Testing ECMAScript Modules (ESM) and Mocking Local State?,"<p>How can I test functions of ECMAScript Modules (ESM) (or JavaScript Modules) that depend on the local state of their module?  Specifically, I want to mock the local state within the module.</p>

<p>From this article <a href=""http://exploringjs.com/es6/ch_modules.html"" rel=""nofollow noreferrer"">http://exploringjs.com/es6/ch_modules.html</a>, I understand that:</p>

<ul>
<li>Modules are singletons.</li>
<li>In ES6, <code>import</code>s are read-only views on <code>export</code>s</li>
</ul>

<p>Thus, while I could export a local variable, and import that local variable from the test and then modifiy it, because it’s read-only I’ll get an error.</p>

<p><strong>Q)</strong> How can I mock the local state of an ES6 module?  When it's type:</p>

<ol>
<li>Number?</li>
<li>Object?</li>
<li>Function?</li>
</ol>

<hr>

<p>Example <code>sumModule.js</code> - How can I mock this to set the sum, as I wish that is appropriate, for the test?  Zero, may not be appropriate.</p>

<pre><code>let sum = 0 // local state - type number example

export function addToSum (num) {
  sum += num;
  return sum
}
</code></pre>
",https://stackoverflow.com/questions/51334734/unit-testing-ecmascript-modules-esm-and-mocking-local-state,"['javascript', 'unit-testing', 'module', 'mocking', 'es6-modules']",260,TRUE,1,1
Using fixures in Unit testing with Nodejs and MongoDB,"<p>I'm working on a <em>Nodejs</em>, <em>MongoDB project</em>, and I want to write <em>unit tests for it using <strong>Jest</em></strong>, Let's assume that there are two schemas in my project: <code>User</code>, <code>Book</code>. What I need is a structure, or a way or a tool to solve these issues:</p>

<ol>
<li><p>be able to load a bunch of data before each test, and clear it afterward (I want a fix and clear database state for each test)</p>

<ul>
<li>it is better if the data is loaded from a JSON file.</li>
</ul></li>
<li><p>I need to be able to specify the data I want to load for each test. for example, I only need fixtures related to User schema when I want to write unit tests for User API, so I don't want to load fixtures related to Book schema.</p></li>
<li><p>it would be a bonus point, but not necessary if the database used is the in-memory database instead of the real MongoDB database. (I want the tests to be fast)</p></li>
</ol>

<p>so far I only have found some libraries that solve the first one, but not the second one.</p>
",https://stackoverflow.com/questions/52985788/using-fixures-in-unit-testing-with-nodejs-and-mongodb,"['node.js', 'mongodb', 'testing', 'jestjs', 'fixtures']",60,FALSE,1,0
Spring WebFlux project that connects to ElasticSearch Unit Testing,"<p>I am currently working on a Spring WebFlux project that connects to ElasticSearch. I have a Rest Service that in turn calls a method in the Service Layer that connects to the ES. I am having trouble writing UnitTests for my Service Layer. Any help would be appreciated as this is the first time I am working with Reactive Programming. Below are the code snippets for my Controller and Service methods.</p>

<p>Controller Code :</p>

<pre><code>@GetMapping(path = ""/api/apis/services/{id}"", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
  Flux&lt;ClassA&gt; serviceApis(@PathVariable final String serviceKey) {
        return apiService.getDataForService(serviceKey);
  }
</code></pre>

<p>Service Layer :</p>

<pre><code>@PreAuthorize(""isFullyAuthenticated()"")
    public Flux&lt;ClassA&gt; getDataForService(
            final String id) {

        IdentityToken token = GSLSecurityContext.getCurrentUserIdentityToken();
        if (token == null) {
            return Flux.error(new Exception(""No token found""));
        }

        String securityQueryJson = getSecurityShould(token);

        String queryToRun = QUERY
                .replace(""XXX_SIZE_XXX"", config.getValueAsString(""scroll.size""))
                .replace(""XXX_SECURITY_SHOULD_XXX"", securityQueryJson)
                .replace(""XXX_SERVICE_KEY_XXX"", id);

        WebClient client = ClientUtil.getDataLakeWebClient(config);
        Flux&lt;ClassA&gt; response = getData(client, queryToRun);
        return response;
    }
</code></pre>

<p>The getData code is as below :</p>

<pre><code>protected Flux&lt;ClassA&gt; getData(
        final WebClient client,
        final String queryToRun) {
    String scrollTimeoutQuery = ""?scroll="" + config.getValueAsString(""scroll.timeout"");
    long timeout = config.getValueAsLong(""query.timout"");
    return Flux.generate(
        () -&gt; null,
        (scrollId, sink) -&gt; {
            ClassAWrapper lastWrapper = null;
            if (scrollId == null) {
                Mono&lt;ClassAWrapper&gt; wrapper = client.post()
                    .uri(getSearchURI() + scrollTimeoutQuery)
                    .body(BodyInserters.fromObject(queryToRun)).retrieve()
                    .bodyToMono(ClassAWrapper.class)
                    .onErrorMap(original -&gt; new Exception(""Unable to retrieve from elastic search for query "" + queryToRun, original))
                    .log();
                try {
                    lastWrapper = wrapper.block(Duration.ofSeconds(timeout));
                } catch (IllegalStateException ex) {
                    LOG.error(""Timedout after "" + timeout + "" seconds while getting data from elastic search for query "" + queryToRun);
                    lastWrapper = null;
                } catch (Exception ex) {
                    LOG.error(""Error in getting message details"",ex);
                    lastWrapper = null;
                } 
            } else {
                String scrollQuery = ""{\""scroll\"" : \"""" + config.getValueAsString(""scroll.timeout"") + ""\"", \""scroll_id\"" : \"""" + scrollId + ""\""}"";
                Mono&lt;ClassAWrapper&gt; wrapper = client.post()
                        .uri(""_search/scroll"")
                        .body(BodyInserters.fromObject(scrollQuery)).retrieve()
                        .bodyToMono(ClassAWrapper.class)
                        .onErrorMap(original -&gt; new Exception(""Unable to retrieve next page of data from elastic search"", original))
                        .log();
                try {
                    lastWrapper = wrapper.block(Duration.ofSeconds(timeout));
                } catch (IllegalStateException ex) {
                    LOG.error(""Timeout after "" + timeout + "" seconds while getting data from elastic search for query "" + queryToRun);
                    lastWrapper = null;
                } catch (Exception ex) {
                    LOG.error(""Error in getting message details"",ex);
                    lastWrapper = null;
                } 
            }
            if (lastWrapper == null || lastWrapper.getResult() == null || lastWrapper.getResult().getDetails().isEmpty()) {
                sink.next(new ClassA());
                sink.complete();
                return null;
            }
            sink.next(lastWrapper.getResult());
            return lastWrapper.getScrollId();
        }
    );
}
</code></pre>

<p>Here, queryToRun is the ES query to be executed. config is the configuration. I need to test the method ""getDataForService()"".</p>
",https://stackoverflow.com/questions/50698439/spring-webflux-project-that-connects-to-elasticsearch-unit-testing,"['unit-testing', 'spring-webflux', 'reactive']",604,FALSE,1,0
Play Framework 2.6 Error When Unit Testing Controller Endpoints,"<p>I have the following test:</p>

<pre><code>import org.scalatestplus.play._
import play.api.test.Helpers._
import play.api.test.{FakeRequest, WsTestClient}
import com.github.andyglow.websocket._
import com.inland24.plantsim.controllers.ApplicationTestFactory
import org.scalatest.WordSpecLike
import org.scalatest.concurrent.{IntegrationPatience, ScalaFutures}    
class EventsWebSocketSpec extends PlaySpec with WordSpecLike
      with BaseOneServerPerSuite with ApplicationTestFactory
      with ScalaFutures with IntegrationPatience {

      private implicit val httpPort = new play.api.http.Port(9000)

      ""Routes"" should {

        ""send 404 on a bad request"" in  {
          route(app, FakeRequest(GET, ""/boum"")).map(status) mustBe Some(NOT_FOUND)
        }

        ""send 200 on a good request"" in  {
          route(app, FakeRequest(GET, ""/"")).map(status) mustBe Some(OK)
        }

      }
    }
</code></pre>

<p>I get this error. Seems like the Test is not even started:</p>

<pre><code>Exception encountered when invoking run on a nested suite - org.slf4j.impl.SimpleLoggerFactory cannot be cast to ch.qos.logback.classic.LoggerContext
java.lang.ClassCastException: org.slf4j.impl.SimpleLoggerFactory cannot be cast to ch.qos.logback.classic.LoggerContext
</code></pre>

<p>Has it got anything to do with some dependency exclusion that I have to do? Here are my dependencies:</p>

<pre><code>libraryDependencies ++= Seq(
  ws,
  // Our streaming library
  ""io.monix"" %% ""monix"" % ""2.3.3"",
  ""io.monix"" %% ""monix-cats"" % ""2.3.3"",

  // Dependencies needed for Slick
  ""com.typesafe.slick"" %% ""slick"" % ""3.2.0"",
  ""com.typesafe.slick"" %% ""slick-hikaricp"" % ""3.2.0"",

  // For application Metrics
  ""io.dropwizard.metrics"" % ""metrics-core"" % ""4.0.0"",
  ""io.dropwizard.metrics"" % ""metrics-jvm"" % ""4.0.0"",

  ""com.typesafe.scala-logging"" %% ""scala-logging"" % ""3.8.0"",
  ""org.scala-lang.modules"" % ""scala-async_2.11"" % ""0.9.6"",
  ""com.typesafe"" % ""config"" % ""1.3.1"",

  // For JSON parsing
  ""com.typesafe.play"" %% ""play-json"" % ""2.6.0"",
  ""com.typesafe.play"" %% ""play-json-joda"" % ""2.6.0"",

  // JDBC driver for MySQL &amp; H2
  ""mysql"" % ""mysql-connector-java"" % ""5.1.26"",
  ""com.h2database"" % ""h2"" % ""1.4.186"",

  // Swagger UI API Docs
  ""io.swagger"" %% ""swagger-play2"" % ""1.6.0"",
  ""org.webjars"" %% ""webjars-play"" % ""2.6.0-M1"",
  ""org.webjars"" % ""swagger-ui"" % ""2.2.0"",

  // Test dependencies
  ""com.typesafe.akka"" %% ""akka-testkit"" % ""2.5.2"" % Test,
  ""org.scalatest"" %% ""scalatest"" % ""3.0.1"" % Test,
  ""org.scalatestplus.play"" %% ""scalatestplus-play"" % ""3.1.2"" % Test,
  ""com.github.andyglow"" %% ""websocket-scala-client"" % ""0.2.4"" % Test
)
</code></pre>

<p>Appreciate any help!</p>

<p>EDIT: Upon further exploration, I think the culprit is this slf4j binding:</p>

<pre><code>SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/Users/joe/.ivy2/cache/org.slf4j/slf4j-simple/jars/slf4j-simple-1.7.12.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Users/joe/.ivy2/cache/ch.qos.logback/logback-classic/jars/logback-classic-1.2.3.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.slf4j.impl.SimpleLoggerFactory]
</code></pre>

<p>How to get rid of this? I know that in my build.sbt for one of the dependency, I have to exclude the slf4j, but which one is that?</p>
",https://stackoverflow.com/questions/49082392/play-framework-2-6-error-when-unit-testing-controller-endpoints,"['logging', 'playframework-2.6']",440,TRUE,1,1
Unit testing a post method with a dynamic argument,"<p>I have a post method in my web api controller that takes a dynamic argument </p>

<pre><code> public IEnumerable&lt;Product&gt; Post([FromBody]dynamic value)
    {
        int productId;
        try
        {
            productId = Convert.ToInt32(value.productId.Value);
        }
        catch
        {

            return null;
        }
        return _data.Products.Where(y =&gt; y.Id == productId).ToList();        
    }
</code></pre>

<p>I am trying to unit test this using the Moq frame work and this is what I have</p>

<pre><code> public void PostRequestWithSingleProductTest()

    {
        var reqBody = new {productId = 1};

        var reqObject = new Mock&lt;HttpRequestMessage&gt;();
        reqObject.Setup(rq =&gt; rq.ToString()).Returns(JsonConvert.SerializeObject(reqBody));

        var response = _productController.Post(reqObject.Object);


        Assert.IsNotNull(response);
    }
</code></pre>

<p>The response is always null, and when I debug the test I can see that the value is passed is as {{productId:1}} but the compiler is not able to read this for some reason and it's throwing a <strong>Microsoft.CSharp.Runtime.Binder Exception</strong> .</p>

<p>I have marked the test assembly as a friend using assembly: <strong>InternalsVisibleTo()</strong>.</p>

<p>Please share your thoughts.</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/53194231/unit-testing-a-post-method-with-a-dynamic-argument,"['c#', 'unit-testing', 'asp.net-web-api', 'asp.net-web-api2']",1145,TRUE,1,1
Angular 6 - Unit testing a subscribe function in constructor,"<p>I've been trying to unit test the subscribe function of this service. And looking at the code coverage report generated by istanbul, I can see that this code is not covered.</p>

<h1>Code</h1>

<h2>layout.component.ts</h2>

<pre><code>import {Component, HostListener, Input} from '@angular/core';

import { LayoutService } from './layout.service';

import { some } from 'lodash';

@Component({
    selector: 'cgm-layout',
    templateUrl: './layout.component.html',
    styleUrls: ['./layout.component.scss'],
    providers: [LayoutService]
})
class LayoutComponent {

    message: any;

    constructor(
        private service: LayoutService
    ) {
        service.messagePublished$.subscribe(
            message =&gt; {
                this.setMessage(message);
            }
        );
    }

    setMessage(message): void {
        this.message = message;
        setTimeout(() =&gt; {
            this.message = null;
        }, 7000);
    }

}

export {
    LayoutComponent
};
</code></pre>

<p>This is my Unit Test</p>

<h2>layout.component.spec.ts</h2>

<pre><code>import { CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA } from '@angular/core';
import { async, ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { of } from 'rxjs';
import { LayoutComponent } from './layout.component';
import { LayoutService } from './layout.service';

describe('LayoutComponent', () =&gt; {
    let component: LayoutComponent;
    let fixture: ComponentFixture&lt;LayoutComponent&gt;;
    let service;

    beforeEach(async(() =&gt; {
        service = new LayoutService();
        mockLayoutService = jasmine.createSpyObj('LayoutService', ['messagePublished$']);
        TestBed.configureTestingModule({
            declarations: [
                LayoutComponent,

            ],
            providers: [
                LayoutService
            ],
            schemas: [
                NO_ERRORS_SCHEMA, CUSTOM_ELEMENTS_SCHEMA
            ]
        })
            .compileComponents();
    }));

    beforeEach(() =&gt; {
        fixture = TestBed.createComponent(LayoutComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();

        component.message = 'Garbage';
    });

    it('should call messagePublished', () =&gt; {
        spyOn(service.messagePublished$, 'subscribe');
        TestBed.createComponent(LayoutComponent);

        expect(service.messagePublished$.subscribe).toHaveBeenCalled();
    });

    describe('setMessage', () =&gt; {

        it('should set the Message', fakeAsync(() =&gt; {
            component.setMessage('Message');

            expect(component.message).toBe('Message');
            tick(7000);
            expect(component.message).toBeNull();
        }));

    });
});
</code></pre>

<p>So the code never seems to go over the 'service.messagePublished$.subscribe' part. Here is the <a href=""https://imgur.com/a/CIqmT9E"" rel=""nofollow noreferrer"">code coverage report</a>.</p>

<p>The error I'm getting is 'Expected spy subscribe to have been called', which I'm guessing is the error you get when that code block is not covered.</p>
",https://stackoverflow.com/questions/53260326/angular-6-unit-testing-a-subscribe-function-in-constructor,"['javascript', 'angular', 'unit-testing', 'karma-jasmine']",11788,TRUE,1,1
Patching the googleads package for unit testing with pytest,"<p>I want to test the <code>ReadAdwords</code> class method <code>get_keywords</code>. The code below works but the test throws the following error: <code>AttributeError: Mock object has no attribute 'get'</code>.</p>

<p>The <a href=""https://github.com/googleads/googleads-python-lib/blob/master/googleads/adwords.py#L393"" rel=""nofollow noreferrer"">source code</a> says that <code>GetService()</code> returns ""A googleads.common.GoogleSoapService instance which has the headers and proxy configured for use.""</p>

<p>I can't find <code>def get(</code> anywhere in the source, not just on the soap service instance that is being returned. What's going on here? Is there a way to patch this whilst still using <code>autospec=True</code>?</p>

<p>The equivalent <code>get</code> method in the PHP library is <a href=""https://github.com/googleads/googleads-php-lib/blob/master/src/Google/AdsApi/AdWords/v201809/cm/AdGroupCriterionService.php#L182"" rel=""nofollow noreferrer"">here</a>.</p>

<p>The only similar question I have found whilst searching stack overflow is <a href=""https://stackoverflow.com/questions/34501583/mocking-googleads-for-unit-tests"">this</a>.</p>

<p>The class:</p>

<pre><code>class ReadAdwords:
    def __init__(self, adwords_client):
        self.adwords_client = adwords_client

    def get_keywords(self, selector):
        ad_group_criterion_service = self.adwords_client.GetService(
            ""AdGroupCriterionService"", version=""v201809""
        )

        return ad_group_criterion_service.get(selector)
</code></pre>

<p>The test:</p>

<pre><code>@patch(""googleads.common.GoogleSoapService"", autospec=True)
@patch(""googleads.adwords.AdWordsClient"", autospec=True)
def test_get_keywords(mock_Adwords_client, mock_google_soap_service):
    read_adwords = ReadAdwords(mock_Adwords_client)

    mock_Adwords_client.GetService.return_value = mock_google_soap_service

    read_adwords.get_keywords(""a string"")

    mock_Adwords_client.GetService.assert_called_once()
    mock_google_soap_service.get.assert_called_once()
</code></pre>
",https://stackoverflow.com/questions/53446281/patching-the-googleads-package-for-unit-testing-with-pytest,"['python', 'pytest', 'google-ads-api']",124,FALSE,1,0
Unit testing an ionic3 project with external javascript dependecies,"<p>I have an ionic app that uses google maps and wicket JS libraries. 
In the index.html, I have </p>

<pre><code>&lt;script src=""assets/wicket.js""&gt;&lt;/script&gt;
&lt;script src=""http://maps.google.com/maps/api/js?key=[key]&amp;libraries=drawing,places""&gt;&lt;/script&gt;
</code></pre>

<p>and everything is working as it should when running the app in emulator or ionic serve, but when unit testing a component with a map, I am getting ""google is not defined"" error on the line </p>

<pre><code>let location = new google.maps.LatLng(0, 0);
</code></pre>

<p>I am guessing that's because I am missing the js references in the testing config, but I have no idea where and how to include them. 
Does anyone know where in the testing config to include these? (I have been following the <a href=""https://www.joshmorony.com/how-to-unit-test-an-ionic-2-application/"" rel=""nofollow noreferrer"">https://www.joshmorony.com/how-to-unit-test-an-ionic-2-application/</a> tutorial to add unit tests to my existing app). </p>

<p>Thanks,
Yuval</p>
",https://stackoverflow.com/questions/49635854/unit-testing-an-ionic3-project-with-external-javascript-dependecies,"['angular', 'google-maps-api-3', 'ionic3']",105,TRUE,1,1
How to write generic unit testing for Swift 4?,"<p>I'm trying to write some unit tests for my app (ios11, swift4, Xcode9), but all of the videos that I've seen are all too specific to the projects that the instructor is making and I'm having trouble converting it to my own classes and methods.</p>

<p>Can anyone please help me with some generic code that can be adapted to work in most situations? I'd really appreciate it.</p>
",https://stackoverflow.com/questions/51860847/how-to-write-generic-unit-testing-for-swift-4,"['ios', 'unit-testing', 'swift4']",150,FALSE,1,1
C# Comparing Multiple Objects in Unit Testing without Overriding,"<p>The following test creates error when I test tuples. </p>

<pre><code>'Assert.AreEqual(test,productRepository.GetById(1))' threw an exception of type 'NUnit.Framework.AssertionException'
</code></pre>

<p>1) How would I resolve this without overriding? Many  solutions presented below require an override equals function for each model. This is not maintainable in a 500 model+ database. Object.Equals does not work either.</p>

<p>2) I read about Autofixture, is there any special method in Nunit or recent competitors to Autofixture? (seems like Autofixture is the most popular compared to deepequals and expectedobjects). Are there other Nuget libraries?</p>

<p>These all ask to override, only one answer mentions Autofixture</p>

<ul>
<li><a href=""https://stackoverflow.com/questions/2046121/how-to-compare-two-objects-in-unit-test"">How to Compare two objects in unit test?</a></li>
<li><a href=""https://stackoverflow.com/questions/23530982/c-sharp-asserting-two-objects-are-equal-in-unit-tests"">C# - Asserting two objects are equal in unit tests</a></li>
<li><a href=""https://stackoverflow.com/questions/2920399/c-sharp-how-to-find-if-two-objects-are-equal"">c# How to find if two objects are equal</a></li>
</ul>

<p><strong>NUnit Test</strong></p>

<pre><code>[Test]
public void TestProducts()
{
    var options = new DbContextOptionsBuilder&lt;ElectronicsContext&gt;()
        .UseInMemoryDatabase(databaseName: ""Products Test"")
        .Options;

    using (var context = new ElectronicsContext(options))
    {
        //DbContextOptionsBuilder&lt;ElectronicsContext&gt; context = new DbContextOptionsBuilder&lt;ElectronicsContext&gt;()

        context.Product.Add(new Product { ProductId = 1, ProductName = ""TV"", ProductDescription = ""TV testing"", ImageLocation = ""test"" });
        context.SaveChanges();
        ProductRepository productRepository = new ProductRepository(context);
        var test = new Product
            {ProductId = 1, ProductName = ""TV"", ProductDescription = ""TV testing"", ImageLocation = ""test""};

       **//This works**
        Assert.AreEqual(""TV"", productRepository.GetById(1).ProductName);

       **//This Fails**
        Assert.AreEqual(test,productRepository.GetById(1));

       **//This Fails**
        Assert.AreEqual(Object.Equals(test, productRepository.GetById(1)), 1);
    }
</code></pre>

<p><strong>Repository</strong></p>

<pre><code>public class ProductRepository : IProductRepository&lt;Product&gt;
{
    private readonly ElectronicsContext _context;
    public ProductRepository(ElectronicsContext context)
    {
        _context = context;
    }

    public IEnumerable&lt;Product&gt; GetAllProduct()
    {
        return _context.Product.ToList();
    }

    public IQueryable&lt;Product&gt; Products =&gt; _context.Product;

    public Product GetById(int productid)
    {
        return _context.Product.Find(productid);

    }
}
</code></pre>

<p><strong>Model</strong></p>

<pre><code>public partial class Product
{
    public int ProductId { get; set; }
    public string ProductName { get; set; }
    public string ProductDescription { get; set; }
    public string ImageLocation { get; set; }

    public int? ProductCategoryId { get; set; }
    public virtual ProductCategory ProductCategory { get; set; }
}
</code></pre>
",https://stackoverflow.com/questions/52867085/c-comparing-multiple-objects-in-unit-testing-without-overriding,"['c#', 'unit-testing', 'asp.net-core', 'nunit', 'asp.net-core-2.0']",1234,TRUE,1,2
How to install Microsoft Unit Testing Framework for C++?,"<p>According to the documentation provided by Microsoft's <a href=""https://learn.microsoft.com/en-us/visualstudio/test/writing-unit-tests-for-c-cpp"" rel=""nofollow noreferrer"">Write unit tests for C/C++ in Visual Studio</a> Visual Studio includes 4 unit testing framework for C++ by default without any extra installs required. However when I try to add a unit test framework only Google Test is shown. In my second screenshot I show that I have these framework installed. How do I get Microsoft Unit Testing Framework for C++?</p>

<p><a href=""https://i.stack.imgur.com/rxLqs.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/rxLqs.png"" alt=""enter image description here""></a>
<a href=""https://i.stack.imgur.com/JhaqC.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/JhaqC.png"" alt=""screenshot of installed testing frameworks""></a></p>
",https://stackoverflow.com/questions/48554069/how-to-install-microsoft-unit-testing-framework-for-c,"['c++', 'visual-studio', 'unit-testing', 'visual-studio-2017']",299,FALSE,1,0
How to do unit testing on an aurelia module?,"<p>I'm trying to unit test a home-made NPM module of aurelia components. Note that this is not an aurelia application, it's just a repository of components and classes!</p>

<p>For this, I tried to replicate the setup of <a href=""https://github.com/aurelia/dialog"" rel=""nofollow noreferrer"">aurelia-dialog</a> but I still have a few problems that really prevent me from passing a single test in a useful way...</p>

<ol>
<li>karma is extremely slow to start: close to 1 minute before the first test runs</li>
<li>html templates for components are not served to the client although they are loaded by jasmine : I receive a 404 when the browser requests it but the karma console output shows the file loaded</li>
<li>I unfortunately have to use jquery as an npm dependency and I can't find how to load it for jasmine, which makes it impossible to even load a component using it...</li>
</ol>

<p>Thanks a lot!</p>
",https://stackoverflow.com/questions/49820278/how-to-do-unit-testing-on-an-aurelia-module,"['unit-testing', 'jasmine', 'karma-runner', 'aurelia']",489,TRUE,1,1
Unit testing a retrofit call that uses kotlin coroutines,"<p>I'm using <a href=""https://github.com/Kotlin/kotlinx.coroutines"" rel=""nofollow noreferrer"">kotlin coroutines</a> and <a href=""https://github.com/gildor/kotlin-coroutines-retrofit"" rel=""nofollow noreferrer"">kotlin retrofit coroutines</a> to do network requests in the project I'm currently working on. But I'm unable to figure out how to make my unittests for the logic pass.</p>

<p>Here's my code:</p>

<pre><code>class WorklistInteractor @Inject
    constructor(private val worklistRepository: WorklistRepository,
        private val preferenceManager: PreferenceManager)
: NetworkInteractor, WorklistDialogContract.Interactor {

    private var job = Job()

    override fun getWorklist(listener: OnWorklistResultListener) {
        job = launch(UI) {
            val result = async {
                worklistRepository.getWorklist(
                    ip = preferenceManager.worklistIp,
                    port = preferenceManager.worklistPort).awaitResult()
            }.await()

            when (result) {
            //Successful HTTP result
                is Result.Ok -&gt; listener.onWorklistResult(result.value)
            // Any HTTP error
                is Result.Error -&gt; {
                    Timber.e(result.exception, ""HTTP error with code %s}"", result.exception.code())
                    when(result.exception.code()) {
                        401 -&gt; listener.onInvalidCredentialsFailure()
                        500 -&gt; listener.internalServerError()
                        503 -&gt; listener.noServerResponseFailure()
                        else -&gt; listener.onError(result.exception.cause.toString())
                    }
                }
            // Exception while request invocation
                is Result.Exception -&gt; {
                    Timber.e(result.exception.cause, ""Exception with cause %s"", result.exception.cause.toString())
                    when(result.exception) {
                        is ConnectException -&gt; listener.connectionRefused()
                        is SocketTimeoutException -&gt; listener.failedToConnectToHost()
                        else -&gt; listener.onError(result.exception.cause.toString())
                    }
                }
            }
        }
    }

    override fun cancel() {
        job.cancel()
    }
}
</code></pre>

<p>Here's one of my unittest:</p>

<pre><code>@Test
fun `when worklistquery returns result, pass result back through listeners onWorklistResult`()
        = runBlocking {

    whenever(mWorklistRepositoryMock.getWorklist(anyString(), anyInt(), anyString()))
            .thenReturn(Calls.response(expectedWorklistResult))

    mInteractor.getWorklist(mOnWorklistResultListenerMock)

    verify(mOnWorklistResultListenerMock).onWorklistResult(expectedWorklistResult)
    verifyNoMoreInteractions(mOnWorklistResultListenerMock)
}
</code></pre>

<p>I keep getting the following message when run:</p>

<blockquote>
  <p>Wanted but not invoked:
  onWorklistResultListener.onWorklistResult(
      
  );
  -> at com.example.dialogs.worklistdialog.WorklistInteractorTest$when worklistquery returns result, pass result back through listeners OnWorklistResult()$1.doResume(WorklistInteractorTest.kt:58)</p>
  
  <p>Actually, there were zero interactions with this mock.</p>
</blockquote>
",https://stackoverflow.com/questions/48091690/unit-testing-a-retrofit-call-that-uses-kotlin-coroutines,"['android', 'unit-testing', 'kotlinx.coroutines']",1699,TRUE,1,2
Best practices for using sinon for nodeJS unit testing,"<p>I'm coming from Java experience with spring framework and looking for the most elegant way to write tests with mocks in nodejs.</p>

<p>For java its look like this:</p>

<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
public class AccountManagerFacadeTest {

    @InjectMocks
    AccountManagerFacade accountManagerFacade;

    @Mock
    IService service

    @Test
    public void test() {
        //before
                   here you define specific mock behavior 
        //when

        //then
    }
}
</code></pre>

<p>Looking for something similar for nodeJS, any suggestions? </p>
",https://stackoverflow.com/questions/53912051/best-practices-for-using-sinon-for-nodejs-unit-testing,"['node.js', 'mocking', 'sinon']",299,TRUE,1,1
How to fire Swing GUI events for Unit Testing,"<p>I'm developing a swing application using TDD. My logic is nicely decoupled and triggers by listening to focus events. But I'm not able to fire those events programatically.</p>

<p>I thought that <code>field.requestFocus()</code> would fire focusGained() but it doesn't. I've read that it might be because there's no display. </p>

<pre><code>import junit.framework.TestCase;
public class SomeClassTest extends TestCase{
    @Test
    public void testSomeMethod() {
        someLogic();
        for (JTextField field : fields[]){
            field.requestFocus();
            assertTrue(condition);
            ...
    }
</code></pre>

<p>How can I fire the FocusEvents both 'focusGained' and 'focusLost'? considering that this is for junit testing, an option without GUI would be awesome.</p>

<p>Edit: Using the pattern in the answer I've been able to fire all kind of GUI related events, hope it helps.</p>
",https://stackoverflow.com/questions/53891443/how-to-fire-swing-gui-events-for-unit-testing,"['java', 'swing', 'unit-testing', 'junit', 'tdd']",795,TRUE,1,2
handle different responses using mocha in nodejs unit testing,"<p>my test is getting <code>passed</code>(<code>200 status code</code>), when i passing correct <code>header</code> information. but when i try with <code>wrong info</code>(<code>400 status code</code>), it can't able to handle that error,</p>

<p>this is my code,(here im passing wrong headers info, so response will be status 400 code)</p>

<pre><code>const chai = require('chai');
const expect = require('chai').expect;
const chaiHttp = require('chai-http');
chai.use(chaiHttp);
const main  = require('../server');
let token;
describe('GET USER', function()  {
  this.timeout(50000);
  it('Display info about user and returns a 200 response', (done) =&gt; {
    chai.request(main)
    .get('/users')
    .set(""Authorization"","" "")
    .then(function(response) {
      // Now let's check our response
      expect(response).to.have.status(200);
      done();
    })
    .catch((err)=&gt;{
      expect(err.status).to.be.equal(400)
      done();
    })
  });
});
</code></pre>

<p>im getting error like this,</p>

<pre><code>GET USER
(node:28390) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): AssertionError: expected undefined to equal 400
    1) Display info about user and returns a 200 response

  1 failing

  1) GET USER
       Display info about user and returns a 200 response:
     Error: Timeout of 50000ms exceeded. For async tests and hooks, ensure ""done()"" is called; if returning a Promise, ensure it resolves. (/test/users.test.js)
</code></pre>
",https://stackoverflow.com/questions/51084613/handle-different-responses-using-mocha-in-nodejs-unit-testing,"['javascript', 'node.js', 'unit-testing', 'testing', 'mocha.js']",1456,TRUE,1,2
Replacement of H2 in memory database in unit testing,"<p>So this is the first time I am trying to write unit test for my sping-boot-application in java(it seems surprising but yes :D).</p>

<p>I was trying to use <strong>h2</strong> db for my unit test, But I figured out there are some restrictions of this in memory db. When I try to run my unit tests. It's showing me error like.</p>

<pre><code>2018-10-31 15:32:21.796 [] [] [Test worker] ERROR org.hibernate.tool.hbm2ddl.SchemaExport :485 - Unknown data type: ""JSON""; SQL statement:
</code></pre>

<p>I instantly jumped to google how can it possible, then I discovered that h2 db does not support <code>JSON</code> fields. Although there are some workarounds to skip the JSON data but as I am using <code>@Type</code> So, I can't using workarounds like changing to Text or something. </p>

<p>I am curious is there any other method I can use to complete my unit testing using some other in memory db.</p>
",https://stackoverflow.com/questions/53081272/replacement-of-h2-in-memory-database-in-unit-testing,"['java', 'unit-testing', 'spring-boot', 'junit', 'h2']",1488,FALSE,1,0
Unit Testing a Method That Uses a Context Manager,"<p>I have a method I would like to unit test. The method expects a file path, which is then opened - using a context manager - to parse a value which is then returned, should it be present, simple enough.</p>

<pre><code>@staticmethod
def read_in_target_language(file_path):
    """"""
    .. note:: Language code attributes/values can occur
    on either the first or the second line of bilingual.
    """"""
    with codecs.open(file_path, 'r', encoding='utf-8') as source:
        line_1, line_2 = next(source), next(source)
        get_line_1 = re.search(
            '(target-language="")(.+?)("")', line_1, re.IGNORECASE)
        get_line_2 = re.search(
            '(target-language="")(.+?)("")', line_2, re.IGNORECASE)
        if get_line_1 is not None:
            return get_line_1.group(2)
        else:
            return get_line_2.group(2)
</code></pre>

<p>I want to avoid testing against external files - for obvious reasons - and do not wish to create temp files. In addition, I cannot use StringIO in this case. </p>

<p>How can I mock the file_path object in my unit test case? Ultimately I would need to create a mock path that contains differing values. Any help is gratefully received.</p>
",https://stackoverflow.com/questions/52611692/unit-testing-a-method-that-uses-a-context-manager,"['python-3.x', 'unit-testing', 'testing', 'mocking']",237,FALSE,1,1
class not found when unit testing a custom module,"<p>I'm trying to write tests for a custom module I've written on Drupal 8 and keep getting an error and at this point I'm out of ideas. Here is the error:</p>

<p><code>Error: Class 'Drupal\mypackage\Services\Config\MyClassServiceConfig' not found
</code></p>

<p>The PhpUnit class is under </p>

<p><code>modules\custom\mypackage\tests\src\Unit\mypackageUserAuthTest</code></p>

<p>Here is the code</p>

<pre><code>class mypackageUserAuthTest extends UnitTestCase
{
    protected $user;
    protected $loginService;

    public function setUp()
    {
        parent::setUp();

        $this-&gt;loginService = new LoginService();

        $this-&gt;user = [
            'username'  =&gt; 'xxx',
            'password'  =&gt; 'xxx',
            'deviceId'  =&gt; 'xxx',
            'some-token' =&gt; 'xxx'
        ];
    }

    /** @test */
    public function that_we_can_authenticate_a_user()
    {
        $IsUserLoggedIn = $this-&gt;loginService-&gt;login($this-&gt;user['username'], $this-&gt;user['password']);

        $this-&gt;assertTrue($IsUserLoggedIn);
    }
</code></pre>

<p>Now the method <code>login</code> in <code>loginService</code> code</p>

<pre><code>&lt;?php

namespace Drupal\mypackage\Rest;

use GuzzleHttp\Exception\ClientException;

use Drupal\mypackage\Services\RestServiceFactory;
use Drupal\mypackage\Services\Config\MyClassServiceConfig;

class LoginService
{
    public function login($username, $password)
    {
        $configs = new MyClassServiceConfig(null, ""mobile"", ""v1"");
        $client  = RestServiceFactory::create($configs);

        try {
            $response = $client-&gt;post('login', [
                'json' =&gt; [
                        'username' =&gt; $username,
                        'password' =&gt; $password,
                        'deviceId' =&gt; 'onepiece',
                    ],
            ]);
            return json_decode($response-&gt;getBody(), true);
        } catch (ClientException $exception) {
            switch ($$exception-&gt;getResponse()-&gt;getStatusCode()) {
                case 402: // This only applies to co members
                    throw new SubscriptionRequiredException();
                case 403:
                    throw new BlockedAccountException();
                case 409:
                    throw new DuplicateEmailException();
                case 410:
                    throw new PasswordDoesNotExistException();
            }
            throw $exception;
        }
    }
}
</code></pre>

<p><code>pwd</code> result on <code>MyClassServiceConfig</code> class directory
<code>/var/www/cms/web/modules/custom/mypackage/src/Services/Config</code></p>

<p>But it seems to fail on the line <code>$configs = new MyClassServiceConfig(null, ""mobile"", ""v1"");</code> with the previously mentioned error :</p>

<pre><code>1) Drupal\Tests\mypackage\Unit\mypackageUserAuthTest::that_we_can_authenticate_a_user
Error: Class 'Drupal\mypackage\Services\Config\MyClassServiceConfig' not found
</code></pre>

<p>Btw, I'm using drupal-project structure (<a href=""https://github.com/drupal-composer/drupal-project"" rel=""nofollow noreferrer"">https://github.com/drupal-composer/drupal-project</a>)</p>
",https://stackoverflow.com/questions/50708123/class-not-found-when-unit-testing-a-custom-module,"['phpunit', 'drupal-modules', 'drupal-8']",1217,FALSE,1,2
get value passed to completion handler for unit testing,"<p>I'm trying to get the value passed to a completion handler to test against for unit testing.  It is not a normal setup for a completion handler since the completion handler is a var:</p>

<pre><code> typealias ResultType = Result&lt;Data&gt;
    typealias CompletionType = (ResultType) -&gt; ()

 var onCompletion: CompletionType// this is the completion handler

open override func finished(_ errors: [NSError]) {
    self.urlSession.invalidateAndCancel()

self.onCompletion(Result.failure(EComError.networkError(.notReachable)))

    }
}
</code></pre>

<p>I'm trying to compare the var: onCompletion with the </p>

<pre><code>self.onCompletion(Result.failure(EComError.networkError(.notReachable)))
</code></pre>

<p>but when I try and print the var: onCompletion after the function has been it returns:</p>

<pre><code>Optional((Function))
</code></pre>

<p>I'm trying to write a test case like this:</p>

<pre><code>   func test_finishedResult(){

        sut?.finished([NSError(code: OperationErrorCode.executionFailed)])
           XCTAssertEqual(sut?.onCompletion(Result.failure(EComError.networkError(.notReachable))), sut?.onCompletion)
    }
</code></pre>

<p>but it returns the error: </p>

<blockquote>
  <p>Cannot convert value of type 'DownloadOperation.CompletionType?' (aka
  'Optional&lt;(Result) -> ()>') to expected argument type '()?'</p>
</blockquote>

<p>where </p>

<blockquote>
  <p>DownloadOperation</p>
</blockquote>

<p>is the name of the class the function is in.</p>

<p>Whats the best way to unit test the that the var:</p>

<blockquote>
  <p>onCompletion</p>
</blockquote>

<p>is equal to<code>self.onCompletion(Result.failure(EComError.networkError(.notReachable)))</code>? </p>
",https://stackoverflow.com/questions/49864240/get-value-passed-to-completion-handler-for-unit-testing,"['ios', 'swift', 'unit-testing', 'xctest', 'completionhandler']",2593,TRUE,1,1
"Unit testing, using Moq to verify the exception message","<p>So, I have this test I have setup. It looks like this:</p>

<pre><code>[Test]
public async Task LogErrorAndReturnSuccessIfNoLines()
{
    // Assemble
    const string orderNumber = ""00000000"";
    const string lineNumber = ""001"";
    var model = new OCS { Request = new strOCS { OrderLineID = $""{orderNumber}/{lineNumber}"" } }; // NB: 12 characters means carpet
    var services = WmsContext.GivenServices();

    services.MockConfig.Setup(x =&gt; x.Live).Returns(false);
    services.MockOrderProvider.Setup(x =&gt; x.GetAsync(orderNumber, null, ""Lines.Delivery"")).Returns(Task.FromResult(services.WhenGetOrder()));

    var wmsProvider = services.WhenCreateWmsProvider();

    // Act
    var response = await wmsProvider.ReceiveOrderCompletedAsync(model);

    // Assert
    response.Should().Be(""success"");
    services.MockLogProvider.Verify(x =&gt; x.LogExceptionAsync(new Exception(""Order doesn't exist on ERP""), It.IsAny&lt;string&gt;(), It.IsAny&lt;string&gt;(), It.IsAny&lt;Dictionary&lt;string, string&gt;&gt;(), It.IsAny&lt;string&gt;(), It.IsAny&lt;string&gt;(), It.IsAny&lt;int&gt;()));
}
</code></pre>

<p>This fails because of this line:</p>

<pre><code>services.MockLogProvider.Verify(x =&gt; x.LogExceptionAsync(new Exception(""Order doesn't exist on ERP""), It.IsAny&lt;string&gt;(), It.IsAny&lt;string&gt;(), It.IsAny&lt;Dictionary&lt;string, string&gt;&gt;(), It.IsAny&lt;string&gt;(), It.IsAny&lt;string&gt;(), It.IsAny&lt;int&gt;()));
</code></pre>

<p>If I change it to this:</p>

<pre><code>services.MockLogProvider.Verify(x =&gt; x.LogExceptionAsync(It.IsAny&lt;Exception&gt;(), It.IsAny&lt;string&gt;(), It.IsAny&lt;string&gt;(), It.IsAny&lt;Dictionary&lt;string, string&gt;&gt;(), It.IsAny&lt;string&gt;(), It.IsAny&lt;string&gt;(), It.IsAny&lt;int&gt;()));
</code></pre>

<p>It passes. But I want to make sure that the message sent is exactly <strong>Order doesn't exist on ERP</strong>.
When it fails, it says this:</p>

<blockquote>
  <p>Message: Moq.MockException : 
  Expected invocation on the mock at least once, but was never performed: x => x.LogExceptionAsync(System.Exception: Order doesn't exist on ERP, It.IsAny(), It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny(), It.IsAny())
  No setups configured.</p>
</blockquote>

<p>It also states that the performed invocations are:</p>

<blockquote>
  <p>ILogProvider.LogTrace(""OCS Received"", ...</p>
</blockquote>

<p>and </p>

<blockquote>
  <p>ILogProvider.LogExceptionAsync(System.Exception: Order doesn't exist on ERP, ...</p>
</blockquote>

<p>As you can see, the second one is the one I am after.
Can anyone see what I am doing wrong?</p>

<hr>

<p>Here is my <strong>WmsContext</strong> so you can see how the Mocks are created:</p>

<pre><code>public class WmsContext
{
    public readonly Mock&lt;ICormarConfig&gt; MockConfig;
    public readonly Mock&lt;IComplaintsProvider&gt; MockComplaintsProvider;
    public readonly Mock&lt;IDistributionProvider&gt; MockDistributionProvider;
    public readonly Mock&lt;IListItemProvider&gt; MockListItemProvider;
    public readonly Mock&lt;ILogProvider&gt; MockLogProvider;
    public readonly Mock&lt;IMessageProvider&gt; MockMessageProvider;
    public readonly Mock&lt;IOrderLineProvider&gt; MockOrderLineProvider;
    public readonly Mock&lt;IOrderProvider&gt; MockOrderProvider;
    public readonly Mock&lt;IStockProvider&gt; MockStockProvider;
    public readonly Mock&lt;IProofOfDeliveryService&gt; MockProofOfDeliveryService;

    private readonly Lazy&lt;IComplaintsProvider&gt; _lazyComplaintsProvider;
    private readonly Lazy&lt;IDistributionProvider&gt; _lazyDistributionProvider;
    private readonly Lazy&lt;IListItemProvider&gt; _lazyListItemProvider;
    private readonly Lazy&lt;ILogProvider&gt; _lazyLogProvider;
    private readonly Lazy&lt;IMessageProvider&gt; _lazyMessageProvider;
    private readonly Lazy&lt;IOrderLineProvider&gt; _lazyOrderLineProvider;
    private readonly Lazy&lt;IOrderProvider&gt; _lazyOrderProvider;
    private readonly Lazy&lt;IStockProvider&gt; _lazyStockProvider;
    private readonly Lazy&lt;IProofOfDeliveryService&gt; _lazyProofOfDeliveryService;

    private WmsContext()
    {
        MockConfig = new Mock&lt;ICormarConfig&gt;();
        MockComplaintsProvider = new Mock&lt;IComplaintsProvider&gt;();
        MockDistributionProvider = new Mock&lt;IDistributionProvider&gt;();
        MockListItemProvider = new Mock&lt;IListItemProvider&gt;();
        MockLogProvider = new Mock&lt;ILogProvider&gt;();
        MockMessageProvider = new Mock&lt;IMessageProvider&gt;();
        MockOrderLineProvider = new Mock&lt;IOrderLineProvider&gt;();
        MockOrderProvider = new Mock&lt;IOrderProvider&gt;();
        MockStockProvider = new Mock&lt;IStockProvider&gt;();
        MockProofOfDeliveryService = new Mock&lt;IProofOfDeliveryService&gt;();

        _lazyComplaintsProvider = new Lazy&lt;IComplaintsProvider&gt;(() =&gt; MockComplaintsProvider.Object);
        _lazyDistributionProvider = new Lazy&lt;IDistributionProvider&gt;(() =&gt; MockDistributionProvider.Object);
        _lazyListItemProvider = new Lazy&lt;IListItemProvider&gt;(() =&gt; MockListItemProvider.Object);
        _lazyLogProvider = new Lazy&lt;ILogProvider&gt;(() =&gt; MockLogProvider.Object);
        _lazyMessageProvider = new Lazy&lt;IMessageProvider&gt;(() =&gt; MockMessageProvider.Object);
        _lazyOrderLineProvider = new Lazy&lt;IOrderLineProvider&gt;(() =&gt; MockOrderLineProvider.Object);
        _lazyOrderProvider = new Lazy&lt;IOrderProvider&gt;(() =&gt; MockOrderProvider.Object);
        _lazyStockProvider = new Lazy&lt;IStockProvider&gt;(() =&gt; MockStockProvider.Object);
        _lazyProofOfDeliveryService = new Lazy&lt;IProofOfDeliveryService&gt;(() =&gt; MockProofOfDeliveryService.Object);
    }

    public static WmsContext GivenServices() =&gt; new WmsContext();

    public IWmsProvider WhenCreateWmsProvider() =&gt;
        new WmsProvider(
            MockConfig.Object, 
            _lazyDistributionProvider, 
            _lazyLogProvider, 
            _lazyComplaintsProvider, 
            _lazyStockProvider, 
            _lazyProofOfDeliveryService, 
            _lazyMessageProvider, 
            _lazyOrderProvider, 
            _lazyOrderLineProvider, 
            _lazyListItemProvider
            );

    public OrderViewModel WhenGetOrder(params string[] lineNumbers)
    {
        var lines = lineNumbers.Select(lineNumber =&gt; new OrderLineViewModel {Id = lineNumber}).ToList();

        return new OrderViewModel
        {
            Lines = lines
        };
    }
}
</code></pre>
",https://stackoverflow.com/questions/52078545/unit-testing-using-moq-to-verify-the-exception-message,"['c#', 'nunit', 'moq']",1438,TRUE,1,1
Unit Testing with Jasmine - Can not spyOn mocked method,"<p>I am writing a javascript library that calls a method on another js lib.
Most of the time i would create a mock function of the 3rd party library and spy on it. However, it doesn't seem to work.</p>

<p>For example:</p>

<p><strong>mymain.js</strong></p>

<pre><code>export const checkForExternalFunc = () =&gt; {
  try {
   return com.externalFunc
  } catch (error) {
    return false
  }
}
</code></pre>

<p><strong>mymain_spec.js</strong></p>

<pre><code>import { checkForExternalFunc } from './src';

describe('checkForExternalFunc', () =&gt; {
 let com = com || {};
 com.externalFunc = function () {
   return true;
 };

 it('return the function when com.externalFunc is present', () =&gt; {
  spyOn(com, ""externalFunc"");

  let check = checkForExternalFunc();
  expect(check).toBe(jasmine.Any(function));
 });
})
</code></pre>

<p>and this would give me an <strong>error</strong></p>

<pre><code>ReferenceError: com is not defined
</code></pre>

<p><strong>Function in 3rd part library</strong></p>

<pre><code>var com = com || {};
com.externalFunc = function () {
   // return something
};
</code></pre>

<p>Any suggestion how i can approach this? Also i have researched a little on Stub with Sinon but not sure how to use it properly. Any help will be appreciated. Thanks!!</p>

<p>Note: I setup project with webpack + babel, karma, jasmine.</p>
",https://stackoverflow.com/questions/52299318/unit-testing-with-jasmine-can-not-spyon-mocked-method,"['javascript', 'jasmine', 'karma-jasmine']",604,FALSE,1,1
How do I run coroutines as blocking for unit testing?,"<p>I've begun writing unit tests for my MVP Android project, but my tests dependent on coroutines intermittently fail (through logging and debugging I've confirmed verify sometimes occurs early, adding <code>delay</code> fixes this of course)</p>

<p>I've tried wrapping with <code>runBlocking</code> and I've discovered <code>Dispatchers.setMain(mainThreadSurrogate)</code> from <code>org.jetbrains.kotlinx:kotlinx-coroutines-test</code>, but trying so many combinations hasn't yielded any success so far.</p>

<pre><code>abstract class CoroutinePresenter : Presenter, CoroutineScope {
    private lateinit var job: Job

    override val coroutineContext: CoroutineContext
        get() = job + Dispatchers.Main

    override fun onCreate() {
        super.onCreate()
        job = Job()
    }

    override fun onDestroy() {
        super.onDestroy()
        job.cancel()
    }
}

class MainPresenter @Inject constructor(private val getInfoUsecase: GetInfoUsecase) : CoroutinePresenter() {
    lateinit var view: View

    fun inject(view: View) {
        this.view = view
    }

    override fun onResume() {
        super.onResume()

        refreshInfo()
    }

    fun refreshInfo() = launch {
        view.showLoading()
        view.showInfo(getInfoUsecase.getInfo())
        view.hideLoading()
    }

    interface View {
        fun showLoading()
        fun hideLoading()

        fun showInfo(info: Info)
    }
}

class MainPresenterTest {
    private val mainThreadSurrogate = newSingleThreadContext(""Mocked UI thread"")

    private lateinit var presenter: MainPresenter
    private lateinit var view: MainPresenter.View

    val expectedInfo = Info()

    @Before
    fun setUp() {
        Dispatchers.setMain(mainThreadSurrogate)

        view = mock()

        val mockInfoUseCase = mock&lt;GetInfoUsecase&gt; {
            on { runBlocking { getInfo() } } doReturn expectedInfo
        }

        presenter = MainPresenter(mockInfoUseCase)
        presenter.inject(view)
        presenter.onCreate()
    }

    @Test
    fun onResume_RefreshView() {
        presenter.onResume()

        verify(view).showLoading()
        verify(view).showInfo(expectedInfo)
        verify(view).hideLoading()
    }

    @After
    fun tearDown() {
        Dispatchers.resetMain()
        mainThreadSurrogate.close()
    }
}
</code></pre>

<p>I believe the <code>runBlocking</code> blocks should be forcing all child <code>coroutineScopes</code> to run on the same thread, forcing them to complete before moving on to verification.</p>
",https://stackoverflow.com/questions/53900118/how-do-i-run-coroutines-as-blocking-for-unit-testing,"['android', 'kotlin', 'junit', 'mockito', 'kotlin-coroutines']",3094,TRUE,7,2
"GetString(IStringLocalizer, String, Object[]) returns null when Unit-Testing","<p>I have a test Class that at some point Localizes a String with using the
<code>GetString(IStringLocalizer, String, Object[])</code> Extension-Method</p>
<p>The follwing will work except for testing</p>
<pre><code>public class ClassToTest
{
    private readonly IStringLocalizer&lt;SharedResource&gt; _localizer;
    
    public AnalyticsLogic(IStringLocalizer&lt;SharedResource&gt; localizer)
    {
        _localizer = localizer;
    }
    
    public async Task&lt;string&gt; SomeMethod()
    {
        return _localizer.GetString(&quot;key&quot;, DateTime.Today));  // &quot;My Date: 31.10.2018&quot; - will return null when testing
    }       

    public async Task&lt;string&gt; SomeMethod2()
    {
        return _localizer.GetString(&quot;key&quot;);  // &quot;My Date: {0:d}&quot;
    }
}
</code></pre>
<p>This is how i built up my test:</p>
<pre><code>public class ClassToTestTest
{
    private readonly ClassToTest _testee;
    private readonly Mock&lt;IStringLocalizer&lt;SharedResource&gt;&gt; _localizerMock = new Mock&lt;IStringLocalizer&lt;SharedResource&gt;&gt;();

    public ClassToTestTest()
    {
        _testee = new ClassToTest(_localizerMock.Object);

        _localizerMock.Setup(lm =&gt; lm[&quot;key&quot;]).Returns(new LocalizedString(&quot;key&quot;, &quot;My Date: {0:d}&quot;));
    }



    [Fact]
    public async Task SomeMethod()
    {
        var result = await _testee.SomeMethod();

        Assert.Equal($&quot;My Date: {new DateTime(2018, 10, 31):d}&quot;, result);
    }

    [Fact]
    public async Task SomeMethod2()
    {
        var result = await _testee.SomeMethod2();

        Assert.Equal(&quot;My Date: {0:d}&quot;, result);
    }
}
</code></pre>
<p>Running the Test will fail with the following error:</p>
<blockquote>
<p>SomeMethod() failed</p>
<ul>
<li>Assert.Equal() Failure</li>
<li>Expected: My Date: 31.10.2018</li>
<li>Actual:   (null)</li>
</ul>
</blockquote>
<p>Usually I would simply assume the Method <code>GetString(IStringLocalizer, String, Object[])</code> not to be able to handle format strings, but since im using this in a productive environment and it works, I have no clue how this may be fixed.  To me it seems like I have properly mocked the <code>_localizer</code> dependency. Otherwise  the <code>GetString(IStringLocalizer, String)</code> would not return the format-string.</p>
<h3>Edit:</h3>
<p>For clarification:</p>
<ul>
<li>Test <code>SomeMethod()</code> will fail</li>
<li>Test <code>SomeMethod2()</code> will succeed</li>
</ul>
",https://stackoverflow.com/questions/53082384/getstringistringlocalizer-string-object-returns-null-when-unit-testing,"['c#', 'unit-testing', 'localization', 'moq', '.net-core-2.1']",2181,TRUE,0,1
Unit Testing Angular app with jQWidgets and Karma/Jasmine,"<p>If anyone has created jasmine/karma Angular tests that have jQWidgets - even if you haven't encountered this error I would like to see your karma.conf.js and .spec files, as I am having an issue. </p>

<p>I am able to ng serve the app fine - the app being little more than the starter provided by Angular - , but my .spec unit test for a component throws this error in karma:</p>

<pre><code>Failed: Unexpected value ‘undefined’ declared by the module ‘DynamicTestModule’
</code></pre>

<p>Within my spec file:</p>

<pre><code>import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { jqxGridComponent } from 'jqwidgets-scripts/jqwidgets-ts/angular_jqxgrid';

describe('AppComponent', () =&gt; {
  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [jqxGridComponent, AppComponent]
    }).compileComponents();
  }));

  it('app dummy test', () =&gt; {
    expect(1).toBe(2);
  });
});
</code></pre>

<p>app.component.ts : </p>

<pre><code>import { Component } from '@angular/core';
import { jqxGridComponent } from 'jqwidgets-scripts/jqwidgets-ts/angular_jqxgrid';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor() {}
}
</code></pre>

<p>app.module.ts  :</p>

<pre><code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';

import { jqxGridComponent } from 'jqwidgets-scripts/jqwidgets-ts/angular_jqxgrid';

@NgModule({
  declarations: [AppComponent, jqxGridComponent],
  imports: [BrowserModule],
  providers: [],
  bootstrap: [AppComponent] 
})
export class AppModule {} 
</code></pre>

<p>I would appreciate any help and/or examples of working jqWidget tests. </p>
",https://stackoverflow.com/questions/51071622/unit-testing-angular-app-with-jqwidgets-and-karma-jasmine,"['angular', 'karma-jasmine', 'jqwidget']",196,FALSE,0,1
Change Typescript import directories during compilation for unit testing,"<p>Let's say I have a directory called <code>src</code> containing a file called <code>app.ts</code></p>

<pre><code>export default function app(){
    return ""Hello World"";
}
</code></pre>

<p>I have another directory called <code>test</code> containing a file called <code>some.test.ts</code></p>

<pre><code>import ""mocha"";
import { assert } from ""chai"";
import app from ""../src/app""

describe(""Some test"", () =&gt; {
    it(""says Hello World"", function(){
        assert.equal(app(),""Hello World"");
    });
})
</code></pre>

<p>And a <code>gulpfile.js</code> for building both the production and test code:</p>

<pre><code>gulp.task(""build"", function () {
    var tsproject = ts.createProject(""tsconfig.json"");
    var tsresult = gulp.src(""./src/**/*.ts"")
        .pipe(tsproject());

    tsresult.js
        .pipe(gulpBabel({ presets: ['es2015'] }))
        .pipe(gulp.dest(""./dist""))

    tsresult.dts.pipe(gulp.dest(""./dist""));
});

gulp.task(""build-test"", [""build""], function () {
    var tsproject = ts.createProject(""tsconfig.json"");
    var tsresult = gulp.src(""./test/**/*.test.ts"")
        .pipe(sourcemaps.init())
        .pipe(tsproject());

    tsresult.js
        .pipe(gulpBabel({ presets: ['es2015'] }))
        .pipe(sourcemaps.write())
        .pipe(gulp.dest(""./dist/test""))

    tsresult.dts.pipe(gulp.dest(""./dist/test""));
});
</code></pre>

<p>My <code>tsconfig.json</code> is as follows:</p>

<pre><code>{
    ""compilerOptions"": {
        ""target"": ""es6"",
        ""forceConsistentCasingInFileNames"": true,
        ""declaration"": true,
        ""sourceMap"": true,
        ""experimentalDecorators"": true,
        ""moduleResolution"": ""node"",
        ""module"": ""es2015""
        ""rootDir"": ""src""

    }
}
</code></pre>

<p>This will compile fine, but when I try to run the test, it won't work because it is looking for <code>../dist/src/app.js</code>.</p>

<p>I want to keep my source code in the <code>src</code> folder, but I want it to be compiled into the root of the <code>dist</code> folder. At the same time, I want to keep my imports so that my IDE can find them during development, while the compiled code can find them at runtime. I assume this would involve some sort of transformation of the import statements during compilation.</p>

<p>Is this at all possible using (preferably) Gulp?</p>
",https://stackoverflow.com/questions/51967061/change-typescript-import-directories-during-compilation-for-unit-testing,"['javascript', 'node.js', 'typescript', 'gulp', 'es6-modules']",42,FALSE,0,0
Unit testing several messages in Bot Framework using Chai,"<p>I'm covering my chatbot (built with Bot Framework) by unit tests using Chai. In one case, the bot responds to a user by 2 messages. I want to check that both messages are correct. The only I found for this test not to fail is this:</p>

<pre><code>bot.on('send', (message) =&gt; {
        expect(message.text).to.satisfy(function(text) {
            if (text === message1 || text === message2 ) {
                return true;
            }
            else {
                return false;
            }
        });


    });

done();
</code></pre>

<p>As I can see through the test, the callback happens twice and the test passes when the bot functions correctly; however, the test doesn't really check whether 2 different messages were returned in correct order. </p>

<p>Is there any way to do this using Chai's <code>expect</code> or other tools?</p>
",https://stackoverflow.com/questions/51005674/unit-testing-several-messages-in-bot-framework-using-chai,"['node.js', 'unit-testing', 'botframework', 'chai']",127,TRUE,0,2
Unit testing component with @Input / @Output and reactive form,"<p>This is my component:</p>

<pre><code>import { Component, OnInit, Input, Output, EventEmitter, ChangeDetectionStrategy, OnDestroy } from '@angular/core';
import { FormBuilder, FormGroup , Validators } from '@angular/forms';
import { Subscription } from 'rxjs';
import { Values } from '../_models/values';

@Component({
  selector: 'some',
  templateUrl: './my.component.html',
  styleUrls: ['./my.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class Mycomponent implements OnInit, OnDestroy {

  @Input()
  values: Array&lt;string&gt;;

  @Output()
  selectedValues = new EventEmitter&lt;Values&gt;();

  private myForm: FormGroup;

  @Input()
  errorMsg: string;

  private selectSubscription: Subscription;

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.myForm = this.fb.group({
      'selectAll': [false],
      'values': [this.values, Validators.required]
    });

    this.selectSubscription = this.myForm.get('selectAll').valueChanges.subscribe(value =&gt; {
      this.changeSelection(value);
    });
  }

  submit(): void {
    console.log('called');

    console.log(this.myForm.value.values);

    const theSelectedValues = {
      vals: this.myForm.value.values
    };
    this.selectedValues.emit(theSelectedValues);
  }

  private changeSelection(selectAll: boolean): void {
    if (selectAll) {
      const valuesSelect = this.myForm.controls['values'];
      valuesSelect.disable();
    } else {
      this.myForm.controls['values'].enable();

    }
  }

  ngOnDestroy() {
    this.selectSubscription.unsubscribe();
  }

}
</code></pre>

<p>The template:</p>

<pre><code>&lt;form [formGroup]=""myForm"" (ngSubmit)=""submit()""&gt;
  &lt;fieldset&gt;
    &lt;mat-checkbox formControlName=""all""&gt;Select all&lt;/mat-checkbox&gt;
  &lt;/fieldset&gt;
  &lt;fieldset&gt;
    &lt;select id=""chooser"" formControlName=""values"" multiple&gt;
      &lt;option *ngFor=""let val of values?.urls"" [value]=""val""&gt;{{val}}&lt;/option&gt;
    &lt;/select&gt;
  &lt;/fieldset&gt;
  &lt;button mat-button [disabled]=""myForm.invalid""&gt;Go!&lt;/button&gt;
&lt;/form&gt;
&lt;div *ngIf=""errorMsg""&gt;{{errorMsg}}&lt;/div&gt;
</code></pre>

<p>The test</p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { Mycomponent } from './my.component';
import { By } from '@angular/platform-browser';
import { FormBuilder } from '@angular/forms';
import { NO_ERRORS_SCHEMA } from '@angular/core';

describe('Mycomponent', () =&gt; {
  let component: Mycomponent;
  let fixture: ComponentFixture&lt;Mycomponent&gt;;


  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [],
      schemas: [NO_ERRORS_SCHEMA],
      declarations: [Mycomponent],
      providers: [
        FormBuilder      ]
    })
      .compileComponents();

  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(Mycomponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });

  it('should emit selected values', () =&gt; {

    spyOn(component.selectedValues, 'emit');
    component.values = ['abc', 'de'];

    fixture.detectChanges();

    expect(fixture.debugElement.queryAll(By.css('option')).length).toBe(2); // is 0

    const formDE = fixture.debugElement.query(By.css('form'));
    formDE.triggerEventHandler('ngSubmit', {});

    // urls: null
    expect(component.selectedValues.emit).toHaveBeenCalledWith({ vals: ['abc', 'de'] });
  });
});
</code></pre>

<p>The test fails because</p>

<p>a) </p>

<pre><code>component.values = ['abc', 'de'];
</code></pre>

<p>Does not lead to the form having two option elements</p>

<p>and b)</p>

<pre><code>expect(component.selectedValues.emit).toHaveBeenCalledWith({ vals: ['abc', 'de'] });
</code></pre>

<p>Is called, but with <code>{ vals: null }</code></p>

<p>The code works, the app itself works fine, just the test is failing.</p>

<p>How do I set up the form properly, the <code>@Input</code> element?</p>

<p>I have looked at some blog posts but have not been able to adapt them to my code.</p>
",https://stackoverflow.com/questions/52000324/unit-testing-component-with-input-output-and-reactive-form,"['javascript', 'angular', 'testing', 'ngrx']",279,TRUE,0,1
query from InMemory database in .net core unit testing,"<p>i am using UseInMemoryDatabase() function in below code statement:</p>

<pre><code>var options = new DbContextOptionsBuilder&lt;CRUDContext&gt;()
            .UseInMemoryDatabase(databaseName: ""DBTest1"")
            .Options;

        // Run the test against one instance of the context
        using (var context = new CRUDContext(options))
</code></pre>

<p>now i want to query on ""DBTest1"" from SQL Server Object Explorer in VS or query on ""DBTest1"" from Microsoft SQL Server Management Studio.</p>

<p>how can i do that?</p>

<p>thanks guys.</p>
",https://stackoverflow.com/questions/53237991/query-from-inmemory-database-in-net-core-unit-testing,"['unit-testing', 'asp.net-core', '.net-core', 'in-memory-database']",223,FALSE,0,0
Jest - DOM related and across JS files Unit Testing,"<p>I am using <a href=""https://jestjs.io/"" rel=""nofollow noreferrer"">Jest</a> for Unit Testing. Added <a href=""https://github.com/smooth-code/jest-puppeteer"" rel=""nofollow noreferrer"">jest-puppeteer</a> and <a href=""https://github.com/jhnns/rewire"" rel=""nofollow noreferrer"">rewire</a> in it. The problem is when I am trying to call <code>sayHello()</code> using the below the code, <code>$button</code> variable is undefined and throws error in <code>main.js</code>. And if I call <code>someFunctionFromAnotherJS()</code>, that is also throwing error. This will return error anyway as I don't know how to write unit tests for DOM related and for across JS files. Please note I also need to use all the global variables loaded in the browser in JS files.</p>

<p>Please look at the below code and tell me how can I achieve this.</p>

<p><strong>tests/main.test.js</strong></p>

<pre><code>var rewire = require('rewire');
var main = rewire('../main');
var sayHello = main.__get__('sayHello');

describe('Testing', () =&gt; {
  beforeAll(async () =&gt; {
    await page.goto('https://***.**.com/**');
  });

  it('should test page', async () =&gt; {
    await page.type('#lid', '*****@gmail.com');
    await page.type('#pwd', '*****');
    await page.click('#signin_submit');
    var dimensions = await page.evaluate(() =&gt; {
      return {
        width: document.documentElement.clientWidth,
        height: document.documentElement.clientHeight,
        deviceScaleFactor: window.devicePixelRatio
      };
    });

    await page.goto('https://***.**.com/**', {timeout: 30000, waitUntil: 'load'});
    await page.goto('https://***.**.com/**', {timeout: 30000, waitUntil: 'load'});
    var evaluatedPage = await page.evaluate(() =&gt; {
      return {
        isFreeUser: window.isFreeUser
      };
    });
    await page.screenshot({path: 'screenshot.png'});
    console.log('Evaluated Page:', evaluatedPage);
    expect(evaluatedPage.isFreeUser).to.equal(false);

    sayHello();
  });
});
</code></pre>

<p><strong>main.js</strong></p>

<pre><code>var $button = $('#myButton');

function sayHello() {
    $button.text('Hello!');
    return someFunctionFromAnotherJS();
}
</code></pre>

<p><strong>another.js</strong></p>

<pre><code>function someFunctionFromAnotherJS() {
    return 'hello';
}
</code></pre>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/52315936/jest-dom-related-and-across-js-files-unit-testing,"['javascript', 'unit-testing', 'jestjs', 'puppeteer']",367,TRUE,0,1
Unit Testing code which uses autofac as IoC-container,"<p>I have a simple framework which will allow ""everything"" subscribe to events given that a ""Guard"" has been passed. The syntax for declaring it looks like this:</p>

<pre><code>public class MyObject : ICanHandle&lt;MySuperAwesomeEvent, GivenYouAreLeetGuard&gt; { .... }
</code></pre>

<p>The guard can be created two different ways. Either by registering in the container using this extensions method</p>

<pre><code>public static void RegisterCommandGuard&lt;TCommandGuard&gt;(this ContainerBuilder builder)
  where TCommandGuard : IExecuteGuard
 {
     var type = typeof(TCommandGuard);
     var typeName = type.FullName;
     builder.RegisterType&lt;TCommandGuard&gt;().Named(typeName, type);
 }
</code></pre>

<p>Or it will be created by using reflection during the resolvement of this component in my framework. </p>

<pre><code>public bool CanExecute(object message)
{
    object resolvedType = null;
    var name = CanExecuteGuard.FullName;
    if(!_componentContext.TryResolveNamed(name, typeof(IExecuteGuard), out resolvedType))
    {
        try
        {
            resolvedType = (IExecuteGuard)Activator.CreateInstance(CanExecuteGuard);
        }
        catch (Exception e)
        {
            throw new Exception($""Cannot locate {name} in container nor create an instance of it. See inner exception:"", e);
        }
    }

    return ((IExecuteGuard)resolvedType).CanExecute(message);
}
</code></pre>

<p>Running this in my application works as I expect, but in my tests I'm not able to resolve any of the ""Guards"".</p>

<pre><code>[Fact]
public void EventAggregator_GivenGuardWithDependencies_ShouldFireEventToAllSubscribers()
{
    var containerBuilder = new ContainerBuilder();
    containerBuilder.RegisterType&lt;UserRepository&gt;().As&lt;IUserRepository&gt;();
    containerBuilder.RegisterCommandGuard&lt;MustBeAdminGuard&gt;();
    var container = containerBuilder.Build();

    using (var lifeTimeScope = container.BeginLifetimeScope())
    {
        var eventAggregator = new ExtendedEventAggregator(lifeTimeScope);
        var @object = new ObjectWhichHandlesUsers();
        eventAggregator.Subscribe(@object);
        eventAggregator.PublishOnUIThread(new FireEmployeeCommand(userId: 1, userToFireId: 5));
        @object.UserIds.Should().HaveCount(6);
    }
}
</code></pre>

<p>The <code>TryResolveNamed</code> method in the IComponentContext will never find my registered guard. Looking at the debugger, I can clearly see that ""something"" is registered somehow</p>

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

<p>What am I doing wrong here? Other suggestions on how to improve the code is also appricated with a comment. Thanks!</p>

<p><strong>EDIT:</strong></p>

<p>During debugging of my unit test, I tried to check wheter or not the Guard had been registered by typing the following in the Immidiate Window in Visual Studio:</p>

<pre><code>lifeTimeScope.IsRegisteredWithName(""Caliburn.Micro.Demo.Tests.MustBeAdminGuard"",typeof(MustBeAdminGuard))
</code></pre>

<p>And this query returns true. What is the real difference by passing in the <code>IComponentContext</code> instead of the <code>ILifeTimeScope</code>? I thought this interface only exposed a subset of the methods exposed by <code>ILifeTimeScope</code>..</p>
",https://stackoverflow.com/questions/53846452/unit-testing-code-which-uses-autofac-as-ioc-container,"['c#', 'unit-testing', 'autofac']",157,TRUE,0,1
Unit testing multiple sequential &#39;put&#39; calls in redux saga,"<p>I have an already written saga which had 4-5 yield in it and appropriate unit tests written for it. But now as part of a defect correction, I had to add another yield put(actionA)(A) effect just before the last yield put(actionB)(B) effect in the saga. So, as expected one of my test cases is failing which tested (B) previously.</p>

<p>So, since I am just adding another yield to the saga, to make my previous tests run correctly, I just added another generator.next() call to the unit test, to make it go to the last yield. But for some reason that doesn't rectify it. </p>

<p>Is there something which I need to do different when adding one more yield put(action) effect?</p>

<p>Sorry if I am not able to show a lot of code and can only explain conceptually, because I don't have the code in front of me right now but need an answer for this. So any help would be appreciated.</p>
",https://stackoverflow.com/questions/48975252/unit-testing-multiple-sequential-put-calls-in-redux-saga,['redux-saga'],645,FALSE,1,1
ASP.NET Web API Unit Testing : Control database identity increase,"<p>I have one API project created using ASP.NET Web API 2.0. At the back end I've used SQL database for storage. There is one API which is inserting record in one table, let's call that table as 'X'. I've also created one <em>API client</em> to facilitate interaction with API. Now I am writing integration tests for this <em>API client</em>. </p>

<p><strong><em>Problem:</em></strong></p>

<p>Integration tests will run several times daily and if any test fails, email notification will be sent to admin. Table 'X' has identity set for it's primary key, thus for every insert, identity is going to increase. So if integration test for insert API is running continuously, this identity will increase with overwhelming rate. I can delete entries created by tests, but how can I control unwanted increase in identity caused due to integration tests?</p>
",https://stackoverflow.com/questions/48863942/asp-net-web-api-unit-testing-control-database-identity-increase,"['sql', 'asp.net', 'asp.net-mvc', 'asp.net-web-api2', 'integration-testing']",43,TRUE,1,1
Unit Testing Angular components with rxjs Subjects using Jasmine,"<p>I have two components and a service layer. The service layer has a subject declared in it with a set and get method definition. The first component, based on an user action calls the set method of the subject while the second component is subscribed to the same subject. It works just fine but when I try to unit test the subscription in second component, I'm having trouble with the approach. I have a mock service layer created to test other functionalities as well. </p>

<p>The subscription inside ngOnit is not getting hit during the test run. Code executes within the subscribe when component initializes but not after setSubject is invoked. When I debug, I can see that it hits after the execution is complete but I have no way to verify if data is updated.</p>

<pre><code>export class MockService {
 private subject = new Subject&lt;any&gt;();

 getSubject() {
   return Observable.of(this.subject);
 }

 setSubject(value) {
   this.subject.next({ message: value });
 }

}
</code></pre>

<p>Component 2</p>

<pre><code>export class Component2 implements OnInit {
  textFromComponent1: string;
  subscription: Subscription;

  constructor(public service: Service) {}
  ngOnInit() {
    this.subscription = this.service.getSubject().subscribe(message =&gt; {
      this.textFromComponent1 = message.value;
    });
  }
}
</code></pre>

<p>Component 2 Unit Test</p>

<pre><code>beforeEach( async(() =&gt; {
    TestBed.configureTestingModule( {
        declarations: [Component2],
        schemas: [CUSTOM_ELEMENTS_SCHEMA],
        providers: [{ provide: Service, useClass: MockService }]
    } )
        .compileComponents();
} ) );
beforeEach(() =&gt; {
    fixture = TestBed.createComponent( Component2 );
    component = fixture.componentInstance;
    fixture.detectChanges();
});
it('should test subscription' () =&gt; {
   component.service.setSubject(""abc"");
   expect(component.textFromComponent1).toBe(""abc"");
});
</code></pre>
",https://stackoverflow.com/questions/52263178/unit-testing-angular-components-with-rxjs-subjects-using-jasmine,"['angular', 'unit-testing', 'jasmine', 'rxjs', 'karma-jasmine']",755,FALSE,1,1
iOS Unit Testing Bundle: Why Is The App Launched?,"<p>I have added a Unit Test target and a UI Test target to my application project. When I run the Unit Tests my application is launched. When I run the UI Tests a ""special Runner version"" of my application is launched. I (barely) understand that the runner version is for producing user actions. But why is my app launched when the unit tests are run? The implication is that my unit tests can interact with the running application but that does not seem to be the case. The whole XCTest environment is new to me. Any clarifications would be just great. Thanks.</p>
",https://stackoverflow.com/questions/49366624/ios-unit-testing-bundle-why-is-the-app-launched,"['unit-testing', 'xcode9', 'xctest']",34,FALSE,0,1
Salesforce - unit testing for custom fields for Account object,"<p>Suppose in <code>Account</code> object, it have 3 custom fields, there are <code>invoice_delivery_method</code>, <code>invoice_delivery_email</code> and <code>invoice_delivery_print</code>. For <code>invoice_delivery_method</code>, the type is picklist, and the possible values are <code>Email</code>, <code>Email and Print</code>, <code>Print</code> and <code>Other</code>. The rest of two custom fields are checkbox, and default to unchecked, which is <code>false</code>.</p>

<p>Now when user update the <code>invoice_delivery_method</code> field to <code>Email</code>, (either by Salesforce account page or by SOQL), the <code>invoice_delivery_email</code> is set to <code>true</code>, and <code>invoice_delivery_print</code> is set to <code>false</code>.</p>

<p>The way I did is create a trigger class like following:</p>

<pre><code>trigger InvoiceDeliveryMethodTrigger on Account (before update) {
    InvoiceDeliveryMethodTriggerHandler.handleBeforeUpdate(Trigger.new);
}
</code></pre>

<p>Inside the handler class I did following:</p>

<pre><code>public class InvoiceDeliveryMethodTriggerHandler {
    public static void handleBeforeUpdate(Account[] accounts){
        RecordType recordType = [select Id from RecordType where sobjecttype = 'Account' and Name =: MSSP_Settings__c.getOrgDefaults().Account_Record_Type__c];  
        for (Account account : accounts) {
            if(account.RecordTypeId == recordType.Id) {
                System.debug('Information for Account: ' + account);
                System.debug('Information for Invoice Delivery Method: ' + account.Invoice_Delivery_Method__c);
                account.Invoice_Delivery_Email__c = false;
                account.Invoice_Delivery_Print__c = false;
                String delivery_method = account.Invoice_Delivery_Method__c;
                System.debug('String is not blank ' + String.isNotBlank(delivery_method));
                if (String.isNotBlank(delivery_method)){
                    if (delivery_method.equals('Email')){
                        account.Invoice_Delivery_Email__c = true;
                        account.Invoice_Delivery_Print__c = false;
                    }
                    else if (delivery_method.equals('Email and Mail')){
                        account.Invoice_Delivery_Email__c = true;
                        account.Invoice_Delivery_Print__c = true;
                    }
                    else if (delivery_method.equals('Mail')){
                        account.Invoice_Delivery_Email__c = false;
                        account.Invoice_Delivery_Print__c = true;                   
                    }  
                }
            }
        }
    }
}
</code></pre>

<p>I also have one trigger class on <code>Account</code> after update, but I didn't change any value for that 3 custom field.</p>

<p>If I test via application, it seems that two custom field is got updated based on the value of <code>invoice_delivery_method</code>. But I got problems for my unit testing.</p>

<p>Here is the unit test class I wrote</p>

<pre><code>    @isTest
    private class InvoiceDeliveryMethodTest {
        @isTest(SeeAllData=true)
        static void testAccountEmailSelected(){
            Account testAccount = new Account();
            // populating some of the mandatory field for Account
            testAccount.Invoice_Delivery_Method__c = 'Other';
            insert testAccount;        


            Account acct = [Select Id, Invoice_Delivery_Method__c, Invoice_Delivery_Email__c, Invoice_Delivery_Print__c from Account 
                            where Id =: testAccount.Id];
            acct.Invoice_Delivery_Method__c = 'Email';
            update acct;
            acct = [Select Id, Invoice_Delivery_Method__c, Invoice_Delivery_Email__c, Invoice_Delivery_Print__c from Account 
                    where Id =: testAccount.Id];    
            System.assertEquals('Email', acct.Invoice_Delivery_Method__c);
            System.assert(acct.Invoice_Delivery_Email__c);
            System.assert(!acct.Invoice_Delivery_Print__c);
            delete testAccount;

        }
}
</code></pre>

<p>When I run the test case, it fail on <code>System.assert(acct.Invoice_Delivery_Email__c);</code></p>

<p>That fields still <code>false</code>. Why this happen?</p>
",https://stackoverflow.com/questions/51031191/salesforce-unit-testing-for-custom-fields-for-account-object,['salesforce'],1128,FALSE,0,2
Unit Testing Remove one Item in my Mock Database,"<p>I am on learning unit testing and have a question.</p>

<p>I mocked my class ApplicationDbContext with my data.</p>

<p>Now I would like to delete an item from my data. :(</p>

<p>The first Test passed but the second failed it still shows me 20 items</p>

<p>Can anyone help me?</p>

<p><strong>My classe IApplicationDbContext :</strong></p>

<pre><code>    public interface IApplicationDbContext : IDisposable
{
    IDbSet&lt;OrderingEquipment&gt; OrderingEquipments { get; set; }
    int SaveChanges();
    Task&lt;int&gt; SaveChangesAsync();
}
</code></pre>

<p><strong>My classe ApplicationDbContext:</strong></p>

<pre><code>    public class ApplicationDbContext : DbContext, IApplicationDbContext
{
    public virtual IDbSet&lt;OrderingEquipment&gt; OrderingEquipments { get; set; }

    public ApplicationDbContext() : base(""DefaultConnection"")
    {
    }
}
</code></pre>

<p><strong>My classe OrderingEquipment:</strong></p>

<pre><code>    public class OrderingEquipment
{
    [Key]
    public Guid Guid { get; set; }
    public string Text { get; set; }
    public byte?[] xDEHFile { get; set; }
    public string xDEHFileName { get; set; }
    public DateTime Timestamp { get; set; }

    public string ModelToString()
    {
        return string.Format(""Guid: {0}, Text: {1}, xDEHFile: {2}, xDEHFileName: {3} Timestamp: {4}"", Guid, Text, xDEHFile, xDEHFileName, Timestamp);
    }
}
</code></pre>

<p><strong>My Controller Methode:</strong></p>

<pre><code>public void Remove(OrderingEquipment orderingEquipments)
    {
        if (orderingEquipments == null)
        {
            //throw exception oder ein Result?
            throw new ArgumentNullException(""orderingEquipmentsCointener is null"");
        }

        try
        {
            using (db)
            {
                //orderingEquipments.ForEach(x =&gt; log.Error(""Removed: "" + x.ModelToString()));
                var itemToRemove = db.OrderingEquipments.Find(orderingEquipments.Guid);
                db.OrderingEquipments.Remove(itemToRemove);
                db.SaveChanges();
            }
        }
        catch (Exception e)
        {
           // orderingEquipments.ForEach(x =&gt; log.Error(x.ModelToString(), e));
        }
    }
</code></pre>

<p><strong>My Unit Tests</strong></p>

<pre><code>public class OrderingEquipmentControllerTests
{

    private IDbSet&lt;OrderingEquipment&gt; dbSet;
    private IApplicationDbContext dbContext;
    private OrderingEquipmentController controller;

    [SetUp]
    public void Initialize()
    {
        // Create test product data
        var orderingEquipments = Builder&lt;OrderingEquipment&gt;.CreateListOfSize(20)
            .All()
            .With(p =&gt; p.Guid = Guid.NewGuid())
            .With(p =&gt; p.Timestamp = DateTime.UtcNow.AddMonths(new Random().Next(1)))
            .With(p =&gt; p.Timestamp = DateTime.UtcNow.AddDays(new Random().Next(2)))
            .TheFirst(5)
            .With(p =&gt; p.Text = ""First five"")
            .Build()
            .AsQueryable();

        dbSet = Substitute.For&lt;IDbSet&lt;OrderingEquipment&gt;&gt;();
        dbSet.Provider.Returns(orderingEquipments.Provider);
        dbSet.Expression.Returns(orderingEquipments.Expression);
        dbSet.ElementType.Returns(orderingEquipments.ElementType);
        dbSet.GetEnumerator().Returns(orderingEquipments.GetEnumerator());
        dbSet.Find(Arg.Any&lt;object[]&gt;()).Returns(callinfo =&gt;
        {
            object[] idValues = callinfo.Arg&lt;object[]&gt;();
            if (idValues != null &amp;&amp; idValues.Length == 1)
            {
                Guid requestedId = (Guid)idValues[0];
                return orderingEquipments.FirstOrDefault(p =&gt; p.Guid == requestedId);
            }

            return null;
        });

        dbContext = Substitute.For&lt;IApplicationDbContext&gt;();
        dbContext.OrderingEquipments.Returns(dbSet);

        controller = new OrderingEquipmentController(dbContext);
    }

    [Test()]
    public void GetAllOrderingEquipmentsTest()
    {
        var items = controller.GetAllOrderingEquipments();

        Assert.That(items.Count, Is.EqualTo(20));
    }

    [Test()]
    public void RemoveOneOrderingEquipment()
    {
        var items = controller.GetAllOrderingEquipments();
        controller.Remove(items.First());


        Assert.That(items.Count, Is.EqualTo(19));
    }
}
</code></pre>
",https://stackoverflow.com/questions/48580332/unit-testing-remove-one-item-in-my-mock-database,"['c#', '.net', 'nunit', 'tdd', 'nsubstitute']",1915,FALSE,0,1
"Unit testing strategy in Scala with Try, Success, Failure","<p>For the sake of simplicity suppose we have a method called <code>listTail</code> which is defined in the following way:</p>

<pre><code>private def listTail(ls: List[Int]): List[Int] = {
 ls.tail
}
</code></pre>

<p>Also we have a method which handles the exception when the list is empty.</p>

<pre><code>private def handleEmptyList(ls: List[Int]): List[Int] = {
 if(ls.isEmpty) List.empty[Int]
}
</code></pre>

<p>Now I want to create a safe version of the <code>listTail</code> method, which uses both methods:</p>

<pre><code>import scala.util.{Try, Success, Failure}

def safeListTail(ls: List[Int]): List[Int] = {
 val tryTail: Try[List[Int]] = Try(listTail(ls))
 tryTail match {
   case Success(list) =&gt; list
   case Failure(_) =&gt; handleEmptyList(ls)
 }
}
</code></pre>

<p>My question is, if the two private methods are already tested, then should I test the safe method as well? And if yes, how? 
I was thinking just to check if the pattern matching cases are executed depending on the input. That is, when we hit the Failure case then the <code>handleEmptyList</code> method is executed. But I am now aware of how to check this.</p>

<p>Or do I need to refactor my code, and put everything in a single method? Even though maybe my private methods are much more complex than this in the example.</p>

<p>My test are written using ScalaTest. </p>
",https://stackoverflow.com/questions/53189883/unit-testing-strategy-in-scala-with-try-success-failure,"['scala', 'unit-testing', 'scalatest']",576,TRUE,0,2
How to get the Values from a Task&lt;IActionResult&gt; returned through an API for Unit Testing,"<p>I have created an API using ASP.NET MVC Core v2.1. One of my <code>HttpGet</code> methods is set up as follows:</p>

<pre><code>public async Task&lt;IActionResult&gt; GetConfiguration([FromRoute] int? id)
{
    try
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        ..... // Some code here

        return Ok(configuration);
    }
    catch (Exception ex)
    {
        ... // Some code here
    }
}
</code></pre>

<p>When unit testing this I can check that Ok was the response, but I really need to see the values of the configuration. I don't seem to be able to get this to work with the following:</p>

<pre><code>[TestMethod] 
public void ConfigurationSearchGetTest()
{
    var context = GetContextWithData();
    var controller = new ConfigurationSearchController(context);
    var items = context.Configurations.Count();
    var actionResult = controller.GetConfiguration(12);

    Assert.IsTrue(true);
    context.Dispose();
}
</code></pre>

<p>At runtime, I can check that <code>actionResult</code> has certain values that I am unable to code for. Is there something I am doing wrong? Or am I just thinking about this wrong? I would like to be able to do:</p>

<pre><code>Assert.AreEqual(12, actionResult.Values.ConfigurationId);
</code></pre>
",https://stackoverflow.com/questions/50801094/how-to-get-the-values-from-a-taskiactionresult-returned-through-an-api-for-uni,"['c#', '.net-core', 'asp.net-core-mvc']",66698,TRUE,42,5
Unit Testing - how to properly calculate expected value for assertion,"<p>I am new in unit testing and I was just wondering what if a method internally calls its own public methods to calculate the return value like following: </p>

<pre><code>public Integer getTotalBeforeSubscriptionDiscount() {
  return getTotal() + getSubscriptionSavings()
}
</code></pre>

<p>I am writing unit test for it and my question is: Should I use specific integer values for matching the result the result with expectations e.g</p>

<pre><code>Integer expected = 10;
Integer actual = obj.getTotalBeforeSubscription();
assertEquals(expected, actual);
</code></pre>

<p>OR
is it allowed to call public methods and calculate expected value at runtime like following:</p>

<pre><code>Integer expected = obj.getTotal() + obj.getSubscriptionSavings();
assertEquals(expected, obj.getTotalBeforeSubscription());
</code></pre>
",https://stackoverflow.com/questions/51387772/unit-testing-how-to-properly-calculate-expected-value-for-assertion,"['java', 'unit-testing', 'junit']",2036,TRUE,6,2
Unit testing JAX-RS/Jersey servlet with Guice Injections,"<p>I have an application that uses Jersey/JAX-RS for web services (annotations, etc) and Guice to inject service implementations. I don't really like the way Guice works with servlets directly, I prefer the Jersey way, so I had to do a bit of fussing to get the service injections to work since Guice wouldn't be creating my servlet classes, and I didn't want to deal with the HK2-Guice bridge. I did this by creating a listener class (called Configuration) that sets up the injectors in static fields upon application startup and then manually effecting the injections in each servlet class by creating a parent class that all my servlets extend with a constructor that contains the following:</p>

<pre><code>public MasterServlet() {
    // in order for the Guice @Inject annotation to work, we have to create a constructor
    // like this and call injectMembers(this) on all our injectors in it
    Configuration.getMyServiceInjector().injectMembers(this);
    Configuration.getDriverInjector().injectMembers(this);
}
</code></pre>

<p>I know it's kind of hacky, but this works just fine in my servlets. I can use the Guice @Inject annotations on my services and switch between named implementations and so on. The problem comes when I go to set up my unit tests. I'm using JerseyTest to do my tests, but running a test against my servlets results in a 500 error with Guice saying the following:</p>

<blockquote>
  <p>com.google.inject.ConfigurationException: Guice configuration errors:
  1) No implementation for com.mycompany.MyService was bound.
    while locating com.mycompany.MyService
      for field at com.mycompany.servlet.TestGetServlet.service(TestGetServlet.java:21)
    while locating com.mycompany.servlet.TestGetServlet</p>
</blockquote>

<p>The test looks like this:</p>

<pre><code>public class TestServletTest extends JerseyTest {

    @Test
    public void testServletFunctional() {
        final String response = target(""/testget"").request().get(String.class);
        assertEquals(""get servlet functional"", response);
    }

    @Before
    public void setup() {
        Configuration configuration = new Configuration();
        configuration.contextInitialized(null);
    }

    @Override
    protected Application configure() {
        return new ResourceConfig(TestGetServlet.class);
    }
}
</code></pre>

<p>You'll notice in the setup method I am manually creating my Configuration class since I can't rely on the test container (Grizzly) to create it (I get NullPointerExceptions without those two lines). More about this below.</p>

<p>And here's the servlet being tested:</p>

<pre><code>@Path(""/testget"")
public class TestGetServlet extends MasterServlet {

    @Inject
    MyService service;

    @GET
    @Produces({""text/plain"", MediaType.TEXT_PLAIN})
    public String testGet() {
        //service = Configuration.getServiceInjector().getInstance(MyService.class);
        return ""get servlet functional"";
    }
}
</code></pre>

<p>Notice the commented line in the testGet() method? If I do that instead and remove the @Inject annotation above, everything works fine, which indicates that Grizzly is not creating my servlets the way I expect.</p>

<p>I think what's happening is that Grizzly doesn't know about Guice. Everything seems to suggest that Grizzly isn't seeing the Configuration class, despite the fact that by putting it in my test's @Before method it seems to be at least <em>available</em> to the classes that use it (see: the commented line in the TestGetServlet class). I just don't know how to fix it.</p>
",https://stackoverflow.com/questions/51913345/unit-testing-jax-rs-jersey-servlet-with-guice-injections,"['java', 'servlets', 'guice', 'jersey-2.0', 'jersey-test-framework']",642,TRUE,0,1
Angular 6 Unit testing: change pristine in reactive form,"<p>Recently sorry if it's a duplicate of any questiom. I didn't find any solution for my problem.</p>

<p>So I have a form with one input field. When I'm fetching data in <code>onInit</code> I put the value inside this field and make it pristine. After I change value manually form becomes dirty and I make some actions.</p>

<p>It works in component but I can't properly test it. After I make <code>setValue()</code> for input field it stayed pristine (in test). But I need to emulate the real input and forms pristine should becomes <code>false</code>.</p>

<p>component.ts</p>

<pre><code>ngOnInit() {
    this.form = this.fb.group({
        speed: this.fb.control(null)
    });

    this.service.getData().pipe(takeUntil(this.destroyed$))
        .subscribe(info =&gt; {
            this.info = info;
            this.updateForm();
        });
}


updateForm() {
    this.form.patchValue({
        speed: this.info.speed
    });
    this.form.get('speed').setValidators([
        Validators.required,
        Validators.pattern('^[0-9]*$'),
    ]);
    this.form.markAsPristine();
}
</code></pre>

<p>component.spec.ts</p>

<pre><code>beforeEach(() =&gt; {
    fixture = TestBed.createComponent(component);
    component = fixture.componentInstance;
    fixture.detectChanges();
});

it('should create', () =&gt; {
    expect(component).toBeTruthy(); // passed
});

it('should make form dirty', () =&gt; {
    component.info = generateInfo();
    fixture.detectChanges();
    component.updateForm();
    fixture.whenStable().then(() =&gt; {
        expect(component.form.pristine).toBeTruthy();
        expect(component.form.get('speed').value).toBe(20);
        component.form.controls['speed'].setValue(10);
        expect(component.form.pristine).toBeFalsy();  //error Expected true to be falsy.
    });
});
</code></pre>
",https://stackoverflow.com/questions/53914523/angular-6-unit-testing-change-pristine-in-reactive-form,"['angular', 'typescript', 'unit-testing', 'angular-reactive-forms']",4775,TRUE,0,1
Getting nullPointer in unit testing of spring boot service,"<p>Suppose i want to write unit testcases for this method </p>

<pre><code>@Service
public class OfferServiceImpl implements OfferService {

@Autowired
OfferRepository OfferRepository;

@Override
public List&lt;Offer&gt; getAllOffers() {
    return OfferRepository.findAll();
}
</code></pre>

<p>i tried writing by two ways..</p>

<p>first is </p>

<pre><code>@RunWith(MockitoJUnitRunner.class)
public class OfferServiceTest {

@Mock
private OfferRepository offerRepositoryMock;

@InjectMocks
private OfferServiceImpl offerServiceImpl;




    @Test
        public void getAllOffersTest() {
            List&lt;Offer&gt; offerList=new ArrayList&lt;&gt;();
            offerList.add(new Offer(""SE"",new Date(), 10));
 //line number 47 --&gt;&gt;when(offerRepositoryMock.findAll()).thenReturn(offerList);
            assertNotNull(offerServiceImpl.getAllOffers());
            assertEquals(offerList, offerServiceImpl.getAllOffers());
        }
</code></pre>

<p>and 2nd is</p>

<pre><code>@RunWith(SpringRunner.class)
@SpringBootTest(classes = OfferServiceImpl.class) 
public class OfferServiceTest {

private OfferRepository offerRepositoryMock;
private OfferServiceImpl offerServiceImpl;


@Before
public void setUp() {
    offerRepositoryMock = Mockito.mock(OfferRepository.class);
    offerServiceImpl = new OfferServiceImpl();
}


@Test
public void getAllOffersTest() {
    List&lt;Offer&gt; offerList=new ArrayList&lt;&gt;();
    offerList.add(new Offer(""SE"",new Date(), 10));
    when(offerRepositoryMock.findAll()).thenReturn(offerList);
    assertNotNull(offerServiceImpl.getAllOffers());
    assertEquals(offerList, offerServiceImpl.getAllOffers());
}
</code></pre>

<p>Below exception i am getting in both ways
tried adding setUp also but getting the same exception</p>

<pre><code>   FAILED: getAllOffersTest
java.lang.NullPointerException
    at com.singh.recruitsystem.service.OfferServiceTest.getAllOffersTest(OfferServiceTest.java:47)
    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.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
    at org.testng.TestRunner.privateRun(TestRunner.java:767)
    at org.testng.TestRunner.run(TestRunner.java:617)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
    at org.testng.SuiteRunner.run(SuiteRunner.java:240)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
    at org.testng.TestNG.run(TestNG.java:1057)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
</code></pre>

<p>what is difference b/w both ways and how to resolve nullPOinter ecception.
i want to test this as a standalone. what should be my correect way of writting unit test cases for this.</p>
",https://stackoverflow.com/questions/52868669/getting-nullpointer-in-unit-testing-of-spring-boot-service,"['java', 'spring', 'unit-testing', 'spring-boot', 'testng']",2621,FALSE,0,5
"Simple definition of stub, spy, fake and mock in unit testing","<p>I'm quite new to unit testing. I've read around on here as well as done some Googling, but am still a bit confused as to the meaning of each of the four meanings. I came across the following definition which help....</p>
<blockquote>
<p>Stub - stubs are minimal implementations of interfaces or base classes</p>
<p>Spy - a spy will record which members were invoked</p>
<p>Fake - more complex, a fake may resemble a production implementation</p>
<p>Mock - A mock is usually dynamically created by a mock library and depending on its configuration, a mock can behave like a dummy, a stub, or a spy</p>
</blockquote>
<p>However, I'd like to simplify the meaning (if possible) and ask a few questions.</p>
<ol>
<li>Do all of the above only relate to functions, or can they be objects or any other type?</li>
<li><strong>Stub</strong> - Is Stubbing bascially a way to provide dummy info instead of making the calling to the actual database? So for example, if I had an API call, instead of actually making a call to the API, I just instead make a GET request to a JSON file which is in my <em>tests</em> folder which has some dummy data in, and use that instead of making the API call?</li>
<li><strong>Spy</strong> - so is this a way of tracking what happens to a function for example. Meaning you follow when it's called, where it gets passed around to?</li>
<li><strong>Fake</strong> - Is this for example a function which you create inside the test file to mimic the real function or be a simpified version of the actual function?</li>
</ol>
<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/52131231/simple-definition-of-stub-spy-fake-and-mock-in-unit-testing,['unit-testing'],4773,TRUE,12,2
Unit Testing AngularJS &#39;config&#39; Written in TypeScript using Jasmine,"<p>I'm currently trying to Unit Test the <code>config</code> of a new AngularJS component. We are using <code>ui-router</code> to handle the routing in our application. We have been able to successfully test it for all our previous components, but the code for all of them was written in plain Javascript. Now that we switched to TypeScript we are having some issues.</p>

<p>This is the TypeScript code where we make the configuration of the module:</p>

<pre><code>'use strict';

// @ngInject
class StatetiworkpaperConfig {

    constructor(private $stateProvider: ng.ui.IStateProvider) {
        this.config();
    }

    private config() {
        this.$stateProvider
            .state('oit.stateticolumnar.stateticolumnarworkpaper', {
                url: '/stateticolumnarworkpaper',
                params: { tabToLoad: null, groupTabId: null, jurisdiction: null, showOnlyItemsWithValues: false, showOnlyEditableItems: false},
                template: '&lt;stateticolumnarworkpaper-component active-tab-code=""$ctrl.activeTabCode""&gt;&lt;/stateticolumnarworkpaper-component&gt;',
                component: 'stateticolumnarworkpaperComponent',
                resolve: {
                    onLoad: this.resolves
                }
            });
    }

    //@ngInject
    private resolves($q, $stateParams, ColumnarWorkpaperModel, ChooseTasksModel, localStorageService) {
        // Some not important code
    }
}

angular
    .module('oit.components.batch.batchprocess.stateticolumnar.stateticolumnarworkpaper')
    .config([""$stateProvider"", ($stateProvider) =&gt; {
        return new StatetiworkpaperConfig($stateProvider);
    }]);
</code></pre>

<p>This is the Spec file, which is written in Javascript:</p>

<pre><code>describe('oit.components.batch.batchprocess.stateticolumnar.stateticolumnarworkpaper', function () {

    beforeEach(module('oit.components.batch.batchprocess.stateticolumnar.stateticolumnarworkpaper'));
    beforeEach(module('oit'));

    var state = 'oit.stateticolumnar.stateticolumnarworkpaper';

    it('has a route', inject(function ($state) {
        var route = $state.get(state);
        expect(route.url).toBe('/stateticolumnarworkpaper');
    }));
});
</code></pre>

<p>My issue is when executing the line <code>var route = $state.get(state)</code>, as the <code>route</code> variable is always null. I could verify that the <code>config()</code> method is being executed, but I'm simply out of ideas as to why <code>route</code> is always null on my test.</p>

<p>Just for reference, this is the configuration of another component, but using Javascript</p>

<pre><code>'use strict';

angular
    .module('oit.components.binders.binder.dom_tas.taxaccountingsystem.stateworkpapers.stateworkpapersreview')
    .config(stateworkpapersreviewConfig);

function stateworkpapersreviewConfig($stateProvider) {
    $stateProvider
        .state('oit.binder.taxaccountingsystem.stateworkpapersreview', {
            url: '/stateworkpapersreview?reviewType&amp;binderId&amp;year&amp;jurisdiction&amp;chartId&amp;withBalance',
            templateUrl: 'components/binders/binder/dom_tas/taxaccountingsystem/stateworkpapers/stateworkpapersreview/stateworkpapersreview.tpl.html',
            controller: 'StateworkpapersreviewController',
            controllerAs: 'stateworkpapersreviewCtrl',
            resolve: {
                onLoad: resolves
            }
        });

    function resolves($q, $stateParams, StateTiBinderJurisdictionsModel, WorkpaperModel, localStorageService, StateTiFiltersModel) {
        // Some not important code
    }
}
</code></pre>

<p>As you can see the code is basically the same, but still, I can successfully test this component's <code>config</code> in the way I described, but when I try with the one written in TypeScript I get the error I mentioned.</p>

<p>PD: I'm aware of several similar posts (like <a href=""https://stackoverflow.com/questions/30316334/testing-stateprovider-state-if-configured-in-config-in-angularjs-returns-null-on"">this</a> one), but none of them deal with TypeScript, which is my issue. </p>
",https://stackoverflow.com/questions/50299603/unit-testing-angularjs-config-written-in-typescript-using-jasmine,"['angularjs', 'typescript', 'jasmine', 'angular-ui-router', 'config']",50,FALSE,0,1
Generate HTML Report after running django unit testing testcases,"<p>I am newbie to djnago and python, I want to generate the report of testcases run by djnago  and send in mail to team.</p>

<p>Please help me </p>
",https://stackoverflow.com/questions/48809217/generate-html-report-after-running-django-unit-testing-testcases,"['django', 'python-3.x', 'unit-testing']",725,FALSE,-3,1
Unit testing with SpringJUnit4ClassRunner using only @Component and @Autowired,"<p>I have the following class:</p>

<pre><code>@Component
public class MyClass {
    @Autowired MyPojo pojo;
}
</code></pre>

<p>How do i test it without mocking the injected beans? I <strong>do not</strong> have a configuration [XML or declarative].
I have done the following:</p>

<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@ComponentScan
public class MyClassTest {
    @Autowired MyClass myClass;

    @Test
    public void test() {
        this.myClass...()
    }
}
</code></pre>
",https://stackoverflow.com/questions/50698543/unit-testing-with-springjunit4classrunner-using-only-component-and-autowired,"['java', 'spring', 'junit', 'springjunit4classrunner']",1902,TRUE,0,1
How come my Unit testing only passes negative cases?,"<p>I am trying to set up a unit test for a little practice I am doing in JS.</p>

<p>I am using Jasmine unit test framework for this.</p>

<p>However, when running the unit tests on my little JS application (a prime number machine) it only passes the cases where it expects the number NOT to be prime.</p>

<p>and it fails all the prime number cases.</p>

<p>I cannot seem to figure out why, since my application in the actual HTML I embedded this in, works just fine.</p>

<p>My application looks like this.</p>

<pre><code>function findPrime(){
            //get the input value
            var num = 0;
            var c = 0;

            //loop till i equals to $num
            for (i = 1; i &lt;= num; i++) {
                //check if the $num is divisible by itself and 1
                // % modules will give the reminder value, so if the reminder is 0 then it is divisible
                if (num % i == 0) {
                    //increment the value of c
                    c = c + 1;
                }
            }

            //if the value of c is 2 then it is a prime number
            //because a prime number should be exactly divisible by 2 times only (itself and 1)
            if (c == 2) {
                return true;
            }else{
                return false;
            }
        }
</code></pre>

<p>And my unit test looks like this.</p>

<pre><code>    describe(""PrimeNumberMachineTest"", function() {
  it(""should determine 2 is a prime number"", function() {
    expect(findPrime(2)).toBeTruthy();
  });
  it(""should determine 3 is a prime number"", function() {
    expect(findPrime(3)).toBeTruthy();
  });
  it(""should determine 4 is not a prime number"", function() {
    expect(findPrime(4)).toBeFalsy();
  });
  it(""should determine 5 is a prime number"", function() {
    expect(findPrime(5)).toBeTruthy();
  });
  it(""should determine 6 is not a prime number"", function() {
    expect(findPrime(6)).toBeFalsy();
  });
  it(""should determine 7 is a prime number"", function() {
    expect(findPrime(7)).toBeTruthy();
  });
  it(""should determine 8 is not a prime number"", function() {
    expect(findPrime(8)).toBeFalsy();
  });
  it(""should determine 9 is not a prime number"", function() {
    expect(findPrime(9)).toBeFalsy();
  });
  it(""should determine 10 is not a prime number"", function() {
    expect(findPrime(10)).toBeFalsy();
  });
  it(""should determine 11 is a prime number"", function() {
    expect(findPrime(11)).toBeTruthy();
  });
  it(""should determine 12 is not a prime number"", function() {
    expect(findPrime(12)).toBeFalsy();
  });
  it(""should determine 13 is a prime number"", function() {
    expect(findPrime(13)).toBeTruthy();
  });
  it(""should determine 14 is not a prime number"", function() {
    expect(findPrime(14)).toBeFalsy();
  });
  it(""should determine 15 is not a prime number"", function() {
    expect(findPrime(15)).toBeFalsy();
  });
  it(""should determine 16 is not a prime number"", function() {
    expect(findPrime(16)).toBeFalsy();
  });
  it(""should determine 17 is a prime number"", function() {
    expect(findPrime(17)).toBeTruthy();
  });
  it(""should determine 18 is not a prime number"", function() {
    expect(findPrime(18)).toBeFalsy();
  });
  it(""should determine 19 is a prime number"", function() {
    expect(findPrime(19)).toBeTruthy();
  });
  it(""should determine 20 is not a prime number"", function() {
    expect(findPrime(20)).toBeFalsy();
  });
  it(""should determine 37,120,123 is a prime number"", function() {
    expect(findPrime(37120123)).toBeTruthy();
  });
});
</code></pre>

<p>But the results come back as follows:</p>

<p><a href=""https://i.stack.imgur.com/rH44K.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/rH44K.jpg"" alt=""Jasmine Results""></a></p>
",https://stackoverflow.com/questions/53259376/how-come-my-unit-testing-only-passes-negative-cases,"['javascript', 'unit-testing', 'jasmine']",151,TRUE,0,2
Unexpected request error when unit-testing angular $http service,"<p>I'm using unit-testing in my angularJS application. Here's a test spec I have for a service:</p>

<pre><code>describe('service', function () {
    var service = {};
    var $httpBackend;

    beforeEach(module('myApp'));
    beforeEach(inject(function (_service_, _$httpBackend_) {
        service = _service_;
        $httpBackend = _$httpBackend_;
    }));

    it('should return test message', function () {
        var response;
        var test = ""This is a test"";

        $httpBackend.when('GET', '/api/Account/GetTest')
            .respond(200, test);

        service.getTest().then(function (data) {
            response = data;
        });

        expect(response).toEqual(test);
    });
});
</code></pre>

<p>And, here's the <code>getTest</code> function in my service:</p>

<pre><code>var getTest = function () {
    return $http.get(""api/Account/GetTest"");
};
</code></pre>

<p>Why am I getting the following error:</p>

<blockquote>
  <p>Error: Unexpected request: GET api/Account/GetTest</p>
</blockquote>

<p>I also figured if I remove the slash from the url in my spec, the error will change to this (and I have no idea why):</p>

<blockquote>
  <p>Error: Unexpected request: GET /app/views/login.html</p>
</blockquote>
",https://stackoverflow.com/questions/49118149/unexpected-request-error-when-unit-testing-angular-http-service,"['angularjs', 'unit-testing', 'jasmine', 'angular-mock', 'angularjs-ngmock']",653,FALSE,0,1
"Unit testing in Loopback with Mocha, Sinon and Chai","<p>I'm trying to get into unit testing on of my custom methods in Loopback.
The method itself clears all of the user data give parameter.</p>

<pre><code>module.exports = function(User) {
  User.clearData = async function(options) {
    const cityId = options.accessToken.cityId;

    const deleteUserData = () =&gt; {
      return User.destroyAll({cityId: cityId}, options).catch(error =&gt; {
        console.log('Error deleting user', error);
        throw error;
      });
    };

    await deleteUserData();
  };
};
</code></pre>

<p>What I've done before is something like this :</p>

<pre><code>const sinon = require('sinon');
const {expect} = require('chai');

const clearDataUser = require('../clear-data');

describe('User clear data', ()=&gt;{
  let spy,
    User;

  const options = {
    accessToken: {
      cityId: 1,
    },
  };

  beforeEach(()=&gt;{
    spy = sinon.spy();
    User = {
      destroyAll: spy,
    };
  });

  it('should call destroyAll', () =&gt; {
    clearDataUser(User);
    User.destroyAll({cityId: options.accessToken.cityId}, options);
    expect(spy.callCount).to.eq(1);
  });
});
</code></pre>

<p>This will test only that <code>destroyAll</code> is called. Is there a way to test out the <code>catch</code> condition? I'm also using <code>async/await</code>, so can this also be factored in?
_____________________________________EDIT_____________________________________</p>

<p>I changed it up a little bit to look like :</p>

<pre><code>  it('should call destroyAll', async() =&gt; {
    clearDataUser(User);
    const deleteUserData = () =&gt; {
      return User.destroyAll({cityId: options.accessToken.cityId}, options);
    };

    await deleteUserData();
    expect(spy.callCount).to.eq(1);
  });
</code></pre>

<p>However if I try to add <code>.catch(error =&gt; { expect(error).to.not.equal('undefined'); });</code>, I get <code>TypeError: Cannot read property 'catch' of undefined</code></p>
",https://stackoverflow.com/questions/52248031/unit-testing-in-loopback-with-mocha-sinon-and-chai,"['unit-testing', 'mocha.js', 'sinon', 'chai', 'loopback']",699,FALSE,0,1
.length is not taking in Jasmine Karma unit testing,"<p>Could anyone please help me to resolve the below issue.</p>

<blockquote>
  <p>Error: TypeError: Cannot read property 'length' of undefined</p>
</blockquote>

<p>Component File:</p>

<pre><code> @Input()
   allPropertyLines: any[];

 @Input()
   completedPropertyLines: any[];

 allPropertyLength: number = 0;
 completedPropertyLength: number = 0;

  ngOnInit() {
      this.allPropertyLength = this.allPropertyLines.length;
      this.completedPropertyLength = this.completedPropertyLines.length;      
   }
</code></pre>

<p>Spec File:</p>

<pre><code> beforeEach(() =&gt; {
   fixture = TestBed.createComponent(ListPropertyComponent);
   comp = fixture.componentInstance;
   comp.ngOnInit();    
 });
it('should create component', () =&gt; expect(comp).toBeDefined());
</code></pre>
",https://stackoverflow.com/questions/48495395/length-is-not-taking-in-jasmine-karma-unit-testing,"['angular', 'ionic3', 'karma-jasmine', 'karma-coverage', 'angular-test']",1892,TRUE,0,1
"While unit testing REST endpoint, LocalDateTime is sent truncated","<p>I'd like to unit test my REST endpoint. I'm  very new to this, but I was able to write the following code:</p>

<pre><code>HttpPost request = new HttpPost(""http://localhost:8080/myrest"");
ObjectMapper mapper = new ObjectMapper();
String empJson = mapper.writeValueAsString(clientDto);
StringEntity input = new StringEntity(empJson);
input.setContentType(""application/json"");
request.setEntity(input);
org.apache.http.HttpResponse httpResponse = 
HttpClientBuilder.create().build().execute(request);
</code></pre>

<p><code>clientDto</code> is an instance of a simple POJO with a field of type <code>LocalDateTime</code>. The thing is that my deserializer always gets that date as the following string <code>{</code> (one char only). How do I fix this? If you think that unit testing can be done in a better way, please let me know. I've used Apache dependency but this is not a must.   </p>
",https://stackoverflow.com/questions/51439643/while-unit-testing-rest-endpoint-localdatetime-is-sent-truncated,"['java', 'rest', 'jakarta-ee', 'junit']",195,FALSE,0,1
Unit testing : avoid actual execution of the async task,"<p>I am using Roboelectric 3.0 and Mockito to unit test a class.
The class does some work and starts an Async task that has stubbed dependencies so I am getting a runtime exception(during the async task execution).</p>

<p>Is there a way, I can check </p>

<ol>
<li>the Async task was started</li>
<li>Avoid executing the Async task.</li>
</ol>
",https://stackoverflow.com/questions/49784390/unit-testing-avoid-actual-execution-of-the-async-task,"['java', 'android', 'mockito', 'robolectric']",47,FALSE,0,0
dataTaskWithURL crash unit testing in VIPER with swift 4,"<p>I'm Following <a href=""http://masilotti.com/testing-nsurlsession-input/"" rel=""nofollow noreferrer"">this tutorial</a> and trying to unit test my web services. The tutorial is in swift 2 and I've written it into swift 4.
I've done everything okay but the app is crashing, wether I'm unit-testing or running the app and I can't figure why. Can anyone help?</p>

<p>the crash line of code is: </p>

<pre><code>extension URLSession : URLSessionProtocol{
    func dataTaskWithURL(url: NSURL, completionHandler: (Data?, URLResponse?, Error?) -&gt; Void) -&gt; URLSessionDataTaskProtocol {

        return dataTaskWithURL(url: url, completionHandler: completionHandler) //app crash

    }
}
</code></pre>

<p>Here is the full code of my webService: </p>

<pre><code>import Foundation

protocol URLSessionProtocol {
    typealias DataTaskResult = (Data?, URLResponse?, Error?) -&gt; Void

    func dataTaskWithURL(url: NSURL, completionHandler: DataTaskResult)
        -&gt; URLSessionDataTaskProtocol
}
protocol URLSessionDataTaskProtocol {
    func resume()
}

class UserListRemoteDataManager:UserListRemoteDataManagerInputProtocol {

    var remoteRequestHandler: UserListRemoteDataManagerOutputProtocol?

    private let session : URLSessionProtocol

    init(session : URLSessionProtocol) {
        self.session = session
    }

    func retrieveUsers() {
        if let url = NSURL(string: Endpoints.Users.fetch.url){
            session.dataTaskWithURL(url: url, completionHandler: { (data, response, error) in
                if error != nil {
                    print(error as Any)
                }
                if error == nil &amp;&amp; data != nil {
                    do{
                        let users = try JSONDecoder().decode(UserModel.self, from: data!)
                        self.remoteRequestHandler?.onUsersRetrieved(users.users)
                    }catch let error as NSError {
                        print(error)
                        self.remoteRequestHandler?.onError()
                    }
                }
            }).resume()
        }
    }
}
extension URLSession : URLSessionProtocol{
    func dataTaskWithURL(url: NSURL, completionHandler: (Data?, URLResponse?, Error?) -&gt; Void) -&gt; URLSessionDataTaskProtocol {

        return dataTaskWithURL(url: url, completionHandler: completionHandler) //app crash

    }
}
extension URLSessionDataTask : URLSessionDataTaskProtocol{

}
</code></pre>
",https://stackoverflow.com/questions/52706087/datataskwithurl-crash-unit-testing-in-viper-with-swift-4,"['ios', 'swift', 'unit-testing', 'nsurlsession', 'swift-protocols']",135,TRUE,0,1
Angular - Router unit testing with testing module and RouterMock,"<p>I've read several questions about how to unit test routing. But nothing fits my case really. I have a navbar-comp. with several <code>[routerLink]=[...]</code>
And when I simulate a click event. I want for instance to call <code>expect(router.navigate).toHaveBeenCalledWith(*path*);</code></p>

<p>But I am already failing on the test setup: It throws me everytime a: <code>cannot find root of undefined</code>.</p>

<h2>Test suite</h2>

<pre><code>describe('NavbarComponent', () =&gt; {
  let component: NavbarComponent;
  let fixture: ComponentFixture&lt;NavbarComponent&gt;;

  const router: Router = jasmine.createSpyObj('Router', ['navigate']);

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [
        NgbModule.forRoot(),
        RouterTestingModule
      ],
      providers: [
        {provide: Router, useValue: router}
      ],
      declarations: [
        NavbarComponent,
      ]
    })
      .compileComponents();
  }));

  it('should navigate on click - home', () =&gt; {
    (&lt;jasmine.Spy&gt;router.navigate).and.stub();
    const debugElm = fixture.debugElement.nativeElement.querySelector('#navLogo');
    debugElm.click();

    expect(router.navigate).toHaveBeenCalledWith(['/stories']);
  });
</code></pre>

<p>When I delete the <code>RoutingTestingModule</code> import then it throws me: <code>Cannot bind to routerLink</code> - which I actually need to test. Really frustrating... Does anyone has a solution for this? </p>
",https://stackoverflow.com/questions/51231953/angular-router-unit-testing-with-testing-module-and-routermock,"['angular', 'unit-testing', 'routes', 'jasmine', 'angular2-routing']",3142,TRUE,0,1
Injecting an instance of drools StatefulKnowledgeSession during unit testing,"<pre><code>public class App {

    @Autowired
    private KnowledgeBase kBase;

    private StatefulKnowledgeSession statefulKnowledgeSession;

    public void method() {
        statefulKnowledgeSession = kBase.newStatefulKnowledgeSession();

        statefulKnowledgeSession.fireAllRules();
    }


}
</code></pre>

<p>I am working on a spring application that has a class of the form shown above. </p>

<p>The test class is of the form shown below</p>

<pre><code>public class AppTest {


    @Spy
    private StatefulKnowledgeSession statefulKnowledgeSession;


}
</code></pre>

<p>The test class shown above does not contain the complete code but it is just to tell how the class looks. Now I want to fire the rules during unit testing by calling the actual method but I am not able to use @Spy as StatefulKnowledgeSession is an interface. @Spy needs an object to be created but I cannot obviously instantiate an interface.</p>

<p>Please Help!</p>
",https://stackoverflow.com/questions/51179487/injecting-an-instance-of-drools-statefulknowledgesession-during-unit-testing,"['spring', 'mockito', 'drools']",84,FALSE,0,0
Unit testing visual c++ code throws when deleting pointer,"<p>I am currently unit testing unmanaged visual c++ code in visual studio 2010.<br/>
My solution is structured as following:</p>

<pre><code>&lt;Solution&gt;
  - [0] Static library project (visual c++, no clr)
  - [1] Project that's using [0] (visual c++, no clr, referencing [0])
  - [2] Unit Test Project (dynamic library, /clr, referencing [0])
&lt;/Solution&gt;
</code></pre>

<p><strong><code>Project [0]</code> is being tested by <code>Project [2]</code> and contains <code>SomeClass</code>:</strong></p>

<pre><code>class SomeClass
{
public:
    SomeClass() {}
    int Testme() { return 42; }
};
</code></pre>

<p><strong>In <code>Project [2]</code> I am testing <code>SomeClass</code> as following, and this works:</strong></p>

<pre><code>[TestClass]
public ref class SomeClassUnitTests
{
public:
    [TestMethod]
    void TestmeReturns42()
    {
        SomeClass sc;
        Assert::AreEqual&lt;int&gt;(42, sc.Testme());
    }
};
</code></pre>

<p>But when I allocate the memory for <code>SomeClass</code> on the heap and only when I afterwards call delete on it, a message pops up showing that the heap was corrupt/invalid.</p>

<pre><code>[TestClass]
public ref class SomeClassUnitTests
{
public:
    [TestMethod]
    void TestmeReturns42()
    {
        SomeClass *ptr = new SomeClass();
        Assert::AreEqual&lt;int&gt;(42, ptr-&gt;Testme());

        // Without following line, everything works:
        if (ptr) delete ptr;
    }
};
</code></pre>

<blockquote>
  <p>What could be the issue causing the Tests to throw right here, and why does allocating memory with 'new' work, but deleting doesn't?</p>
</blockquote>
",https://stackoverflow.com/questions/51871478/unit-testing-visual-c-code-throws-when-deleting-pointer,"['unit-testing', 'visual-studio-2010', 'pointers', 'visual-c++']",240,FALSE,0,0
Composition vs Inheritance - how this can help Unit Testing?,"<p>Why using Composition is more recommended for <code>Unit testing</code> approach?</p>

<p>It is related to the fact that by extending a class you have to test the entire API of the parent class too and by using Composition you have more control on the methods you want to use from the parent class?</p>
",https://stackoverflow.com/questions/51062968/composition-vs-inheritance-how-this-can-help-unit-testing,"['java', 'php', 'unit-testing']",125,TRUE,0,1
Unit testing Spring MVC Controller: java.util.Map data not bound,"<p>Dear devs at stackoverflow,</p>

<p>I would really appreciate your help with a tricky problem I am not able to resolve while unit testing one of my Spring MVC controllers.</p>

<p>The entire code repository can be found here: <a href=""https://github.com/peerpub/peerpub"" rel=""nofollow noreferrer"">https://github.com/peerpub/peerpub</a></p>

<p><strong>Environment:</strong></p>

<ul>
<li>Java 8</li>
<li>Maven 3.5</li>
<li>Spring Boot 2.0.1</li>
<li>Spring Framework 5.0.4</li>
<li>Thymeleaf 3</li>
<li>JUnit 5 + Mockito</li>
</ul>

<p><strong>Problem description:</strong></p>

<p>While trying to come up with detailed tests for <a href=""https://github.com/peerpub/peerpub/blob/oliver_dtsvc/src/main/java/de/fzj/peerpub/doc/doctype/DocTypeAdminCtrl.java"" rel=""nofollow noreferrer""><code>DocTypeAdminCtrl.java</code></a> using a unit test approach with Mockito/MockMVC, I am not able to bind data based on a <code>Map</code>, while simple <code>String</code> and <code>Boolean</code> work just fine. The same is happening when I try to use this in my full-stack integration tests (already tried that).</p>

<p><em>While using the application via the web browser, this problem does not appear, so this seems to be entirely testing related.</em></p>

<p>All tests named <code>editPost...()</code> in <a href=""https://github.com/peerpub/peerpub/blob/oliver_dtsvc/src/test/java/de/fzj/peerpub/doc/doctype/DocTypeAdminCtrlTest.java"" rel=""nofollow noreferrer""><code>DocTypeAdminCtrlTest.java</code></a> fail. Example log excerpt from <code>mvn test</code>:</p>

<pre><code>Tests run: 7, Failures: 3, Errors: 0, Skipped: 0, Time elapsed: 0.437 sec &lt;&lt;&lt; FAILURE! - in de.fzj.peerpub.doc.doctype.DocTypeAdminCtrlTest
editPostFormSuccess  Time elapsed: 0.103 sec  &lt;&lt;&lt; FAILURE!
java.lang.AssertionError: Status expected:&lt;302&gt; but was:&lt;200&gt;
at de.fzj.peerpub.doc.doctype.DocTypeAdminCtrlTest.editPostFormSuccess(DocTypeAdminCtrlTest.java:148)

editPostFormNonMatchingNames  Time elapsed: 0.046 sec  &lt;&lt;&lt; FAILURE!
java.lang.AssertionError: Model attribute 'doctype' expected:   &lt;DocTypeForm(name=vfAtXQ, displayName=01p14G7v22, system=false, multiDoc=true, attributes=[6Vuzhn, zKXSTl], mandatory={6Vuzhn=null, zKXSTl=true}, defaults={6Vuzhn=, zKXSTl=sooeOYb6Ld})&gt; but was:&lt;DocTypeForm(name=vfAtXQ, displayName=01p14G7v22, system=false, multiDoc=true, attributes=[6Vuzhn, zKXSTl], mandatory=null, defaults=null)&gt;
at de.fzj.peerpub.doc.doctype.DocTypeAdminCtrlTest.editPostFormNonMatchingNames(DocTypeAdminCtrlTest.java:165)

editPostFormExceptionDTO  Time elapsed: 0.041 sec  &lt;&lt;&lt; FAILURE!
java.lang.AssertionError: Model attribute 'doctype' expected:&lt;DocTypeForm(name=GPzldO, displayName=mIV7Utta1Y, system=false, multiDoc=false, attributes=[8GsYhQ, bZGkd2], mandatory={8GsYhQ=null, bZGkd2=true}, defaults={8GsYhQ=SfoDlEiYAz, bZGkd2=k4uaLxx8yf})&gt; but was:&lt;DocTypeForm(name=GPzldO, displayName=mIV7Utta1Y, system=false, multiDoc=false, attributes=[8GsYhQ, bZGkd2], mandatory=null, defaults=null)&gt;
 at  de.fzj.peerpub.doc.doctype.DocTypeAdminCtrlTest.editPostFormExceptionDTO(DocTypeAdminCtrlTest.java:210)
</code></pre>

<p>Please note that the properties <code>mandatory</code> and <code>defaults</code> always get set to <code>null</code>, while present in the model. I verified that even my custom validator <a href=""https://github.com/peerpub/peerpub/blob/oliver_dtsvc/src/main/java/de/fzj/peerpub/doc/doctype/DocTypeFormValidator.java"" rel=""nofollow noreferrer"">DocTypeFormValidator.java</a> is not seeing this data. This is also causing my <code>editPostFormSuccess</code> test to fail: as the properties are set to <code>null</code>, the validator is unhappy and the binding result contains errors.</p>

<p>As I unit/integration tested any kind of stuff used by my <code>DocTypeAdminCtrl.java</code> I am pretty sure that there must be something missing or wrong either in my controller class or in my test class. </p>

<p>There could be a bug in the <code>MockMvcRequestBuilderUtils.postForm()</code> (see <a href=""https://github.com/f-lopes/spring-mvc-test-utils"" rel=""nofollow noreferrer"">upstream</a>), but I actually have no clue how to write an alternate <code>post()</code> request with my test data containing <code>Map</code> and <code>List</code>. Having a look at the <code>MockHttpServletRequestBuilder</code> with a debugger, all data seems to be present, including <code>mandatory</code> and <code>defaults</code>, so this might be a less important thing to examine...?</p>

<p>Some suspicious debug log output lines that caught my attention:</p>

<pre><code>org.springframework.beans.BeanUtils - No property editor [java.util.MapEditor] found for type java.util.Map according to 'Editor' suffix convention
org.springframework.core.annotation.AnnotationUtils - Failed to meta-introspect annotation interface org.springframework.web.bind.annotation.ModelAttribute: java.lang.NullPointerException
</code></pre>

<p>Searching for these errors here on StackOverflow and via Google didn't help much... :-(</p>

<p><strong>Steps to reproduce:</strong></p>

<p>Just clone my repo, switch to my feature branch <code>oliver_dtsvc</code> and run <code>mvn test</code>.</p>

<p>Does anybody out there have a clue? Any help is very much appreciated!</p>
",https://stackoverflow.com/questions/49782283/unit-testing-spring-mvc-controller-java-util-map-data-not-bound,"['spring', 'unit-testing', 'spring-mvc', 'controller', 'mockito']",272,TRUE,0,1
Unit testing value of Observable returned from service (using async pipe),"<p>Running Angular/Jasmine/Karma, I have a component that consumes a service to set the value of an Observable 'items' array.  I display this using an async pipe.  Works great.</p>

<p>Now, I'm trying to set up a unit test and got it to pass, but I'm not sure I'm correctly verifying that the 'items' array is getting the correct value.</p>

<p>Here is the relevant component .html and .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 class ViperDashboardComponent implements OnInit, OnDestroy {

    items: Observable&lt;DashboardItem[]&gt;;

    constructor(private dashboardService: ViperDashboardService) { }

    ngOnInit() {
        this.items = this.dashboardService.getDashboardItems();
    }
}</code></pre>
<pre class=""snippet-code-html lang-html prettyprint-override""><code>    &lt;ul class=""list-group""&gt;
        &lt;li class=""list-group-item"" *ngFor=""let item of items | async""&gt;
            &lt;h3&gt;{{item.value}}&lt;/h3&gt;
            &lt;p&gt;{{item.detail}}&lt;/p&gt;
        &lt;/li&gt;
    &lt;/ul&gt;</code></pre>
</div>
</div>
</p>

<p>And my component.spec.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>    beforeEach(() =&gt; {
        fixture = TestBed.createComponent(ViperDashboardComponent);
        component = fixture.componentInstance;

        viperDashboardService =        
  fixture.debugElement.injector.get(ViperDashboardService);

        mockItems = [
            { key: 'item1', value: 'item 1', detail: 'This is item 1' },
            { key: 'item2', value: 'item 2', detail: 'This is item 2' },
            { key: 'item3', value: 'item 3', detail: 'This is item 3' }
        ];

        spy = spyOn(viperDashboardService, 'getDashboardItems')
            .and.returnValue(Observable.of&lt;DashboardItem[]&gt;(mockItems));

    });

    it('should create', () =&gt; {
        expect(component).toBeTruthy();
    });

    it('should call getDashboardItems after component initialzed', () =&gt; {
        fixture.detectChanges();
        expect(spy.calls.any()).toBe(true, 'getDashboardItems should be called');
    });

    it('should show the dashboard after component initialized', () =&gt; {
        fixture.detectChanges();
        expect(component.items).toEqual(Observable.of(mockItems));
    });</code></pre>
</div>
</div>
</p>

<p>Specifically, I'd like to know:</p>

<p>1) I started off creating an async ""it"" test, but was surprised when that didn't work.  Why does a synchronous test work when I'm working with async data streams?</p>

<p>2) When I check the equivalence of component.items to the Observable.of(mockItems), am I really testing that the values are equal?  Or am I just testing that they are both Observables?  Is there a better way?</p>
",https://stackoverflow.com/questions/48328292/unit-testing-value-of-observable-returned-from-service-using-async-pipe,"['angular', 'unit-testing', 'typescript', 'jasmine', 'karma-runner']",16544,TRUE,12,2
Unit testing AngularJS $http event handler with Jasmine/Karma?,"<p>I'm using AngularJS 1.5.8, and I have a factory with a method that returns an instance of an $http request. It includes a progress <code>eventHandler</code>. My question is, how can I test this event handler using Jasmine/Karma? Normally, requests are tested by mocking them up via <code>$httpBackend.expectPOST</code> or similar, but then the progress event is never fired. And if I don't mock it up, Karma complains about an unexpected request. How do I do this?</p>
",https://stackoverflow.com/questions/52614879/unit-testing-angularjs-http-event-handler-with-jasmine-karma,"['angularjs', 'unit-testing', 'http', 'karma-jasmine', 'eventhandler']",262,TRUE,0,1
Include HTML file in Angular unit testing code coverage report,"<p>I am using Angular 6 with karma coverage istanbul reporter to see code coverage. </p>

<p>It show only .ts file in the code coverage report which could be misleading as HTML templates can also include code logic. </p>

<p>Is there anyway to include HTML code to unit test code coverage? </p>
",https://stackoverflow.com/questions/52259871/include-html-file-in-angular-unit-testing-code-coverage-report,"['angular', 'jasmine', 'istanbul', 'karma-coverage']",370,FALSE,6,0
How to write unit testing for if else statements,"<p>I would like to write a unit testing for a function called ""fibb"" using Mocha, Chai or Jasmin.</p>

<p><strong>app.js</strong></p>

<pre><code>fibb: function (n) {
  if(n==1) {
    return 1;
  } else {
    return (n * (n-1));
  }
}
</code></pre>

<p><strong>test.js:</strong></p>

<pre><code>var fibb = require(""../app"").fibb;
describe('App', function() {
  it('should be 20', function() {
    assert.equal(fibb(5), 20);
  });
});
</code></pre>

<p>This code is working for statement <code>2(n*(n-1))</code> but I want to write for both the possibilities(when ‘n==1<code>and</code>(n*(n-1))` statements). </p>
",https://stackoverflow.com/questions/49340558/how-to-write-unit-testing-for-if-else-statements,"['javascript', 'unit-testing', 'jasmine', 'mocha.js', 'chai']",1336,FALSE,0,1
Unit Testing Rest Services with Spring Boot and JUnit,"<p>I have a basic SpringBoot app. using Spring Initializer, JPA, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file. I've defined this Rest method to get a User</p>

<pre><code>  @GetMapping(path = ""/api/users/{id}"", 
                consumes = ""application/json"", 
                produces = ""application/json"")
    public ResponseEntity&lt;User&gt; getUser
                                    (HttpServletRequest request, 
                                    @PathVariable long id) {

        User user = checkAccess(request, id);
        return ResponseEntity.ok(user);

    }
</code></pre>

<p>I've created this Junit to test it</p>

<pre><code>@ContextConfiguration(classes={TestSystemConfig.class})
@RunWith(SpringRunner.class)
@WebMvcTest(UserResourceController.class)
public class UserResourceControllerTests {

    @Autowired
    private MockMvc mvc;


    @MockBean
    private UserResourceController UserResourceController;

    @Test
    public void getUser() throws Exception {

        mvc.perform(get(""/api/users/1"")
                   .with(user(""pere.peris@gmail.com"").password(""password""))
                   .contentType(APPLICATION_JSON))
                   .andExpect(status().isOk());

    }
}
</code></pre>

<p>But I got this error when I run the test:</p>

<pre><code>org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException: Name for argument type [long] not available, and parameter name information not found in class file either.
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:866)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851)
    at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:71)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:166)
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320)
</code></pre>
",https://stackoverflow.com/questions/50605095/unit-testing-rest-services-with-spring-boot-and-junit,"['rest', 'unit-testing', 'spring-boot', 'junit4', 'junit5']",1517,TRUE,0,1
How to test if a goroutine has been called while unit testing in Golang?,"<p>suppose that we have a method like this:</p>

<pre><code>func method(intr MyInterface) {
    go intr.exec()
} 
</code></pre>

<p>In unit testing <code>method</code>, we want to assert that <code>inter.exec</code> has been called once and only once; so we can mock it with another mock struct in tests, which will give us functionality to check if it has been called or not:  </p>

<pre><code>type mockInterface struct{
    CallCount int
}

func (m *mockInterface) exec() {
    m.CallCount += 1
}
</code></pre>

<p>And in unit tests:</p>

<pre><code>func TestMethod(t *testing.T) {
    var mock mockInterface{}
    method(mock)
    if mock.CallCount != 1 {
        t.Errorf(""Expected exec to be called only once but it ran %d times"", mock.CallCount)
    }
}
</code></pre>

<p>Now, the problem is that since <code>intr.exec</code> is being called with <code>go</code> keyword, we can't be sure that when we reach our assertion in tests, it has been called or not.  </p>

<h2>Possible Solution 1:</h2>

<p>Adding a channel to arguments of <code>intr.exec</code> may solve this: we could wait on receiving any object from it in tests, and after receiving an object from it then we could continue to assert it being called. This channel will be completely unused in production (non-test) codes. 
This will work but it adds unnecessary complexity to non-test codes, and may make large codebases incomprehensible. </p>

<h2>Possible Solution 2:</h2>

<p>Adding a relatively small sleep to tests before assertion may give us some assurance that the goroutine will be called before sleep is finished:</p>

<pre><code>func TestMethod(t *testing.T) {
    var mock mockInterface{}
    method(mock)

    time.sleep(100 * time.Millisecond)

    if mock.CallCount != 1 {
        t.Errorf(""Expected exec to be called only once but it ran %d times"", mock.CallCount)
    }
}
</code></pre>

<p>This will leave non-test codes as they are now.<br>
The problem is that it will make tests slower, and will make them flaky, since they may break in some random circumstances. </p>

<h2>Possible Solution 3:</h2>

<p>Creating a utility function like this:</p>

<pre><code>var Go = func(function func()) {
    go function()
} 
</code></pre>

<p>And rewrite <code>method</code> like this:</p>

<pre><code>func method(intr MyInterface) {
    Go(intr.exec())
} 
</code></pre>

<p>In tests, we could change <code>Go</code> to this:</p>

<pre><code>var Go = func(function func()) {
    function()
} 
</code></pre>

<p>So, when we're running tests, <code>intr.exec</code> will be called synchronously, and we can be sure that our mock method is called before assertion.<br>
The only problem of this solution is that it's overriding a fundamental structure of golang, which is not right thing to do.   </p>

<hr>

<p>These are solutions that I could find, but non are satisfactory as far as I can see. What is best solution?</p>
",https://stackoverflow.com/questions/51065482/how-to-test-if-a-goroutine-has-been-called-while-unit-testing-in-golang,"['unit-testing', 'go', 'goroutine']",36745,TRUE,28,3
NodeJS Mocha unit testing with global injected variables from WebPack.DefinePlugin,"<p>Global variables injected via the WebPack.DefinePlugin don't seem to mesh well with my Mocha unit tests. The global variables aren't recognised when running the test and the <a href=""https://mochajs.org/"" rel=""nofollow noreferrer"">Mocha documentation</a> doesn't appear to have a way to inject these global variables.</p>

<p>How do I inject these variables such that they'll work in the unit test?</p>

<h2>Detailed description</h2>

<p>Given a WebPack project with the following configuration:</p>

<pre><code>{
    ...
    plugins: [
        ...
        new webpack.DefinePlugin({
            __ENV__: JSON.stringify(process.env.ENVIRONMENT),
            ...
        }),
        ...
    ]
}
</code></pre>

<p>And having the following typescript code in my project:</p>

<pre><code>declare let __ENV__: string;

...

export const ENV = __ENV__;
</code></pre>

<p>If I run Mocha with the following options: </p>

<pre><code>mocha --compilers ts:ts-node/register --require ./test/entry.ts **/*.test.ts
</code></pre>

<p>Mocha will run into the following error:</p>

<pre><code>C:\git\project\src\constants\config.ts:7
export const ENV = __ENV__;
                   ^
ReferenceError: __ENV__ is not defined
    at Object.&lt;anonymous&gt; (C:\git\project\src\constants\config.ts:7:20)
    ...
</code></pre>

<h2>What I tried</h2>

<p>I figured I should define <code>__ENV__</code> in my <code>entry.ts</code> file. The following attempts all failed with various errors when running mocha:</p>

<pre><code>const __ENV__ = 'dev'; // Same message as above.
window.__ENV__ = 'dev'; // Property '__ENV__' does not exist on type 'Window'.
window['__ENV__'] = 'dev'; // ReferenceError: window is not defined
global.__ENV__ = 'dev'; // Property '__ENV__' does not exist on type 'Global'.
export declare let __ENV__ = 'dev'; // Initializers are not allowed in ambient contexts.
export declare const __ENV__ = 'dev'; // Initializers are not allowed in ambient contexts.
</code></pre>
",https://stackoverflow.com/questions/50952917/nodejs-mocha-unit-testing-with-global-injected-variables-from-webpack-defineplug,"['node.js', 'unit-testing', 'typescript', 'mocha.js']",676,TRUE,4,1
Jest and Enzyme simulating onDrag event for React unit testing,"<p>I have a problem with simulating <strong>drag</strong> event in my React Enzyme Jest unit test. Spy is never called in opposite to the <strong>dragStart</strong> and <strong>dragExit</strong>. Working ones are basing on mouse event and drag of course not - many tries of simulating it in strange ways like:
<code>wrapper.find('Draggable').simulate('mouseDown').simulate('mouseMove', {PageY: 100}).simulate('mouseUp');</code></p>

<p>...are failed, so this is my actual describe block:</p>

<pre><code>it('should call dragStart()', () =&gt; {
    wrapper.find('Draggable').simulate('mouseDown');
    expect(wrapper.instance().props.dragStart).toHaveBeenCalled(); // PASS
});
it('should call dragExit()', () =&gt; {
    wrapper.find('Draggable').simulate('mouseDown').simulate('mouseUp');
    expect(wrapper.instance().props.dragExit).toHaveBeenCalled(); // PASS
});
it('should call dragMove()', () =&gt; {
    wrapper.find('Draggable').simulate('drag');
    expect(wrapper.instance().props.dragMove).toHaveBeenCalled(); // FAIL
});
</code></pre>

<p>How can I simulate that dragging? I chose <strong>react-draggable</strong> dependency. I use enzyme <strong>mount</strong> with jest.fn() spy props to render my wrapper. Please for help and if you need any more information - just say! :)</p>

<p>PS: I know <a href=""https://github.com/mzabriskie/react-draggable/blob/master/specs/draggable.spec.jsx#L712"" rel=""nofollow noreferrer"">Draggable solution with TestUtils</a> but I want to create same effect with <strong>Enzyme</strong>, however my efforts are ending with not called spy at all:</p>

<pre><code>wrapper.find('Draggable').simulate('mouseDown', {clientX: 0, clientY: 0}).simulate('mouseMove', {clientX: 0, clientY: 100}).simulate('mouseUp');
</code></pre>
",https://stackoverflow.com/questions/48216011/jest-and-enzyme-simulating-ondrag-event-for-react-unit-testing,"['reactjs', 'unit-testing', 'drag-and-drop', 'jestjs', 'enzyme']",4861,FALSE,4,0
"Python unit testing nested &quot;async with&quot;, how to mock/patch?","<p>I've been struggling a bit with unit testing a piece of asynchronous code, that uses nested ""async with"".</p>

<p>python version 3.6.3
aiohttp version 3.4.4</p>

<p>The bare knuckles version of the function that I want to unit test:</p>

<pre><code>async def main():

    url = 'http://www.google.com'
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.read()
</code></pre>

<p>And the stripped down unit test code is like so:</p>

<pre><code>class AsyncMock(MagicMock):
    async def __call__(self, *args, **kwargs):
        return super(AsyncMock, self).__call__(*args, **kwargs)


class TestAsyncTest(unittest.TestCase):

    @patch('aiohttp.ClientSession', new_callable=AsyncMock)
    def test_async_test(self, mock_session):

        loop = asyncio.get_event_loop()
        result = loop.run_until_complete(main())
        print('result={}'.format(result))
        loop.close()
</code></pre>

<p><strong>Question</strong>: How to patch the nested calls, I want the ""get"" function to raise an exception. I suspect it should look something like this:</p>

<pre><code>mock_session.__aenter__().get().__aenter__.side_effect = asyncio.TimeoutError()
</code></pre>

<p>But that gives me an error:</p>

<pre><code>E
======================================================================
ERROR: test_async_test (test_test_async_unittest.TestAsyncTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File ""/usr/lib/python3.6/unittest/mock.py"", line 1179, in patched
    return func(*args, **keywargs)
  File ""/ntfs/projects/gsmg/scratch/test_test_async_unittest.py"", line 18, in test_async_test
    mock_session.__aenter__().get().__aenter__.side_effect = asyncio.TimeoutError()
  File ""/usr/lib/python3.6/unittest/mock.py"", line 584, in __getattr__
    raise AttributeError(name)
AttributeError: __aenter__

----------------------------------------------------------------------
Ran 1 test in 0.004s

FAILED (errors=1)
</code></pre>

<p>However, if I run it without that line (just the code posted above), I get this error:</p>

<pre><code>E
======================================================================
ERROR: test_async_test (test_test_async_unittest.TestAsyncTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File ""/usr/lib/python3.6/unittest/mock.py"", line 1179, in patched
    return func(*args, **keywargs)
  File ""/ntfs/projects/gsmg/scratch/test_test_async_unittest.py"", line 19, in test_async_test
    result = loop.run_until_complete(main())
  File ""/usr/lib/python3.6/asyncio/base_events.py"", line 473, in run_until_complete
    return future.result()
  File ""/ntfs/projects/gsmg/scratch/test_async_unittest.py"", line 8, in main
    async with aiohttp.ClientSession() as session:
AttributeError: __aexit__

----------------------------------------------------------------------
Ran 1 test in 0.007s

FAILED (errors=1)
</code></pre>
",https://stackoverflow.com/questions/53508368/python-unit-testing-nested-async-with-how-to-mock-patch,"['python-3.x', 'unit-testing', 'python-asyncio']",2225,TRUE,4,1
Java 8: unit-testing a method that returns a Function object,"<p>I'm trying to write a Java 8 unit test for a method that returns a <code>Function</code>; something like:</p>

<pre><code>class MyObject&lt;X&gt; {
     public Function&lt;X,Obj&gt; getFunction() {...}
 }
</code></pre>

<p>In my unit test I create a sample Object and call <code>getFunction()</code> and want to compare that to the expected function which does not work with <code>org.junit.Assert.assertEquals</code>:</p>

<pre><code>@Test
public void getFunction_returnsFunction() {
   final MyObject&lt;St&gt; object = new MyObject&lt;&gt;(..);
   final Function&lt;St,Obj&gt; expectedResult = ...;

   // this does not work
   assertEquals(expectedResult, object.getFunction());
}
</code></pre>

<p>Is it even possible to compare two <code>Function</code>s? How would you recommend to unit test this method?</p>
",https://stackoverflow.com/questions/53540533/java-8-unit-testing-a-method-that-returns-a-function-object,"['java', 'unit-testing', 'lambda', 'java-8']",3777,TRUE,10,1
Django Unit Testing - Client login does not seem to work,"<p>I have been referring to the tutorial in <a href=""https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Testing"" rel=""nofollow noreferrer"">https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Testing</a> when working on my own unit testing. My unit test codes are below:  </p>

<pre><code>from django.core.urlresolvers import reverse
from django.test import Client, TestCase
from django.contrib.auth.models import User

from companies.models import Company

class ContactViewTest(TestCase):

    def setUp(self):
        self.client = Client(HTTP_HOST='localhost:8000')

        company = Company(name='Test')
        company.save()

        user = User.objects.create(username='test_user1', email='test_user1@test.com')
        user.set_password('password')
        user.save()

        self.user = user
        self.company = company

    def test_logged_in_all_contacts_correct_template(self):
        c = self.client
        user_login = c.login(username=self.user.username, password=self.user.password)
        self.assertTrue(user_login)

        resp = c.get(reverse('all-contacts'), follow=True)

        # Check if user is logged in
        self.assertEquals(str(resp.context['user']), 'test_user1')
        # Check if response is ""success""
        self.assertEqual(resp.status_code, 200)

        self.assertTemplateUsed(resp, 'all_contacts.html')
</code></pre>

<p>Upon running python manage.py test contacts.tests, I ran into a few errors.</p>

<p>The first being <code>self.assertTrue(user_login)</code> which returns <code>AssertionError: False is not true</code></p>

<p>The second being <code>self.assertEquals(str(resp.context['user']), 'test_user1')</code> which returns <code>AssertionError: 'AnonymousUser' != 'test_user1'</code> when I removed <code>self.assertTrue(user_login)</code></p>

<p>I am not really sure what went wrong other than the client.login() did not work as I expected so thanks in advance to whoever can help.</p>
",https://stackoverflow.com/questions/50180122/django-unit-testing-client-login-does-not-seem-to-work,"['python', 'django', 'unit-testing']",4364,TRUE,4,2
Every test in project says &quot;Excluded from Live Unit Testing&quot;?,"<p>I have the test adapter &amp; framework packages added per the docs <a href=""https://learn.microsoft.com/en-us/visualstudio/test/live-unit-testing-faq?view=vs-2017"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/visualstudio/test/live-unit-testing-faq?view=vs-2017</a>.</p>

<p>I see the ""beaker"" symbol\icon beside each test, but hovering says it's Excluded from live unit testing.</p>

<p>Tests all run fine MANUALLY, and I've tried right-clicking and telling it to include, but does nothing.  I have no code in here manually excluding anything...</p>

<p>.net 4.7.1 project </p>

<p><strong><em>EDIT</em></strong></p>

<p>There is an error</p>

<blockquote>
  <p>[10:03:48.205 Error] [TestRunner 1] An exception occurred while
  invoking executor 'executor://mstestadapter/v2': Could not load file
  or assembly 'System.Xml.ReaderWriter, Version=4.1.1.0,
  Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its
  dependencies. The system cannot find the file specified. Could not
  load file or assembly 'System.Xml.ReaderWriter, Version=4.0.0.0,
  Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its
  dependencies. The system cannot find the file specified.</p>
</blockquote>

<p>This is a 4.7.1 project testing another 4.7.1 project which is EFCore based.</p>
",https://stackoverflow.com/questions/52005404/every-test-in-project-says-excluded-from-live-unit-testing,"['visual-studio', 'live-unit-tests']",1548,TRUE,4,4
Unit Testing Controller with Authorization ASP.NET Core 2.0 Web API,"<p>I have a controller:</p>

<pre><code>public class InvitationsController: Controller {
        private readonly IMapper _mapper;
        private readonly IInvitationManager _invitationManager;
        private readonly UserManager&lt;MyAppUser&gt; _userManager;

        public InvitationsController(
            IInvitationManager invitationManager,
            IMapper mapper,
            UserManager&lt;MyAppUser&gt; userManager,
            IJobManager jobManager
        ) {
            _invitationManager = invitationManager;
            _mapper = mapper;
            _userManager = userManager;
        } 
[Authorization]
GetInvitationByCode(string code) { ... }
</code></pre>

<p>I'm trying to write unit tests using Xunit and Moq. Here is the implentation of my test:</p>

<pre><code>  public class InvitationsControllerTests {

    private Mock&lt;IInvitationManager&gt; invitationManagerMock;        
    private Mock&lt;UserManager&lt;MyAppUser&gt;&gt; userManagerMock;
    private Mock&lt;IMapper&gt; mapperMock;
    private InvitationsController controller;

    public InvitationsControllerTests() {
        invitationManagerMock = new Mock&lt;IInvitationManager&gt;();          
        userManagerMock = new Mock&lt;UserManager&lt;MyAppUser&gt;&gt;();

        mapperMock = new Mock&lt;IMapper&gt;();
        controller = new InvitationsController(invitationManagerMock.Object,
                   mapperMock.Object,
                   userManagerMock.Object);
    }

    [Fact]
    public async Task GetInvitationByCode_ReturnsInvitation() {

        var mockInvitation = new Invitation {
            StoreId = 1,
            InviteCode = ""123abc"",
        };

        invitationManagerMock.Setup(repo =&gt; 
        repo.GetInvitationByCodeAsync(""123abc""))
            .Returns(Task.FromResult(mockInvitation));

        var result = await controller.GetInvitationByCode(""123abc"");

        Assert.Equal(mockInvitation, result);
    }
</code></pre>

<p>I don't think I'm using the mocking functionality correctly. Specifically with  UserManager. I can't find a clear answer on using Moq to test controllers protected by [Authorize]. When running my tests, it throws an exception on</p>

<pre><code>        controller = new InvitationsController(invitationManagerMock.Object,
                   mapperMock.Object,
                   userManagerMock.Object);
</code></pre>

<p>Which reads:</p>

<p>Castle.DynamicProxy.InvalidProxyConstructorArgumentsException: 'Can not instantiate proxy of class: Microsoft.AspNetCore.Identity.UserManager`1[[MyApp.api.Core.Models.MyAppUser, MyApp.api, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].
Could not find a parameterless constructor.'</p>
",https://stackoverflow.com/questions/49908658/unit-testing-controller-with-authorization-asp-net-core-2-0-web-api,"['c#', 'unit-testing', 'asp.net-core', 'moq']",6606,TRUE,3,2
Posting data using Django unit testing not saving to backend,"<p>I am creating a django app which i which implement most of my logic before the design aspect of the application.
I created a testcase for user registration but anytime I post to the registration url, it received my posted data but never populates it to database.</p>

<pre class=""lang-py prettyprint-override""><code>class AuthTest(TestCase):
    def setUp(self):
        self.client = Client()

    def test_reg_index(self):
        response = self.client.get(reverse_lazy('register'))
        return self.assertEqual(response.status_code, 200)

    def test_registration(self):
        data = {
            'last_name': 'test_user',
            'first_name': 'test_user',
            'email': 'fashtop3@gmail.com',
            'phone': '08035112897',
        }
        response = self.client.post(reverse_lazy('register'), data)

        self.assertEqual(response.status_code, 302)

    def test_login(self):
        # self.client.login(username='foo', password='bar')  # request.user is now user foo
        data = {
            'email': 'test_user@example.com',
            'password': 'pass123',
        }
        response = self.client.post(reverse_lazy('login'), data)

        self.assertEqual(response.status_code, 200)
</code></pre>

<pre class=""lang-py prettyprint-override""><code>class RegisterView(FormView):
    """"""
    this handles users registration
    """"""
    form_class = RegForm
    template_name = ""club/register.html""
    success_url = reverse_lazy(""register"")

    # def get(self, request, *args, **kwargs):
    #     return super(RegisterView, self).get(request, *args, **kwargs)

    def form_invalid(self, form):
        print(form.errors.as_data)
        return super().form_invalid(form)

    def form_valid(self, form):
        """"""
        Process valid registration form
        :param form:
        :return: redirects to success_url
        """"""
        random_password = ''.join(secrets.choice(string.ascii_uppercase + string.digits) for _ in range(6))
        try:
            with transaction.atomic():
                """"""Allow database transactions""""""
                data = form.cleaned_data
                user = User.objects.create_user(
                    email=data['email'],
                    password=random_password,
                    remember_token=hashlib.sha1(str(datetime.now()).encode('utf-8')).hexdigest()
                )
                user.profile.last_name = data['last_name']
                user.profile.first_name = data['first_name']
                user.profile.phone = data['phone']
                user.save()
                send_notification.delay(user.pk, random_password)
                print('Reg success')
                messages.success(self.request, ""Regular successfully registered ""
                                               ""please check your mail for verification"",
                                 extra_tags=""alert-success"")
        except IntegrityError as e:
            print(e)
            messages.error(self.request, ""Registration Failed: Email address already exist"", extra_tags=""alert-danger"")
            return super(RegisterView, self).form_invalid(form)
        except Exception as e:
            print(str(e))
            messages.error(self.request, ""Registration Error, contact site administrator: "", extra_tags=""alert-danger"")
            return super(RegisterView, self).form_invalid(form)

        return super(RegisterView, self).form_valid(form)
</code></pre>
",https://stackoverflow.com/questions/51553785/posting-data-using-django-unit-testing-not-saving-to-backend,"['django', 'django-testing']",1202,TRUE,3,3
What&#39;s the difference between stub and mock in Go unit testing?,"<p>I am using mocks in unit testing in Go. How do I understand the difference between stub and mock in the implementation code in Go?</p>
",https://stackoverflow.com/questions/53360256/whats-the-difference-between-stub-and-mock-in-go-unit-testing,"['unit-testing', 'go']",12332,TRUE,9,1
How to Mock Spring Boot Application Context In Unit Testing,"<p>I Have a Source class which has a dependency Of type Application Context. Using this we are achieving polymorphism. How to unit test this class. I'm using Spring boot application.</p>

<pre><code>@Autowired
ApplicationContext applicationContext;
String beanName= ""employeeImpl"";

applicationContext.getBean(beanName, Employee.class);
</code></pre>
",https://stackoverflow.com/questions/51903701/how-to-mock-spring-boot-application-context-in-unit-testing,['spring-boot'],2316,FALSE,3,1
c# unit testing method that calls EF Core extension method,"<p>I've been trying to unit test this simple method:</p>

<pre><code>public void DeleteAllSettingsLinkedToSoftware(Guid softwareId)
{
    _dbContext.Settings.Where(s =&gt; s.SoftwareId == softwareId).ForEachAsync(s =&gt; s.IsDeleted = true);
    _dbContext.SaveChanges();
}
</code></pre>

<p>However I'm having a hard time unit testing this method from the moment the <code>ForEachAsync()</code> method gets called.</p>

<p>So far I've used Moq to setup the dbContext to return the proper settings when the <code>Where()</code> is executed. 
My attempt:</p>

<pre><code>Setup(m =&gt; m.ForEachAsync(It.IsAny&lt;Action&lt;Setting&gt;&gt;(), CancellationToken.None));
</code></pre>

<p>My question is: How will I unit test the call to the <code>ForEachAsync()</code> method?</p>

<p>I've read online that some people say it's impossible to unit test some static methods, if that's true in my case I'm curious about alternatives to test as much of this method as possible.</p>

<p><strong>Edit</strong></p>

<p>My complete test code:</p>

<pre><code>[TestMethod]
public async Task DeleteAllSettingsLinkedToSoftware_Success()
{
    //Arrange
    var settings = new List&lt;Setting&gt;
    {
        new Setting
        {
            SoftwareId = SoftwareId1
        },
        new Setting
        {
            SoftwareId = SoftwareId1
        },
        new Setting
        {
            SoftwareId = SoftwareId1
        },
        new Setting
        {
            SoftwareId = SoftwareId2
        }
    }.AsQueryable();

    var queryableMockDbSet = GetQueryableMockDbSet(settings.ToList());
    queryableMockDbSet.As&lt;IQueryable&lt;Setting&gt;&gt;()
        .Setup(m =&gt; m.Provider)
        .Returns(new TestDbAsyncQueryProvider&lt;Setting&gt;(settings.Provider));

    DbContext.Setup(m =&gt; m.Settings).Returns(queryableMockDbSet.Object);

    _settingData = new SettingData(DbContext.Object, SettingDataLoggerMock.Object);

    //Act
    var result = await _settingData.DeleteAllSettingsLinkedToSoftwareAsync(SoftwareId1);

    //Assert
    DbContext.Verify(m =&gt; m.Settings);
    DbContext.Verify(m =&gt; m.SaveChanges());
    Assert.AreEqual(4, DbContext.Object.Settings.Count());
    Assert.AreEqual(SoftwareId2, DbContext.Object.Settings.First().SoftwareId);

}
</code></pre>

<p>I am aware that my Assert still needs more checks.</p>

<p>The GetQueryableMockDbSet method:</p>

<pre><code>public static Mock&lt;DbSet&lt;T&gt;&gt; GetQueryableMockDbSet&lt;T&gt;(List&lt;T&gt; sourceList) where T : class
{
    var queryable = sourceList.AsQueryable();

    var dbSet = new Mock&lt;DbSet&lt;T&gt;&gt;();
    dbSet.As&lt;IQueryable&lt;T&gt;&gt;().Setup(m =&gt; m.Provider).Returns(queryable.Provider);
    dbSet.As&lt;IQueryable&lt;T&gt;&gt;().Setup(m =&gt; m.Expression).Returns(queryable.Expression);
    dbSet.As&lt;IQueryable&lt;T&gt;&gt;().Setup(m =&gt; m.ElementType).Returns(queryable.ElementType);
    dbSet.As&lt;IQueryable&lt;T&gt;&gt;().Setup(m =&gt; m.GetEnumerator()).Returns(() =&gt; queryable.GetEnumerator());
    dbSet.Setup(d =&gt; d.Add(It.IsAny&lt;T&gt;())).Callback&lt;T&gt;(s =&gt; sourceList.Add(s));
    dbSet.Setup(d =&gt; d.AddRange(It.IsAny&lt;IEnumerable&lt;T&gt;&gt;())).Callback&lt;IEnumerable&lt;T&gt;&gt;(sourceList.AddRange);
    dbSet.Setup(d =&gt; d.Remove(It.IsAny&lt;T&gt;())).Callback&lt;T&gt;(s =&gt; sourceList.Remove(s));
    dbSet.Setup(d =&gt; d.RemoveRange(It.IsAny&lt;IEnumerable&lt;T&gt;&gt;())).Callback&lt;IEnumerable&lt;T&gt;&gt;(s =&gt;
    {
        foreach (var t in s.ToList())
        {
            sourceList.Remove(t);
        }
    });

    return dbSet;
}
</code></pre>
",https://stackoverflow.com/questions/50645140/c-unit-testing-method-that-calls-ef-core-extension-method,"['c#', 'unit-testing', 'asynchronous', 'mocking', 'moq']",1514,TRUE,3,2
Unit testing a Controller that makes Http requests using HttpClient,"<p>I need to write unit tests (and most importantly, i'm being asked to get code coverage) for this controller.</p>

<pre><code>public class MyController : Controller
{
    public async Task&lt;ActionResult&gt; Index()
    {
        ViewBag.Title = ""Home Page"";
        var httpClient = new HttpClient();
        var json = await httpClient.GetStringAsync(ConfigurationManager.AppSettings[""MyCustomAPI""]);
        var tasks = JsonConvert.DeserializeObject&lt;List&lt;MyObject&gt;&gt;(json);
        return View(tasks);
    }
}
</code></pre>

<p>I've been reading ideas for two days about this but i can't wrap my head around it.</p>

<p>I've been considering injecting the HttpClient like this:</p>

<pre><code>    private readonly HttpClient _httpClient;

    public TasksController(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }
</code></pre>

<p>But it's probably not a good idea to pass an HttpClient in the controller constructor.</p>

<p>Then i've been following <a href=""https://www.meziantou.net/2017/09/28/mocking-an-httpclient-using-an-httpclienthandler"" rel=""nofollow noreferrer"">this</a> guide that uses FakeItEasy but i couldn't adapt this solution to my requirements.</p>

<p>How should i proceed for testing this?</p>
",https://stackoverflow.com/questions/49781092/unit-testing-a-controller-that-makes-http-requests-using-httpclient,"['c#', 'unit-testing']",313,TRUE,3,1
Unit testing Flask app - mocking global variables in the app,"<p>I've got a Flask app module (<code>app.py</code>) which looks like this</p>

<pre><code># imports
...
from flask import Flask, request, Response
...

# module-level vars, including `logger` and `APP`
...
logger = None
APP = None
...

def init():
    """"""
    Initialisation of app resources, including `logger`
    """"""
    ...
    APP = Flask(__name__) 
    ...
    logger = logging.getLogger()
    ...
    ...

try:
    init()
except Exception as e:
    logger.error(str(e))

@APP.route('/healthcheck', methods=['GET'])
def healthcheck():
    """"""
    Healthcheck endpoint - just returns OK if the app
    initialised OK.
    """"""
    return 'OK'

@APP.route('/get_keys', method=['POST'])
def get_keys():
    """"""
    Main endpoint - accepts a POST request from a client
    containing either a CSV or JSON payload defining a set
    of geographic locations, and then returns some ""keys""
    for these.
    """"""
    try:
        logger.info('Extracting payload')
        # extract payload
        logger.info('Processing for keys')
        # do some stuff
        ...
        ...
    except Exception as e:
        logger.error(""Error: {}."".format(str(e)))

    # return response
</code></pre>

<p>I've got unit tests for the Flask app defined in a module <code>AppTests</code> in the <code>tests</code> subpackage.</p>

<pre><code># general imports including `unittest` etc.
# import app module as `app`

class AppTests(unittest.TestCase):
    """"""
    Flask app tests
    """"""

    @classmethod
    def setUpClass(self):

        app.APP.config['TESTING'] = True
        app.APP.config['DEBUG'] = False

        self.app = app.APP.test_client()

        # define other resources needed for `self.app`


    def test_healthcheck(self):

        res = self.app.get(path='/healthcheck')

        self.assertEqual(res.status_code, 200)

    def test_get_keys__csv(self):

        # define sample csv data in `data` variable

        headers = {
            'Accept-Encoding': 'identity,deflate,gzip,compress',
            'Content-Type': 'text/csv; charset=utf-8',
            'Content-Length': len(data)
        }

        res = self.app.post(path='/get_keys', headers=headers.items(), data=data)

        self.assertEqual(res.status_code, 200)
</code></pre>

<p>The test for the <code>healthcheck</code> endpoint passes but the test for the  <code>get_keys</code> endpoint fails.</p>

<pre><code>$ python -m unittest -v AppTests.AppTests.test_get_keys__csv
test_get_keys__csv (AppTests.AppTests) ... 
ERROR

======================================================================
ERROR: test_get_keys__csv (AppTests.AppTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File ""AppTests.py"", line 105, in test_get_keys__csv
    res = self.app.post(path='/get_keys', headers=headers.items(), data=data)
  File ""/path/to/venv/lib/python2.7/site-packages/werkzeug/test.py"", line 801, in post
    return self.open(*args, **kw)
  File ""/path/to/venv/lib/python2.7/site-packages/flask/testing.py"", line 127, in open
    follow_redirects=follow_redirects)
  File ""/path/to/venv/lib/python2.7/site-packages/werkzeug/test.py"", line 764, in open
    response = self.run_wsgi_app(environ, buffered=buffered)
  File ""/path/to/venv/lib/python2.7/site-packages/werkzeug/test.py"", line 677, in run_wsgi_app
    rv = run_wsgi_app(self.application, environ, buffered=buffered)
  File ""/path/to/venv/lib/python2.7/site-packages/werkzeug/test.py"", line 884, in run_wsgi_app
    app_rv = app(environ, start_response)
  File ""/path/to/venv/lib/python2.7/site-packages/flask/app.py"", line 1994, in __call__
    return self.wsgi_app(environ, start_response)
  File ""/path/to/venv/lib/python2.7/site-packages/flask/app.py"", line 1985, in wsgi_app
    response = self.handle_exception(e)
  File ""/path/to/venv/lib/python2.7/site-packages/flask/app.py"", line 1540, in handle_exception
    reraise(exc_type, exc_value, tb)
  File ""/path/to/venv/lib/python2.7/site-packages/flask/app.py"", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File ""/path/to/venv/lib/python2.7/site-packages/flask/app.py"", line 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File ""/path/to/venv/lib/python2.7/site-packages/flask/app.py"", line 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File ""/path/to/venv/lib/python2.7/site-packages/flask/app.py"", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File ""/path/to/venv/lib/python2.7/site-packages/flask/app.py"", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File ""/path/to/app.py"", line 205, in get_keys
    logger.error(""Error: {}."".format(str(e)))
AttributeError: 'NoneType' object has no attribute 'error'

----------------------------------------------------------------------
Ran 1 test in 0.036s

FAILED (errors=1)
</code></pre>

<p>It looks like the reference to the <code>logger</code> object in the <code>get_keys</code> endpoint in the app is null when I make the call to <code>self.app.post('/get_keys, headers=headers.items(), data=data)</code>. Every call to <code>logger.info</code> is generating an exception in the endpoint, which is caught and logged, and that's what I am seeing when I run the endpoint test.</p>

<p>Is there a way to mock this, or some how bypass the use of <code>logger</code> from the tests module itself? I would rather not modify the endpoint method itself.</p>
",https://stackoverflow.com/questions/48809346/unit-testing-flask-app-mocking-global-variables-in-the-app,"['python', 'flask', 'python-unittest']",1990,TRUE,3,1
Automating unit testing in PyQt5 using Gitlab&#39;s CI: QXcbConnection error,"<p>I am creating a GUI skeleton (for now) using PyQt5 and I have written some unit tests (using Python's unittest package) for testing its basic features. While trying to automate the procedure of running those unit tests each time a commit is made to this repository (currently hosted in GitLab), I have created the following <strong>.gitlab-ci.yml</strong> file:</p>

<pre><code>before_script:
 - sudo apt-get -qq update &amp;&amp; sudo apt-get -qq install -y python3
 - sudo apt-get -qq update
 - sudo apt-get -qq install -y python3 python-virtualenv python3-pip 
 - virtualenv venv
 - . venv/bin/activate
 - sudo apt-get install python3-pyqt5 -y
 - sudo apt-get install python3-pyqt5.qtmultimedia -y
 - cd test

stages: 
    - test

job1:
    stage: test
    script: python3 -m unittest -v test.GuiTest
</code></pre>

<p>Which does run (so the runners should have been set up correctly) but I am getting the <strong>following error when executing the script of job 1</strong>:</p>

<blockquote>
  <p>$ python3 -m unittest -v test
  QXcbConnection: Could not connect to display 
  bash: line 62: 50549 Aborted                 (core dumped) python3 -m unittest -v test
  ERROR: Job failed: exit status 1</p>
</blockquote>

<p>From the research I did, it seems that the CI server is facing problems trying to run a graphical application. However, for running the unit tests, no any actual window needs to be opened. The problem seems to be this particular line of the test (.py) file: </p>

<blockquote>
  <p>application = QApplication(sys.argv)</p>
</blockquote>

<p>Is there any way in which I can bypass this issue? I do understand that if the testing functions required any graphical feature (e.g. pressing a button) this would be a problem but in this case, there is no such need.</p>

<p>Thanks a lot.</p>

<p><strong>EDIT</strong>: Could you please have a look at this question since it was probably posted on an incorrect timing.</p>
",https://stackoverflow.com/questions/49184586/automating-unit-testing-in-pyqt5-using-gitlabs-ci-qxcbconnection-error,"['python', 'unit-testing', 'continuous-integration', 'gitlab', 'pyqt5']",975,TRUE,3,1
Unit testing a PUT method of the Django REST framework,"<p>I'm trying to write tests for <code>APIviewSet</code>. GET and POST work fine, but I can not combine tests for the PUT method. I think that the problem has to do with the path I pass to the function, but I can not figure out how to fix it. I found nothing in the documentation.</p>

<pre><code>class ResponseTracebackTestCase(TestCase):
""""""class for traceback""""""


class JustTest(ResponseTracebackTestCase):

    maxDiff = None

    def setUp(self):
        # Every test needs access to the request factory.
        self.factory = APIRequestFactory()
        self.time = datetime.datetime(2010, 1, 1)
        self.user = User.objects.create_user(
            username='admin', email='admin@admin.com', password='top_secret1', born_date=self.time, date_joined=self.time)
        self.view = ClientViewSet.as_view({'get': 'list', 'post': 'create', 'put': 'update'})

    #...some_code

    def test_admin_update(self):
        request = self.factory.put('/api/service/client/', {...some_data})
        force_authenticate(request, user=self.user)
        response = self.view(request, pk=1)
        self.assertResponseCodeEquals(response, 200)
        response.render()
        self.assertEqual(json.loads(response.content), {...some_data})
</code></pre>

<p>Traceback:</p>

<pre><code>  File ""/code/service/tests.py"", line 138, in test_admin_update
    self.assertResponseCodeEquals(response, 200)
  File ""/code/service/tests.py"", line 32, in assertResponseCodeEquals
    ) + '\n' + ''.join(format_list(response._init_stack))
AssertionError: 404 != 200 : Response code was '404', expected '200'
</code></pre>

<p>response.detail:</p>

<pre><code>{'detail': ErrorDetail(string='Not found.', code='not_found')}
</code></pre>
",https://stackoverflow.com/questions/51497676/unit-testing-a-put-method-of-the-django-rest-framework,"['django', 'unit-testing', 'django-rest-framework']",1189,FALSE,3,0
How to omit (remove) virtual environment (venv) from python coverage unit testing?,"<p><a href=""https://coverage.readthedocs.io/en/coverage-4.5.1a/source.html#source"" rel=""noreferrer"">https://coverage.readthedocs.io/en/coverage-4.5.1a/source.html#source</a></p>

<p>My coverage is also including “venv” folder and I would like to exclude it
no matter what I do even with --include or omit nothing works</p>

<pre><code>coverage run --omit /venv/* tests.py
</code></pre>

<p>This runs the test but still adds ""venv"" folder and dependencies and their % coverage</p>

<p>When I do</p>

<pre><code>coverage run --include tests.py
</code></pre>

<p>To run only tests - it says </p>

<pre><code>Nothing to do.
</code></pre>

<p>It is pretty annoying... can someone please help?</p>

<p><a href=""https://i.stack.imgur.com/JsrgG.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/JsrgG.png"" alt=""Python Coverage Report""></a></p>
",https://stackoverflow.com/questions/52133482/how-to-omit-remove-virtual-environment-venv-from-python-coverage-unit-testin,"['python', 'python-3.x', 'unit-testing', 'coverage.py', 'python-venv']",6399,TRUE,15,4
Mocking/Stubbing/unit testing mysql streaming query rows node js,"<p>I have a following function which uses <a href=""https://github.com/mysqljs/mysql#streaming-query-rows"" rel=""nofollow noreferrer"">streaming-query-rows</a> of mysql node js module. How can i unit test the below function and also i want to mock the database behavior instead of connecting to database while unit test.
'processRow' and ''wirteCsvFile'' function both are synchronous task.</p>

<pre><code>function executeTask(sql_connection,sql_query) {


 let query = sql_connection.query(sql_query);
 let showInfo = {};
 let showids = [];
 query
 .on('error', (error) =&gt; {
   console.error(`error executing query --&gt; ${error}`);
 })
 .on('result', function (row) {
   sql_connection.pause();
   processRow(row, showInfo, showids, function () {
     sql_connection.resume();
   });
 })
 .on('end', function () {
  showids.forEach(showid =&gt; {
    if (showInfo[showid].faults.length === 0) {
      delete showInfo[showid];
    }
  });
  wirteCsvFile(showInfo, (error, done) =&gt; {
    if (error) {
      console.error(error);
    } else {
      console.log(""done"");
      process.exit();
    }
  })
 });
}    
</code></pre>
",https://stackoverflow.com/questions/51738955/mocking-stubbing-unit-testing-mysql-streaming-query-rows-node-js,"['mysql', 'node.js', 'unit-testing', 'mocha.js', 'sinon']",1421,TRUE,2,2
&quot;auth_user does not exist&quot; when doing unit testing in django,"<p>I've been trying to solve this error for a week now and I can't seem to figure out how to fix this error. No one else who is using this repository is having the same problem as I am (I am up to date with the origin), so it has to be some sort of local issue, but I can't figure out what it would be. 
This happens everytime I try to run the django unit tests that we have written. There are no problems when I runserver or when I do migrations, only when testing:
<code>python manage.py test</code></p>

<p>_______ERROR MESSAGE:_________ </p>

<pre><code>Liams-MBP:GrammieGram Liam2$ python manage.py  test grams
Creating test database for alias 'default'...
Traceback (most recent call last):
  File ""/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/db/backends/utils.py"", line 64, in execute
    return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: relation ""auth_user"" does not exist


The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File ""manage.py"", line 22, in &lt;module&gt;
    execute_from_command_line(sys.argv)
  File ""/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py"", line 364, in execute_from_command_line
    utility.execute()
  File ""/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py"", line 356, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File ""/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/core/management/commands/test.py"", line 29, in run_from_argv
    super(Command, self).run_from_argv(argv)
  File ""/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/core/management/base.py"", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File ""/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/core/management/base.py"", line 330, in execute
    output = self.handle(*args, **options)
  File ""/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/core/management/commands/test.py"", line 62, in handle
    failures = test_runner.run_tests(test_labels)
  File ""/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/test/runner.py"", line 601, in run_tests
    old_config = self.setup_databases()
  File ""/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/test/runner.py"", line 546, in setup_databases
    self.parallel, **kwargs
  File ""/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/test/utils.py"", line 187, in setup_databases
    serialize=connection.settings_dict.get('TEST', {}).get('SERIALIZE', True),
  File ""/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/db/backends/base/creation.py"", line 69, in create_test_db
    run_syncdb=True,
  File ""/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/core/management/__init__.py"", line 131, in call_command
    return command.execute(*args, **defaults)
  File ""/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/core/management/base.py"", line 330, in execute
    output = self.handle(*args, **options)
  File ""/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/core/management/commands/migrate.py"", line 173, in handle
    self.sync_apps(connection, executor.loader.unmigrated_apps)
  File ""/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/core/management/commands/migrate.py"", line 311, in sync_apps
    self.stdout.write(""    Running deferred SQL...\n"")
  File ""/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/db/backends/base/schema.py"", line 93, in __exit__
    self.execute(sql)
  File ""/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/db/backends/base/schema.py"", line 120, in execute
    cursor.execute(sql, params)
  File ""/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/db/backends/utils.py"", line 64, in execute
    return self.cursor.execute(sql, params)
  File ""/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/db/utils.py"", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File ""/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/utils/six.py"", line 685, in reraise
    raise value.with_traceback(tb)
  File ""/Users/Liam2/anaconda3/lib/python3.6/site-packages/django/db/backends/utils.py"", line 64, in execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation ""auth_user"" does not exist
</code></pre>

<p>My grams/models.py</p>

<pre><code>from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
import datetime
import uuid
from django.contrib.postgres.fields import ArrayField
from django.db.models.signals import post_save
from django.dispatch import receiver



""""""
@brief A class that describes a user profile.

@field user -  the username of the user
@field usertype - the type of user profile (sender/receiver)
@filed contacts - the user's contact book, list of people they can contact
@field admins - and a list of admins, list of users who have admin
                privileges over this Profile object
""""""
class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    usertype = models.CharField(max_length=30, default=""sender"")
    contacts = ArrayField(models.CharField(max_length=150, default=""default""), default=[])
    admins = ArrayField(models.CharField(max_length=150, default=""default""), default=[])

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)


@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()


""""""
@brief Describes a gram message that a sender type Profile is
       able to send to a receiver type Profile.

@field send_username - the username of the sender profile
@field recp_username - the username of the receiver profile
@field sent_time - the time at which the Gram object was sent
@field display_until - the amount of time the Gram object will be visible
""""""
class Gram(models.Model):
    message = models.CharField(max_length=240)
    send_username = models.CharField(max_length=150, default=""default"")
    recp_username = models.CharField(max_length=150, default=""default"")
    sent_time = models.DateTimeField(null=True)
    display_until = models.DateTimeField(null=True)
    def __str__(self):
        return self.message

#function checks if another user can be added to the list of contacts
#active_user_type - logged in user; new_contact - the contact to be added
def validated_contact_add(active_user_type,new_contact):
    #check if the contact exists in the list of users
    if User.objects.filter(username=new_contact).exists():
        #check if the type of the logged in user is different from the one being added
        if active_user_type != Profile.objects.get(user=User.objects.get(username = new_contact)).usertype:
            return ""valid""
        else:
            return ""wrong type""
    else:
        return ""does not exist""
</code></pre>

<p>_________THINGS I'VE TRIED TO RESOLVE THIS (but failed):_______________</p>

<ul>
<li>deleting db </li>
<li>deleting local repository and recloning, and deleting db</li>
<li>makemigrations auth    and      makemigrations  (there were no
migrations to make) </li>
<li>using --fake (as suggested in
<a href=""https://stackoverflow.com/questions/46726380/django-1-8-test-issue-programmingerror-relation-auth-user-does-not-exist"">Django 1.8 test issue: ProgrammingError: relation &quot;auth_user&quot; does not exist</a>)</li>
<li>turning computer on an off again (as you can see, I'm pretty desperate)</li>
</ul>
",https://stackoverflow.com/questions/50544714/auth-user-does-not-exist-when-doing-unit-testing-in-django,"['python', 'django']",1768,TRUE,2,1
Missing default model permissions during unit testing in Django app,"<p>There are default model permissions for view/add/update/delete in database when applying migrations(it's working with my main DB): </p>

<pre><code>sadmonad=# select count(*) from auth_permission;
count 
-------
32
(1 row)
</code></pre>

<p>But in django.test it is not so: it only creates permissions for django modules like auth, session, contenttype, etc:</p>

<pre><code>test_sadmonad=# select count(*) from auth_permission;
count 
-------
24
(1 row)
</code></pre>

<p>I'm using Django 2.1.1(in my models I didn't specify custom permissions), so what should I do to fix this behaviour?</p>
",https://stackoverflow.com/questions/52777083/missing-default-model-permissions-during-unit-testing-in-django-app,"['django', 'django-unittest']",132,FALSE,2,0
Coroutines unit testing: exceptions are being swallowed and test passes,"<p>I have the next test function:</p>

<pre><code>@Test
fun `registerUser verify that loading was emitted`() {
    runBlocking {
        var emission = 0
        val viewModel = createSubject()
        viewModel.loading.observeForever {
            if (emission == 0) {
                assertNotNull(it)
                assertFalse(it!!) //MARK #1
                emission++
            }
        }
        async { viewModel.registerCommand.registerUser(""asd"") }.await()
        assertNotNull(viewModel.loading.value)
    }
}
</code></pre>

<p>I've wrapped <code>registerUser</code> invocation with <code>async</code> and <code>await</code> according to <a href=""https://github.com/Kotlin/kotlinx.coroutines/issues/61"" rel=""nofollow noreferrer"">this</a>.</p>

<p>Inside <code>registerUser</code>:</p>

<pre><code>fun registerUser(username: String) {
        launch {...
            withContext(ConfigurableDispatchers.IO) {...} 
            ...
        }
}
</code></pre>

<p>Whereas the class which has this function as a member inherits <code>CoroutineScope</code> and overrides <code>coroutineContext</code> with <code>ConfigurableDispatchers.Main + job</code>, whereas durint testing (in <code>@BeforeClass</code>-annotated method) <code>ConfigurableDispatchers.Main</code> is stubbed with </p>

<pre><code>object : MainCoroutineDispatcher() {
    @ExperimentalCoroutinesApi
    override val immediate: MainCoroutineDispatcher
        get() = throw UnsupportedOperationException()

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

<p>Also, <code>ConfigurableDispatchers.IO</code> is stubbed with <code>Dispatchers.Unconfined</code>.</p>

<p>The problem is that assertion exception thrown from <code>MARK #1</code> is just being printed in the console and than just swallowed up. Test passes...
As I can see and as I've debugged - all this method body is being executed in a single thread, so if exception is being caught at the default <code>UncaughtExceptionHandler</code>, then, as I understand, **test should fail **. 
What is also interesting, when I wrap <code>MARK #1</code> (the failing line) with <code>try catch</code> block, whereas I am catching an <code>Exception</code> - nothing drops in the handler...</p>

<p>Why?</p>
",https://stackoverflow.com/questions/53450216/coroutines-unit-testing-exceptions-are-being-swallowed-and-test-passes,"['unit-testing', 'kotlin', 'kotlinx.coroutines']",1076,FALSE,2,0
How to write unit testing for functions in React js?,"<p>I have a function in my App.js file as below.</p>

<pre><code>function unCamelCase(val) {
   return val.replace(/([a-z])([A-Z])/g, '$1 $2')
        .replace(/\b([A-Z]+)([A-Z])([a-z])/, '$1 $2$3')
        .replace(/^./, function(str){ return str.toUpperCase();   })
}
</code></pre>

<p>How to write unit testing for the above function.</p>

<p>Thanks in Advance.</p>
",https://stackoverflow.com/questions/52189806/how-to-write-unit-testing-for-functions-in-react-js,"['reactjs', 'unit-testing']",1432,TRUE,2,1
Mock Unit Testing - Getting details of the classes implementing interface,"<p>I have a User Interface lets call it <code>IUser</code>. 
There are two implementations of this: <code>AdminUser and NormalUser</code>. </p>

<p>Now, I am trying to use these user classes via Unit Testing(Mocking). </p>

<p>I mock the interface as follows: </p>

<pre><code>var mockUser = new Mock&lt;IUser&gt;();

mockUser.get(""username"");
</code></pre>

<p>I have added breakkpoints throughout the classes but I am not sure which instance of the interface is getting called i.e <code>AdminUser or NormalUser</code>.</p>

<p>It never stops at the debug points and no clue from the mockUser instance. </p>

<p><strong>How can I get the details of the class being called by the mockUser mock instance?</strong> </p>

<p>Thanks in advance. </p>
",https://stackoverflow.com/questions/48123186/mock-unit-testing-getting-details-of-the-classes-implementing-interface,"['c#', 'unit-testing', 'mocking', 'moq']",740,TRUE,2,2
How to perform unit testing on react-table using jest?,"<p>How to perform unit testing on react-table using jest? My table will have ajax calls inside onfetchdata.</p>
",https://stackoverflow.com/questions/52662865/how-to-perform-unit-testing-on-react-table-using-jest,"['reactjs', 'react-native', 'jestjs', 'enzyme', 'react-table']",1150,FALSE,2,0
Reducer returns state as &#39;undefined&#39; during Unit Testing with Enzyme,"<p>Testing Redux connect component:The case where I try to test the expected result from a specific Action FETCH_COUNTRY_LIST is failing.Do I need to add the custom middleware in my mockStore. </p>

<pre><code>  REACT-REDUX (Mount + wrapping in &lt;Provider&gt;) ClearAll Component
    ✓ +++ contains ClearAll component
    ✓ +++ contains clear All text
    ✓ +++ check action on dispatching 
    ✓ +++ check reducer INITIAL_STATE
    1) +++ check reducer FETCH_COUNTRY_LIST
</code></pre>

<p>I am not sure why is the state coming as 'undefined' for countryList and selectedCountries.I have added a wrapper.Update(). 
Is there anything that I am doing wrong in the below test case.</p>

<pre><code>import React from 'react';
import expect from 'expect';
import { mount } from 'enzyme';
import { Provider } from ""react-redux"";
import configureMockStore from 'redux-mock-store';
import ClearAllFilters from './ClearAllFilters';
import { deselectAllCountry, deselectAllRegion, deselectAllSector } from '../../actions/filterActions';
import filtersReducer from '../../reducers/filtersReducer/filtersReducer';
//import { COUNTRY_LIST } from '../../constants/filterConstants';

const mockStore = configureMockStore();

const store = mockStore({filters:
{
  countryList: [],
  regionList: [],
  sectorList: [],
  isAllSelected: false,
  isAllSelectedR: false,
  isAllSelectedS: false,
  selectedCountries: [],
  selectedRegions: [],
  selectedSectors: []
}
});

const initialState = {
  countryList: [],
  regionList: [],
  sectorList: [],
  isAllSelected: false,
  isAllSelectedR: false,
  isAllSelectedS: false,
  selectedCountries: [],
  selectedRegions: [],
  selectedSectors: []
};

const wrapper = mount(&lt;Provider store={store}&gt;&lt;ClearAllFilters /&gt;&lt;/Provider&gt;);

//*************Testing for ClearAllFilters React Component**********
describe('REACT-REDUX (Mount + wrapping in &lt;Provider&gt;) ClearAll Component',()=&gt;{

  //Ensures it clears out all actions from our mockStore before each test suite.
  beforeEach(() =&gt; {
    store.clearActions();
  });

  it('+++ contains ClearAll component', () =&gt; {
    expect(wrapper.find(ClearAllFilters).length).toEqual(1)
  });

  it('+++ contains clear All text', () =&gt; {
    expect(wrapper.text()).toEqual('Clear All')
  });

  //Unit tests for Redux Action Creators.
  it('+++ check action on dispatching ', () =&gt; {
    let action
    store.dispatch(deselectAllCountry())
    store.dispatch(deselectAllRegion())
    store.dispatch(deselectAllSector())
    action = store.getActions()
    expect(action[0].type).toBe('COUNTRIES_DESELECT_ALL')
    expect(action[1].type).toBe('REGIONS_DESELECT_ALL')
    expect(action[2].type).toBe('SECTORS_DESELECT_ALL')
  });

  //Unit test for Redux Reducers.
  it('+++ check reducer INITIAL_STATE', () =&gt; {
    expect(filtersReducer(undefined, { type: 'dummy_action' })).toEqual(initialState);
  });

   it('+++ check reducer FETCH_COUNTRY_LIST', () =&gt; {
     const expectedState = {
     countryList: COUNTRY_LIST,
     selectedCountries: COUNTRY_LIST
     };
    wrapper.update();
    expect(filtersReducer(initialState, { type: 'FETCH_COUNTRY_LIST' })).toEqual(...initialState, expectedState);
   });

});

Test Results :
Expected value to equal:
  {""countryList"": [{""checked"": false, ""name"": ""United States"", ""value"": ""USA""}, {""checked"": false, ""name"": ""United Kingdom"", ""value"": ""GBR""}, {""checked"": false, ""name"": ""India"", ""value"": ""IND""}, {""checked"": false, ""name"": ""Singapore"", ""value"": ""SNG""}, {""checked"": false, ""name"": ""Japan"", ""value"": ""JPN""}, {""checked"": false, ""name"": ""South Africa"", ""value"": ""ZAF""}, {""checked"": false, ""name"": ""Germany"", ""value"": ""DEU""}, {""checked"": false, ""name"": ""China"", ""value"": ""CHN""}, {""checked"": false, ""name"": ""France"", ""value"": ""FRA""}], ""selectedCountries"": [{""checked"": false, ""name"": ""United States"", ""value"": ""USA""}, {""checked"": false, ""name"": ""United Kingdom"", ""value"": ""GBR""}, {""checked"": false, ""name"": ""India"", ""value"": ""IND""}, {""checked"": false, ""name"": ""Singapore"", ""value"": ""SNG""}, {""checked"": false, ""name"": ""Japan"", ""value"": ""JPN""}, {""checked"": false, ""name"": ""South Africa"", ""value"": ""ZAF""}, {""checked"": false, ""name"": ""Germany"", ""value"": ""DEU""}, {""checked"": false, ""name"": ""China"", ""value"": ""CHN""}, {""checked"": false, ""name"": ""France"", ""value"": ""FRA""}]}
Received:
  {""countryList"": **undefined**, ""isAllSelected"": false, ""isAllSelectedR"": false, ""isAllSelectedS"": false, ""regionList"": [], ""sectorList"": [], ""selectedCountries"": **undefined**, ""selectedRegions"": [], ""selectedSectors"": []}
</code></pre>

<p>This is the code for my Store: </p>

<pre><code>import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension'
import rootReducer from '../reducers/rootReducer'
import gridQueryMiddleware from ""../services/gridQueryMiddleware"";

export const configureStore = (preloadedState) =&gt; {
  const middlewares = [gridQueryMiddleware];
  const middlewareEnhancer = applyMiddleware(...middlewares);

  const storeEnhancers = [middlewareEnhancer];

  const composedEnhancer  = composeWithDevTools(...storeEnhancers);

  const store = createStore(
    rootReducer,
    preloadedState,
    composedEnhancer
  );

  if (process.env.NODE_ENV !== 'production') {
    if (module.hot) {
      module.hot.accept('./reducers/rootReducer', () =&gt; {
        const newRootReducer = require('./reducers/rootReducer').default;
        store.replaceReducer(newRootReducer)
      })
    }
  }

  return store;
};
</code></pre>
",https://stackoverflow.com/questions/52857662/reducer-returns-state-as-undefined-during-unit-testing-with-enzyme,"['reactjs', 'unit-testing', 'redux', 'enzyme', 'redux-mock-store']",727,FALSE,2,0
How to read Android resource file values in unit testing,"<p>I have an array resource. I want to make test to read and parse the values from xml resource. Here is the codes.</p>
<pre><code>&lt;string-array name=&quot;names&quot;&gt;
    &lt;item&gt;Name1[?]200&lt;/item&gt;
    &lt;item&gt;Name2[?]125&lt;/item&gt;
    &lt;item&gt;Name3[?]142&lt;/item&gt;
&lt;/string-array&gt;
</code></pre>
<p>I want to capture above string resource and parse like below test case. But I couldn't achive.</p>
<pre><code>@RunWith(MockitoJUnitRunner.class)
public class ReadAndParseNamesTest {

@Mock
private Context mockApplicationContext;
@Mock
private Resources mockContextResources;

@Test
public void readAndParseNamesTest() {
    
    MockitoAnnotations.initMocks(this);

    when(mockApplicationContext.getResources()).thenReturn(mockContextResources);

     String[] marray = {&quot;mock main class&quot;};
    when(mockContextResources.getStringArray(R.array.allah_names))
            .thenReturn(marray);
    for(int i = 0;i&lt;marray.length;i++){
        String[] deger = marray[i].split(&quot;[?]&quot;);
        System.out.println(&quot;Deger &quot;+i+&quot;: &quot;+deger[0] + &quot; &quot;+ deger[1]);
    }
  }
}
</code></pre>
<p>I am getting <code>java.lang.ArrayIndexOutOfBoundsException: 1</code> exception because i can't get actual values. Any help will be appreciated. Thank you.</p>
",https://stackoverflow.com/questions/51408851/how-to-read-android-resource-file-values-in-unit-testing,"['android', 'unit-testing', 'mockito']",5101,TRUE,2,1
Mocking/Stubbing CosmosDB connection to perform unit testing node js,"<p>I am looking for any method that I can use to mock connections to Azure in order to perform Unit Testing. Are there any good reliable mocking npm modules available.</p>
",https://stackoverflow.com/questions/51843533/mocking-stubbing-cosmosdb-connection-to-perform-unit-testing-node-js,"['node.js', 'unit-testing', 'mocking', 'azure-cosmosdb']",2561,TRUE,2,2
How to mock ftp server for unit testing in nodeJS,"<p>Could anybody tell me how to mock the FTP connection and downloading the file from FTP client for unit testing in nodeJS?</p>

<p>I'm using FTP node module for connecting to FTP/SFTP client
(<a href=""https://www.npmjs.com/package/ftp"" rel=""nofollow noreferrer"">https://www.npmjs.com/package/ftp</a>)</p>
",https://stackoverflow.com/questions/52018667/how-to-mock-ftp-server-for-unit-testing-in-nodejs,"['node.js', 'ftp', 'mocha.js', 'sinon', 'chai']",2572,TRUE,2,2
How to avoid combinatorial explosion in unit testing Django views,"<p>I have a rather complicated Django (Rest Framework) view which updates an object in the database.</p>

<p>In order to update the object, some conditions need to be met (these aren't the real conditions, but they're similar):</p>

<ol>
<li>The user has to be logged in</li>
<li>The username needs to begin with <code>admin</code></li>
<li>The update data needs to be valid according to some rules</li>
<li>A separate expensive function <code>is_moon_phase_ok</code> needs to return <code>True</code></li>
</ol>

<p>I'm trying to write a solid set of unit tests for this view and the scenarios that I've come up with are the following:</p>

<pre><code>when not logged in, return 401
when not logged in, return {""fail"": ""login""}
when not logged in, don't touch database
when not logged in, don't check moon phase
when username is not admin_*, return 401
when username is not admin_*, return {""fail"": ""username""}
when username is not admin_*, don't touch database
when username is not admin_*, don't check moon phase
when invalid data, return 400
when invalid data, return {""fail"": ""data""}
when invalid data, don't touch database
when invalid data, don't check moon phase
when logged in, return 200
when logged in, return updated data
when logged in, check moon phase
when logged in, update database
</code></pre>

<p>As you can tell, each of these unit tests will take quite a bit of code to set up and then execute. In my case, it's between 7 and 20 lines of code per unit test.</p>

<p>Imagine if the requirements change, and they do change, how much of a pain it would be to overlook the test cases, make sure they still apply, update them according to the new requirements, etc.</p>

<p>Is there a better way of accomplishing the same thing, with the same test coverage, but with less labor?</p>
",https://stackoverflow.com/questions/52641360/how-to-avoid-combinatorial-explosion-in-unit-testing-django-views,"['python', 'django', 'unit-testing', 'django-rest-framework']",372,TRUE,2,1
Android 3.1: Unit Testing a Class that Request User Permissions,"<p>I have a one button app that makes a phone call when pressed. The app uses MVP architecture. The logic to request the permission from a user to make a phone call was placed in the presenter (P) package.   </p>

<p>Now, I'd like to setup a unit test that verifies that the class accurately requests the user permission to make a phone call yet I'm having issues getting started. There is an SO question: <a href=""https://stackoverflow.com/questions/33929937/android-marshmallow-test-permissions-with-espresso/33935435"">Android Marshmallow: Test permissions with Espresso?</a> that attempts to address this problem stating one has to use UIAutomation and Espresso together. It's just not a clear enough answer to apply to this problem. </p>

<p>Can someone provide a solution to help setup this unit test?</p>

<p><strong>MainActivityPresenter class</strong></p>

<pre><code>public class mainActivityPresenter {
    final int REQUEST_PHONE_CALL = 1;

    public void checkPhonePermissions(View view, MainActivity mainActivity){
        ActivityCompat.requestPermissions(mainActivity, new String[]{Manifest.permission.CALL_PHONE},REQUEST_PHONE_CALL);
    }

 }
</code></pre>
",https://stackoverflow.com/questions/49765818/android-3-1-unit-testing-a-class-that-request-user-permissions,"['java', 'android', 'unit-testing', 'android-permissions', 'android-mvp']",1005,TRUE,2,1
How to do unit testing in react native that uses firebase?,"<p>Im quite new to jest unit testing, so stuff like mocking modules is confusing.</p>

<p>In react native, there is a component that uses firebase databse that returns data from a given ref:</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>// when the data of the current user is available
userRef.child(user.uid).on('value', snap =&gt; {
  // check of val() consists data
  if (snap.val()) {
    let
      authUser = snap.val(),
      isPatient = authUser.type === ""Patient"",
      // We update the state object so that the component is re-rendered
      this.setState({
        // the ID of the current user
        authUserUID: user.uid,
        // the type of the current user (i.e. Doctor or Patient)
        authUserType: snap.val().type,
        // title of the dashboard based on the current user type
        activeTitle: snap.val().type === ""Doctor"" ? ""My Patients"" : ""My Doctors"",
      });
  }
});</code></pre>
</div>
</div>
</p>

<p>I'm now trying to do unit testing which uses this 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>import 'react-native'
import React from 'react'
import renderer from 'react-test-renderer'
import LaunchScreen from ""../../App/Containers/LaunchScreen"";

test('LaunchScreen', () =&gt; {
  const tree = renderer.create( &lt;LaunchScreen / &gt; ).toJSON()
  expect(tree).toMatchSnapshot()
})</code></pre>
</div>
</div>
</p>

<p>But it gives a weird error</p>

<blockquote>
  <p>RNFirebase core module was not found natively on iOS, ensure you have correctly included the RNFirebase pod in your projects <code>Podfile</code> and have run <code>pod install</code></p>
</blockquote>

<p>I have no idea since the firebase does return data if I run it. So why is it saying that RNFirebase cannot be found?</p>

<p>Thanks</p>

<h1>Update</h1>

<p>One of the answers have given a nice step by step instructions, and although it solves partially the proposed question; the error still persists. For example; I'm now getting this new error:</p>

<blockquote>
  <p>console.error node_modules\react-test-renderer\cjs\react-test-renderer.development.js:5530
      The above error occurred in the  component:
          in LaunchScreen</p>
  
  <p>Consider adding an error boundary to your tree to customize error handling behavior.</p>
  
  <p>TypeError: _reactNativeFirebase2.default.app is not a function</p>
</blockquote>
",https://stackoverflow.com/questions/49701000/how-to-do-unit-testing-in-react-native-that-uses-firebase,"['javascript', 'firebase', 'unit-testing', 'react-native', 'jestjs']",5566,TRUE,7,2
Firebase Unit Testing: The default Firebase app does not exist,"<p>I try to mock my firebase app but at a point, I don't find a solution to make it work and there is no example in the firebase documentation to make it that way.</p>

<p>In my code, I have this method call to initialize firebase:</p>

<p>ServiceAccount can be a JSON path or the string coming from ENV settings for test purpose</p>

<pre><code>initialize(): void {
    if (!fs.existsSync(this.serviceAccount) &amp;&amp; this.serviceAccount) {
        this.serviceAccount = JSON.parse(this.serviceAccount);
    }
    firebaseAdmin.initializeApp({
        credential: firebaseAdmin.credential.cert(this.serviceAccount),
        databaseURL: this.url
    });
    firebaseAdmin.auth();
    firebaseAdmin.database.enableLogging(true);
    this.database = firebaseAdmin.database();
}
</code></pre>

<p>Then in my test, wrote this:</p>

<pre><code>certStub = sinon.stub(admin.credential, 'cert').returns('');
firebaseAdminInitStub = sinon.stub(admin, 'initializeApp');
authStub = sinon.stub(admin, 'auth')

firebaseDatabaseStub = sinon.stub(admin, 'database');
firebaseDatabaseStub.get(() =&gt; (() =&gt; ({ref: refStub})));
refStub.withArgs(FirebaseContact.ref).returns({push: pushStub});
pushStub.withArgs(Contact).returns(Promise.resolve({ref: 'new_ref'}));

// Initialize it for the coming test
firebase.initialize();
</code></pre>

<p>Basically, I mostly use their code for the real-time database usage, but for the authenticating part, it gave me the error:</p>

<blockquote>
  <p>The default Firebase app does not exist. Make sure you call
  initializeApp() before using any of the Firebase services.</p>
</blockquote>

<p>Throwing in :</p>

<blockquote>
  <p>firebaseAdmin.auth();</p>
</blockquote>

<pre><code>Exception:
at FirebaseAppError.FirebaseError [as constructor] (node_modules/firebase-admin/lib/utils/error.js:39:28)
addressBook.app_test |       at FirebaseAppError.PrefixedFirebaseError [as constructor] (node_modules/firebase-admin/lib/utils/error.js:85:28)
addressBook.app_test |       at new FirebaseAppError (node_modules/firebase-admin/lib/utils/error.js:119:28)
addressBook.app_test |       at FirebaseNamespaceInternals.Object.&lt;anonymous&gt;.FirebaseNamespaceInternals.app (node_modules/firebase-admin/lib/firebase-namespace.js:105:19)
addressBook.app_test |       at FirebaseNamespace.Object.&lt;anonymous&gt;.FirebaseNamespace.app (node_modules/firebase-admin/lib/firebase-namespace.js:372:30)
addressBook.app_test |       at FirebaseNamespace.Object.&lt;anonymous&gt;.FirebaseNamespace.ensureApp (node_modules/firebase-admin/lib/firebase-namespace.js:388:24)
addressBook.app_test |       at FirebaseNamespace.fn (node_modules/firebase-admin/lib/firebase-namespace.js:268:30)
addressBook.app_test |       at Firebase.initialize (src/firebase/firebase.ts:29:23)
addressBook.app_test |       at Object.done (src/tests/api/contact.test.ts:43:18)
</code></pre>

<p>What I know, <code>initializeApp</code> should be called to create the app, but as it has been stub (according to the example) it can create an app. So Should I try to stub the auth part or use the <code>initializeApp</code> differently ?</p>

<p>Any idea ? :(</p>
",https://stackoverflow.com/questions/49518835/firebase-unit-testing-the-default-firebase-app-does-not-exist,"['node.js', 'firebase', 'firebase-realtime-database']",2430,TRUE,2,1
Does Live unit testing work in Visual Studio for Mac,"<p>Does anyone know if/when Microsoft will support live testing in Visual Studio 2017 on Mac? If it is already supported how is it set up? How is it accessed?</p>
",https://stackoverflow.com/questions/48834081/does-live-unit-testing-work-in-visual-studio-for-mac,"['macos', 'visual-studio-2017']",114,FALSE,2,0
Unit testing with a static final field from system properties,"<p>I have an interface with a public static final field which is pulled from system properties. It looks like this:</p>



<pre class=""lang-java prettyprint-override""><code>public interface MyInterface {
    public static final String MYFIELD = System.getProperty(""MyField"");
    ...
}
</code></pre>

<p>I am writing a unit test which uses this field. Even when I set the system property in a static initialiser before the test, the interface field returns null</p>

<pre class=""lang-java prettyprint-override""><code>System.out.println(System.getProperty(""MYField"")); //returns ""MyField""
System.out.println(MyInterface.MYFIELD); //returns null
</code></pre>

<p>Why is the interface field not set? What is the best way to handle this situation? I can't just set the field value in my test because it is final static.</p>

<p>UPDATE:</p>

<p>I may have missed out an important detail; I am using Mocktio. It looks something like this</p>

<pre class=""lang-java prettyprint-override""><code>public class MyTest {

    static {System.setProperty(""MyField"", ""MyValue"");}

    @Test
    public void test1() {
        try {
            final MyInterface mockInterface = Mockito.mock(MyInterface.class);
            ...
        }
     }
}
</code></pre>
",https://stackoverflow.com/questions/50950431/unit-testing-with-a-static-final-field-from-system-properties,"['java', 'junit']",1723,TRUE,1,2
.Net Core Identity Unit Testing - Add Data To Mocked UserStore,"<p>I'm currently trying to unit test my <code>Auth</code> service that uses <code>UserManager</code> and <code>Role Manager</code> from <code>Microsoft.AspNetCore.Identity</code>.  I have a few tests up and running by using the code below.  I mock the <code>UserStore</code> but don't add any data to it.</p>

<pre><code>var dbContextMock = new Mock&lt;ApplicationDbContext&gt;();
var mockUserManager = new Mock&lt;UserManager&lt;ApplicationUser&gt;&gt;(
    new Mock&lt;IUserStore&lt;ApplicationUser&gt;&gt;().Object,
    null,
    null,
    null,
    null,
    null,
    null,
    null,
    null);

var mockRoleManager = new Mock&lt;RoleManager&lt;IdentityRole&gt;&gt;(
    new Mock&lt;IRoleStore&lt;IdentityRole&gt;&gt;().Object,
    null,
    null,
    null,
    null);

var authService = new AuthService(dbContextMock.Object, mockRoleManager.Object, mockUserManager.Object, Configuration);

mockUserManager
    .Setup(x =&gt; x.FindByIdAsync(It.IsAny&lt;string&gt;()))
    .ReturnsAsync(() =&gt; new ApplicationUser { UserName = ""user"" });

mockUserManager
    .Setup(x =&gt; x.RemoveClaimAsync(It.IsAny&lt;ApplicationUser&gt;(), It.IsAny&lt;Claim&gt;()))
    .ReturnsAsync(() =&gt; IdentityResult.Success);

Ack ack = await authService.DeleteClaim(new dtoClaim { Type = ""Type"", Value = ""Value"" });

Assert.IsNotNull(ack.StatusMessage);
</code></pre>

<p>I have an another test that gets and returns all the <code>Users</code> by </p>

<pre><code>IEnumerable&lt;ApplicationUser&gt; users = _userManager.Users.ToList();
</code></pre>

<p>So, is there a way I get mock <code>userManager.Users</code>?</p>

<p>I've tried </p>

<pre><code>mockUserManager
    .Setup(x =&gt; x.Users)
    .ReturnsAsync(userList);
</code></pre>

<p>But get the error </p>

<p><code>ISetup&lt;UserManager&lt;ApplicationUser&gt;, IQueryable&lt;ApplicationUser&gt;&gt;</code> does not contain a definition for <code>ReturnsAsync</code></p>

<p>Also, Question 2. Is there a way I can initialize the mocked UserStore by adding a list of <code>Users</code> to it then have the User Manager refer to that user store instead of me having to manually return the list in the <code>ReturnsAsync</code></p>

<p>So, instead of </p>

<pre><code>mockUserManager
    .Setup(x =&gt; x.FindByIdAsync(It.IsAny&lt;string&gt;()))
    .ReturnsAsync(() =&gt; new ApplicationUser { UserName = ""user"" });
</code></pre>

<p>use</p>

<pre><code>mockUserManager
    .Setup(x =&gt; x.FindByIdAsync(It.IsAny&lt;string&gt;()))
    .ReturnsAsync(() =&gt; Code here to actually run FindByIdAsync against UserStore);
</code></pre>
",https://stackoverflow.com/questions/51365875/net-core-identity-unit-testing-add-data-to-mocked-userstore,"['c#', 'unit-testing', '.net-core', 'asp.net-identity', 'moq']",567,FALSE,1,0
React ES6 with chai/sinon: Unit testing XHR in component,"<p>I have a React utility component that reads the contents of a URL:</p>

<pre><code>'use strict';

export class ReadURL {

  getContent = (url) =&gt; {
      return new Promise((resolve, reject) =&gt; {
console.log('Promise')
          let xhr = new XMLHttpRequest();

          xhr.open(""GET"", url, false);
          xhr.onreadystatechange = () =&gt; {
console.log('onreadystatechange', xhr.readyState)
              if (xhr.readyState === 4) {
                  if (xhr.status === 200 || xhr.status == 0) {
console.log('200')
                      var allText = xhr.responseText;
                      resolve(allText);
                  } else {
                      reject('ajax error:' + xhr.status + ' ' + xhr.responseText);
                  }
              }
          };
          xhr.send(null);
      });
  };

}
</code></pre>

<p>I have been trying to use Sinon's <code>useFakeXMLHttpRequest()</code> to stub the xhr, but no matter how I try, I can't get it to actually process - It currently passes with a false positive, without ever receiving <code>onreadystatechange</code> event.
I've tried with XHR and Axios packages as well as native XMLHttpRequest, with the request wrapped in a promise and not, a whole bunch of different tacks, and read untold blog posts, docs and SO questions and I'm losing the will to live... The component itself works perfectly.</p>

<p>I've managed to get tests working with promises and with stubbed module dependancies, but this has me stumped.</p>

<p>This is the test:</p>

<pre><code>import chai, { expect } from 'chai';
import sinon, { spy } from 'sinon';

import {ReadURL} from './ReadURL';


describe('ReadURL', () =&gt; {

  beforeEach(function() {

    this.xhr = sinon.useFakeXMLHttpRequest();

    this.requests = [];
    this.xhr.onCreate = (xhr) =&gt; {
console.log('xhr created', xhr)
      this.requests.push(xhr);
    };

    this.response = 'Response not set';
  });

  afterEach(function() {
    this.xhr.restore();

    this.response = 'Response not set';
  });

  it('should get file content from an xhr request', () =&gt; {
    const readURL = new ReadURL(),
          url = 'http://dummy.com/file.js',
          urlContent = `&lt;awe.DisplayCode
            htmlSelector={'.awe-login'}
            jsxFile={'/src/js/components/AncoaAwe.js'}
            jsxTag={'awe.Login'}
            componentFile={'/src/js/components/Login/Login.js'}
          /&gt;`;

    readURL.getContent(url).then((response) =&gt;{
console.log('ReadURL-test response', response)
            expect(response).to.equal(urlContent);
          });


    window.setTimeout(() =&gt; {
console.log('ReadURL-test trigger response')
      this.requests[0].respond(200,
        {
          'Content-Type': 'application/json'
        },
        urlContent
      )
    , 10});

  });

});
</code></pre>

<p>The <code>console.log('xhr created', xhr)</code> is triggered, and output confirms that it's a sinon <code>useFakeXMLHttpRequest</code> request.</p>

<p>I have created a repo of the app with the bare minimum required to see the components functions:
<a href=""https://github.com/DisasterMan78/awe-testcase"" rel=""nofollow noreferrer"">https://github.com/DisasterMan78/awe-testcase</a></p>

<p>I haven't got a sample online currently, as I don't know of any online sandboxes that run tests. If I can find a service for that I'll try to add a proof of failed concept.</p>

<p>Help me Obi Wan-Kenobi. You're my only hope!</p>
",https://stackoverflow.com/questions/48106007/react-es6-with-chai-sinon-unit-testing-xhr-in-component,"['reactjs', 'unit-testing', 'xmlhttprequest', 'sinon', 'chai']",390,TRUE,1,1
Unit Testing a Web API end point that you upload files,"<p>I have a web api end point that i want to unit test. I have a custom <code>SwaggerUploadFile</code> attribute that allows a file upload button on the swagger page. But for unit testing I cant figure out how to pass in a file.</p>

<p>For unit testing I am using: <em>Xunit</em>, <em>Moq</em> and <em>Fluent Assertions</em></p>

<p>Below is my controller with the endpoint:</p>

<pre><code>public class MyAppController : ApiController
{
    private readonly IMyApp _myApp;

    public MyAppController(IMyApp myApp)
    {
         if (myApp == null) throw new ArgumentNullException(nameof(myApp));
         _myApp = myApp;
    }

    [HttpPost]
    [ResponseType(typeof(string))]
    [Route(""api/myApp/UploadFile"")]
    [SwaggerUploadFile(""myFile"", ""Upload a .zip format file"", Required = true, Type = ""file"")]
    public async Task&lt;IHttpActionResult&gt; UploadFile()
    {
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        var provider = await Request.Content.ReadAsMultipartAsync();
        var bytes = await provider.Contents.First().ReadAsByteArrayAsync();
        try
        {
           var retVal = _myApp.CheckAndSaveByteStreamAsync(bytes).Result;
           if(retVal)
            {
                return
                    ResponseMessage(
                        new HttpResponseMessage(HttpStatusCode.OK)
                        {
                            Content = new StringContent(JsonConvert.SerializeObject(
                                new WebApiResponse
                                {
                                    Message = ""File has been saved""
                                }), Encoding.UTF8, ""application/json"")
                        });
            }             
            return ResponseMessage(
                new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    Content = new StringContent(JsonConvert.SerializeObject(
                        new WebApiResponse
                        {
                            Message = ""The file could not be saved""
                        }), Encoding.UTF8, ""application/json"")
                });
        }
        catch (Exception e)
        {
            //log error
            return BadRequest(""Oops...something went wrong"");
        }
    }    
}
</code></pre>

<p>Unit test I have so far:</p>

<pre><code>    [Fact]
    [Trait(""Category"", ""MyAppController"")]
    public void UploadFileTestWorks()
    {
        //Arrange

        _myApp.Setup(x =&gt; x.CheckAndSaveByteStreamAsync(It.IsAny&lt;byte[]&gt;())).ReturnsAsync(() =&gt; true);
        var expected = JsonConvert.SerializeObject(
            new WebApiResponse
            {
                Message = ""The file has been saved""
            });

        var _sut = new MyAppController(_myApp.Object);


        //Act
        var retVal = _sut.UploadFile();
        var content = (ResponseMessageResult)retVal.Result;
        var contentResult = content.Response.Content.ReadAsStringAsync().Result;
        //Assert
        contentResult.Should().Be(expected); 
    }
</code></pre>

<p>The above fails as when it hits this line <code>if(!Request.Content.IsMimeMultipartContent())</code> we get a <code>NullReferenceException</code> >  <code>""{""Object reference not set to an instance of an object.""}""</code></p>

<p><strong>Best Answer Implemented:</strong></p>

<p>Created an interface:</p>

<pre><code> public interface IApiRequestProvider
    {
        Task&lt;MultipartMemoryStreamProvider&gt; ReadAsMultiPartAsync();

        bool IsMimeMultiPartContent();
    }
</code></pre>

<p>Then an implementation:</p>

<pre><code>public class ApiRequestProvider : ApiController, IApiRequestProvider
    {       
        public Task&lt;MultipartMemoryStreamProvider&gt; ReadAsMultiPartAsync()
        {
            return Request.Content.ReadAsMultipartAsync();
        }
        public bool IsMimeMultiPartContent()
        {
            return Request.Content.IsMimeMultipartContent();
        }
    }
</code></pre>

<p>Now my controller uses constructor injection to get the RequestProvider:</p>

<pre><code> private readonly IMyApp _myApp;
 private readonly IApiRequestProvider _apiRequestProvider;

 public MyAppController(IMyApp myApp, IApiRequestProvider apiRequestProvider)
        {
             if (myApp == null) throw new ArgumentNullException(nameof(myApp));
             _myApp = myApp;

             if (apiRequestProvider== null) throw new ArgumentNullException(nameof(apiRequestProvider));
             _apiRequestProvider= apiRequestProvider;
        }
</code></pre>

<p>New implementation on method:</p>

<pre><code>[HttpPost]
        [ResponseType(typeof(string))]
        [Route(""api/myApp/UploadFile"")]
        [SwaggerUploadFile(""myFile"", ""Upload a .zip format file"", Required = true, Type = ""file"")]
        public async Task&lt;IHttpActionResult&gt; UploadFile()
        {
            if (!_apiRequestProvider.IsMimeMultiPartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            var provider = await _apiRequestProvider.ReadAsMultiPartAsync();
            var bytes = await provider.Contents.First().ReadAsByteArrayAsync();
            try
            {
               var retVal = _myApp.CheckAndSaveByteStreamAsync(bytes).Result;
               if(retVal)
                {
                    return
                        ResponseMessage(
                            new HttpResponseMessage(HttpStatusCode.OK)


             {
                            Content = new StringContent(JsonConvert.SerializeObject(
                                new WebApiResponse
                                {
                                    Message = ""File has been saved""
                                }), Encoding.UTF8, ""application/json"")
                        });
            }             
            return ResponseMessage(
                new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    Content = new StringContent(JsonConvert.SerializeObject(
                        new WebApiResponse
                        {
                            Message = ""The file could not be saved""
                        }), Encoding.UTF8, ""application/json"")
                });
        }
        catch (Exception e)
        {
            //log error
            return BadRequest(""Oops...something went wrong"");
        }
    }    
}
</code></pre>

<p>And my unit test that mocks the ApiController Request:</p>

<pre><code>    [Fact]
    [Trait(""Category"", ""MyAppController"")]
    public void UploadFileTestWorks()
    {
        //Arrange
        _apiRequestProvider = new Mock&lt;IApiRequestProvider&gt;();
        _myApp = new Mock&lt;IMyApp&gt;();
         MultipartMemoryStreamProvider fakeStream = new MultipartMemoryStreamProvider();
        fakeStream.Contents.Add(CreateFakeMultiPartFormData());
        _apiRequestProvider.Setup(x =&gt; x.IsMimeMultiPartContent()).Returns(true);
        _apiRequestProvider.Setup(x =&gt; x.ReadAsMultiPartAsync()).ReturnsAsync(()=&gt;fakeStream);
        _myApp.Setup(x =&gt; x.CheckAndSaveByteStreamAsync(It.IsAny&lt;byte[]&gt;())).ReturnsAsync(() =&gt; true);
        var expected = JsonConvert.SerializeObject(
            new WebApiResponse
            {
                Message = ""The file has been saved""
            });

        var _sut = new MyAppController(_myApp.Object, _apiRequestProvider.Object);

        //Act
        var retVal = _sut.UploadFile();
        var content = (ResponseMessageResult)retVal.Result;
        var contentResult = content.Response.Content.ReadAsStringAsync().Result;
        //Assert
        contentResult.Should().Be(expected); 
    }
</code></pre>

<p>Thanks to @Badulake for the idea</p>
",https://stackoverflow.com/questions/51284784/unit-testing-a-web-api-end-point-that-you-upload-files,"['c#', 'unit-testing', 'asp.net-web-api']",7328,TRUE,7,2
Unit testing when the returned value is a mock expectation,"<p>So I have a method that looks something like this:</p>

<p><code>public Foo method() {
    ...
    return service.get();
}</code></p>

<p><code>service</code> is an external dependency of the class.</p>

<p>My test code:</p>

<p><code>Foo mockServiceResponse = Mockito.mock(Foo.class);
when(service.get()).thenReturn(mockServiceResponse);</code></p>

<p>In my unit test I inject a mock created with Mockito and set a <code>when</code> for <code>service.get()</code> so my question is, how do I test the return value of <code>method</code>?
If I just check if <code>mockServiceResponse</code> is equal to <code>method()</code> the test doesnt check much since if someone changes <code>method</code> to:</p>

<p><code>public Foo method() {
    ...
    Foo f = service.get();
    f.setId(null);
    return f;
}</code></p>

<p>My test will still pass, which is obviously wrong, so how should I test this?</p>

<p><strong>CLARIFICATION:</strong> What I want to test is that <code>method</code> doesnt change the object returned from <code>service.get()</code> (meaning, I want the second stub to fail my test), problem is mock objects just ignore methods called on them (like <code>setId()</code>) without failing the test.</p>
",https://stackoverflow.com/questions/52672607/unit-testing-when-the-returned-value-is-a-mock-expectation,"['unit-testing', 'mockito']",1668,FALSE,1,2
Unit Testing ASP.Net Core Web API using xUnit and Moq,"<p>I am trying to test my web API using xUnit and Moq. I have instantiated all
 the required mock repository instances using constructor. I have also instantiated the controller in constructor. The controller instance is successfully calling the action method. But not executing function inside my repository.</p>

<pre><code>public class SubjectControllerTest
{
    public Mock&lt;IHostingEnvironment&gt; HostingEnvironment { get; set; }
    private readonly Mock&lt;ILogger&lt;SubjectController&gt;&gt; _logger;
    private readonly Mock&lt;ISubjectManager&lt;Subject&gt;&gt; _subjectManager;
    private readonly Mock&lt;IChapterManager&lt;Chapter&gt;&gt; _chapterManager;
    private readonly Mock&lt;ITopicManager&lt;Topic&gt;&gt; _topicManager;
    private readonly Mock&lt;ILearningPointManager&lt;LearningPoint&gt;&gt; _learningPointManager;
    private SubjectController controller;

    public SubjectControllerTest()
    {
        _subjectManager = new Mock&lt;ISubjectManager&lt;Subject&gt;&gt;();
        _chapterManager = new Mock&lt;IChapterManager&lt;Chapter&gt;&gt;();
        _topicManager = new Mock&lt;ITopicManager&lt;Topic&gt;&gt;();
        _learningPointManager = new Mock&lt;ILearningPointManager&lt;LearningPoint&gt;&gt;();
        _logger = new Mock&lt;ILogger&lt;SubjectController&gt;&gt;();
        HostingEnvironment = new Mock&lt;IHostingEnvironment&gt;();
        controller = new SubjectController(_subjectManager.Object, _chapterManager.Object,
                                             _topicManager.Object, _learningPointManager.Object, HostingEnvironment.Object, _logger.Object);
    }

    [Fact]
    public void Test_GetSubjectList()
    {   
        var subject1 = new Subject
        {
            Subject_ID = 1,
            Subject_Name = ""Physics"",
            Subject_Photo_Url = null,
            Validity_Start_Date = Convert.ToDateTime(""2/2/2018 12:00:00 AM""),
            Validity_End_Date = Convert.ToDateTime(""12/25/2018 12:00:00 AM"")
        };
        var subject2 = new Subject
        {
            Subject_ID = 2,
            Subject_Name = ""Business"",
            Subject_Photo_Url = null,
            Validity_Start_Date = Convert.ToDateTime(""3/10/2018 12:00:00 AM""),
            Validity_End_Date = Convert.ToDateTime(""3/20/2018 12:00:00 AM"")
        };

        var subject3 = new Subject
        {
            Subject_ID = 3,
            Subject_Name = ""Math"",
            Subject_Photo_Url = """",
            Validity_Start_Date = Convert.ToDateTime(""7/8/2018 8:33:23 AM""),
            Validity_End_Date = Convert.ToDateTime(""5/8/2019 8:33:23 AM"")
        };

        List&lt;Subject&gt; subjectList = new List&lt;Subject&gt;();
        subjectList.Add(subject1);
        subjectList.Add(subject2);
        subjectList.Add(subject3);

        int totalPages = 0;
        _subjectManager.Setup(x =&gt; x.GetList(It.IsAny&lt;int&gt;(), It.IsAny&lt;int&gt;(), It.IsAny&lt;string&gt;(), It.IsAny&lt;string&gt;(), ref totalPages))
            .Returns(subjectList);

        // Act
        var result = controller.GetSubjectList(1, 5, string.Empty, string.Empty);

        // Assert
        var okResult = Assert.IsType&lt;JsonResult&gt;(result);
        var viewModel = Assert.IsType&lt;Paging&gt;(okResult.Value);
        var list = viewModel.Data as List&lt;Subject&gt;;

        Assert.Equal(3, list.Count);
    }
}
</code></pre>

<p>I have called <code>GetSubjectList</code> action method here. The method is successfully called but the repository method <code>GetList()</code> is not executed. My API is as below.</p>

<p>What might be the problem?</p>

<pre><code>[HttpGet]
[Route(""api/subjects"")]
public IActionResult GetSubjectList(int page, int pageSize, string search, string sort)
{
    try
    {
        if (search == null)
            search = """";

        if (sort == null)
            sort = """";

        int totalPages = 0;

        List&lt;Subject&gt; list = _subjectManager.GetList(page, pageSize, sort, search, ref totalPages).ToList();

        Paging result = new Paging { Data = list, Total = totalPages };

        return Json(result);
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message, ex);
    }

}
</code></pre>
",https://stackoverflow.com/questions/51239221/unit-testing-asp-net-core-web-api-using-xunit-and-moq,"['unit-testing', 'asp.net-core', 'moq', 'asp.net-core-webapi', 'xunit']",2017,TRUE,1,1
Unit testing properties of a class using C# and reflection,"<p>I'm facing some difficulties with unit testing in C#.</p>

<p>Let's say I have</p>

<pre><code>class Dummy{
    TypeA Foo {get; set;}
    TypeB Bar {get; set;}
}
</code></pre>

<p>and the test method</p>

<pre><code>[TestMethod]
public void TestStuff()
{
    Type type = typeof(Dummy);
    PropertyInfo[] properties = type.GetProperties();

    foreach(PropertyInfo property in properties)
    {
        string result= MyStaticClass.ProcessProperty(property.Name);
        Assert.IsFalse(string.IsNullOrWhiteSpace(result));
    }
}
</code></pre>

<p>The test runs fine, but when it fails I have no clue about which property causes the problem.</p>

<p>In other test methods I've used the <code>[DataTestMethod]</code> and <code>[DataRow(stuff)]</code> in order to provide single inputs and know what caused the test to fail.</p>

<p>Is there a way to do something like this using reflection?</p>

<p>Am I thinking of a wrong unit test?</p>

<p>I'd like to use this approach to check consistency, is it wrong at all? </p>
",https://stackoverflow.com/questions/53390042/unit-testing-properties-of-a-class-using-c-and-reflection,"['c#', 'unit-testing']",1496,TRUE,1,1
Perl unit testing: check if a string is an array,"<p>I have this function that I want to test:</p>

<pre><code>use constant NEXT =&gt; 'next';
use constant BACK =&gt; 'back';

sub getStringIDs {
    return [
        NEXT,
        BACK
    ];
}
</code></pre>

<p>I've tried to write the following test, but it fails:</p>

<pre><code>subtest 'check if it contains BACK' =&gt; sub {
    use constant BACK =&gt; 'back';
    my $strings = $magicObject-&gt;getStringIDs();
    ok($strings =~ /BACK/);
}
</code></pre>

<p>What am I doing wrong?</p>
",https://stackoverflow.com/questions/50971430/perl-unit-testing-check-if-a-string-is-an-array,"['arrays', 'perl', 'unit-testing']",399,TRUE,1,3
Angular unit testing TypeError: Cannot read property &#39;subscribe&#39; of undefined,"<p>I'm creating starter kit template with auth and a example with CRUD (<a href=""https://github.com/fransyozef/basic-login-angular"" rel=""nofollow noreferrer"">https://github.com/fransyozef/basic-login-angular</a>)</p>

<p>Now I'm new with unit testing and i'm trying to get atleast get the testing running that the components are created. But I'm getting stuck with </p>

<pre><code>TypeError: Cannot read property 'subscribe' of undefined
</code></pre>

<p>I think the error comes from</p>

<pre><code>  resolveRoute() {
    this.route.params.subscribe(params =&gt; {
      if (params['id']) {
        this.id = +params['id'];
        this.getItem();
      } else {
        this.handleItemNotFound();
      }
     });
  }
</code></pre>

<p>in the file <a href=""https://github.com/fransyozef/basic-login-angular/blob/master/src/app/items/item-edit/item-edit.component.ts"" rel=""nofollow noreferrer"">https://github.com/fransyozef/basic-login-angular/blob/master/src/app/items/item-edit/item-edit.component.ts</a></p>

<p>Right now I have the testfile :
<a href=""https://github.com/fransyozef/basic-login-angular/blob/master/src/app/items/item-edit/item-edit.component.spec.ts"" rel=""nofollow noreferrer"">https://github.com/fransyozef/basic-login-angular/blob/master/src/app/items/item-edit/item-edit.component.spec.ts</a></p>

<p>Can somebody give me a hand with this?</p>
",https://stackoverflow.com/questions/53702866/angular-unit-testing-typeerror-cannot-read-property-subscribe-of-undefined,"['javascript', 'angular', 'unit-testing', 'frontend', 'karma-jasmine']",5997,TRUE,1,1
Write custom strings to logs during UI testing / unit testing,"<p>Is there any way to add text to the logs of a test?</p>

<p>Neither NSLog nor Swift.print seem to log any remaining text to any logs that I can see, when running UI and/or unit testing in Xcode 9. I am running on device.</p>

<p>Whatever I do, I do not see any NSLog/print stuff in Report navigator, clicking on the Test. I tried expanding everything...</p>
",https://stackoverflow.com/questions/50403718/write-custom-strings-to-logs-during-ui-testing-unit-testing,"['xcode', 'unit-testing', 'xcode-ui-testing']",3970,FALSE,1,1
Kotlin: Unit testing a function that takes a function as parameter,"<p>I have a function that retrieves a list of items from a repository. Instead of using a regular callback I pass in a function and invoke this with the result. But how can you unittest this kind of function. Is there some way to verify that the passed in function is being invoked or should I refactor and use a regular callback and test it using a mocked callback-interface?</p>

<p>My code:</p>

<pre><code>class WorklistInteractor @Inject
constructor(private val worklistRepository: WorklistRepository,
            private val preferenceManager: PreferenceManager,
            private val executor: Executor)
    : WorklistDialogContract.Interactor, Executor by executor {

    @Volatile private var job: Job? = null

    override fun getWorklist(callback: (Result&lt;List&lt;WorklistItem&gt;&gt;) -&gt; Unit) {
        job = onWorkerThread {
            val result = worklistRepository.getWorklist().awaitResult()
            onMainThread { callback(result) }
        }
    }

    override fun cancel() {
        job?.cancel()
    }
}
</code></pre>
",https://stackoverflow.com/questions/49168588/kotlin-unit-testing-a-function-that-takes-a-function-as-parameter,"['android', 'unit-testing', 'kotlin']",3448,TRUE,7,2
What is the unit testing paradigm in the Lagom framework?,"<p>I am new to the Lagom world. I have a scenario to work with <strong>unit tests</strong>. I work under the Lagom / Java framework and a Cassandra database.
I have two different services:</p>

<ul>
<li>Device Service</li>
<li>User Service</li>
</ul>

<p>My need is an intelligent access scenario. A user must register his device  to have access authorization.
This mechanism is managed by a WBS connect () in the device service. So this WBS deals with:</p>

<ul>
<li><p>If the device is not available: it stores it in the DB (for security reasons) and does not allow access</p></li>
<li><p>If the device is registered: it records the date of the access and authorizes the access</p></li>
</ul>

<p>My implementation is ready, it works fine. But my question is how to handle this in the unit test side.
Especially for the autorized access scenario because for a test start, I do not have a device registered in my DB / persistence.</p>

<ul>
<li>Do I need to invoke a WBS Add () that adds a device to my DB / persistence and then invoke the WBS connect () to simulate the access authorization?</li>
<li>Is there a solution to run the WBS connect () without relying on a DB?</li>
<li>If my WBS depends on another Service (User service), how to manage the unit test? Do I have to re-implement the User Service in the unit test of the device service?</li>
</ul>
",https://stackoverflow.com/questions/48260165/what-is-the-unit-testing-paradigm-in-the-lagom-framework,"['java', 'cassandra', 'lagom']",720,TRUE,1,1
How to mock DocumentClient CreateDocumentQuery with filters for DocumentDb unit testing?,"<p>I am writing unit tests for below piece of code which is using Document client CreateDocumentQuery method with where(filter) conditions.</p>

<pre><code> var documentQuery = ReadOnlyDocumentClient.CreateDocumentQuery&lt;MyView&gt;(UriFactory.CreateDocumentCollectionUri(Constants.COSMOS_DB_NAME, Constants.MY_VIEW_COL_NAME))
                                                       .Where(w =&gt; w.Name== query.Name)
                                                       .Where(w =&gt; w.DOB&gt; query.StartDate &amp;&amp; w.DOB &lt; query.EndDate)
                                                       .AsDocumentQuery();
</code></pre>

<p>query is a command parameter which is an input.</p>

<p>I am using MOQ to mock  and I am using below code line to mock</p>

<pre><code> mockDocumentClient.Setup(s =&gt; s.CreateDocumentQuery&lt;MyView&gt;(It.IsAny&lt;Uri&gt;(), It.IsAny&lt;FeedOptions&gt;())).Returns(mockDocumentQuery.Object);
</code></pre>

<p>Now, above piece of code only mocks CreateDocumentQuery and when Where conditions are executed I am not getting mock support.</p>

<p>Please suggest how can I mock CreateDocumentQuery with where conditions?</p>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/50897149/how-to-mock-documentclient-createdocumentquery-with-filters-for-documentdb-unit,"['c#', 'unit-testing', 'documentclient']",1684,TRUE,7,2
"Unit testing VueJS with axios, TypeScript template, and async functions","<p>I'm trying to unit test a component that makes an HTTP call in its <code>mounted()</code> hook. I'm using the template created by CLI using Typescript and Jest. My component looks something like this:</p>

<pre><code>export default class UsrUsers extends Vue {
  private error: string = '';
  private users: User[] | null = null;

  private async mounted() {
    const url = process.env.VUE_APP_SERVICE_URL;

    try {
      const res = await axios.get&lt;User[]&gt;(`${url}/api/users`);
      this.users = res.data;

    } catch (ex) {
      this.error = (ex as AxiosError).message;
    }
  }
}
</code></pre>

<p>I found <a href=""https://github.com/ctimmerm/axios-mock-adapter"" rel=""nofollow noreferrer"">axios-mock-adapter</a> package, and I have a test setup like this:</p>

<pre><code>describe('Users Container', () =&gt; {
  const axiosMock = new MockAdapter(axios);
  const baseUrl = process.env.VUE_APP_SERVICE_URL;

  it('should display no user when user list is empty', async () =&gt; {
    axiosMock.onGet(`${baseUrl}/api/users`).reply(200, []);

    const wrapper = await shallowMount(UsrUsers);
    expect(wrapper.text()).toMatch('no user');
  });
});
</code></pre>

<p>But, it's not working (I also tried with <code>jest.mock('axios')</code>), and I get an empty string as <code>wrapper.text()</code>.</p>

<p>I also tried using <code>$nextTick</code> like this:</p>

<pre><code>it('should display no user', done =&gt; {
  // Set up axiosMock
  const wrapper = shallowMount(UsrUsers);

  wrapper.vm.$nextTick(() =&gt; {
    expect(wrapper.text()).toMatch('no user');
    done();
  });
});
</code></pre>

<p>But this is timing out with the message <code>Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout</code></p>

<p>So, how can I properly test this component?? I tried to find something on the internet, but didn't find anything.</p>
",https://stackoverflow.com/questions/53308414/unit-testing-vuejs-with-axios-typescript-template-and-async-functions,"['typescript', 'vuejs2', 'axios', 'jestjs', 'vue-test-utils']",625,FALSE,1,1
Unit Testing the root component of the React Web Application,"<p>How to test the root component which is rendered through react-dom render function?</p>

<p>I am working on this react component. </p>

<pre><code> export default class EWAWeb extends React.Component {
    render() {
        return (
            &lt;Provider store={store} &gt;
                &lt;Router&gt;
                    &lt;Switch&gt;
                        &lt;Route exact path=""/"" component={SplashScreen} /&gt;
                        &lt;Route path=""/start"" component={SplashScreen} /&gt;
                        &lt;Route path=""/dashboard"" component={Dashboard} /&gt;
                    &lt;/Switch&gt;
                &lt;/Router&gt;
            &lt;/Provider&gt;
        );
    }
}

render(&lt;EWAWeb /&gt;, document.getElementById('app'));
</code></pre>

<p>Inside JEST</p>

<pre><code>describe('To test the Login Component functionality.', () =&gt; {
    configure({ adapter: new Adapter() });
    let compEWAWebParent = null;

    it(`should mount and check.`, () =&gt; {
            compEWAWebParent = mount(&lt;EWAWeb /&gt;);
            const isReduxProvider = compEWAWebParent.find(Provider);
            expect(isReduxProvider).toHaveLength(1);
        });
});
</code></pre>

<p>I am writing this simple test to check.
If I remove the below line, test is working well, </p>

<pre><code>render(&lt;EWAWeb /&gt;, document.getElementById('app'));
</code></pre>

<p>otherwise throwing error:</p>

<blockquote>
  <p>Invariant Violation: Target container is not a DOM element.</p>
</blockquote>

<p>I don't want to segregate the files and also don't want to use document .body.</p>

<p>Thank you.</p>

<p>The issue is resolved and I have achieved 100% code coverage.</p>

<p>Thank you.</p>

<p><strong>Solution</strong></p>

<pre><code>export default class EWAWeb extends React.Component {
    render() {
        return (
            &lt;Provider store={store} &gt;
                &lt;Router&gt;
                    &lt;Switch&gt;
                        &lt;Route exact path=""/"" component={SplashScreen} /&gt;
                        &lt;Route path=""/start"" component={SplashScreen} /&gt;
                        &lt;Route path=""/dashboard"" component={Dashboard} /&gt;
                    &lt;/Switch&gt;
                &lt;/Router&gt;
            &lt;/Provider&gt;
        );
    }
}

const containerDiv = document.getElementById('app');
render(&lt;EWAWeb /&gt;, containerDiv || document.createElement('DIV'));
</code></pre>
",https://stackoverflow.com/questions/48263432/unit-testing-the-root-component-of-the-react-web-application,"['reactjs', 'jestjs', 'react-dom']",1804,TRUE,1,1
"Rest controller unit testing with spring boot, kotlin and junit","<p>I am currently developping a website with spring boot, kotlin where I am trynig to read Google Trends Rss feeds in xml format and parse them to Json.
I want to add unit tests to test my controller but I do not know what to test exactly.</p>

<p>This is my data class: </p>

<pre><code>data class Rss (

    val title: String,
    val source: String,
    val image: String,
    val description: String,
    val url: String
)
</code></pre>

<p>This is my rest Controller </p>

<pre><code>@RestController
@RequestMapping(value=""/rss"")
class RssRestService {

   @GetMapping(value = ""/list/item"")
   @CrossOrigin(""http://localhost:3000"")
   fun rss(): List&lt;Rss&gt;? {

         val url = ""https://trends.google.fr/trends/hottrends/atom/feed?pn=p1""
         val reader = XmlReader(URL(url))
         val feed: SyndFeed = SyndFeedInput().build(reader)
         return feed.entries.subList(1,6)
                 .map { entry -&gt; Rss(
                 title = entry.title,
                 image = entry.foreignMarkup[1].content[0].value.substring(2),
                 source = entry.foreignMarkup[2].content[0].value,
                 description = entry.foreignMarkup[3].content[1].value.toString(),
                 url = entry.foreignMarkup[3].content[1].value
    ) }

}
</code></pre>

<p>And what I did so far for testing is </p>

<pre><code>@RunWith(SpringRunner::class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class DemoApplicationTests {


    @Autowired
    lateinit var testRestTemplate: TestRestTemplate

    @Test
    fun contextLoads() {

    }

    @Test
    fun rssTest() {
        val result = testRestTemplate.getForEntity(""/rss/list/item"", String::class.java)
        Assert.assertNotNull(result)
        Assert.assertEquals(HttpStatus.OK, result.statusCode)

}
</code></pre>

<p>My question is: what should I test? and how to test if the output is write or not? </p>
",https://stackoverflow.com/questions/50210971/rest-controller-unit-testing-with-spring-boot-kotlin-and-junit,"['unit-testing', 'spring-boot', 'junit', 'kotlin', 'spring-restcontroller']",1888,TRUE,1,2
How can I mock a component&#39;s state for unit testing?,"<p>I am using enzyme, jest, sinon for unit testing. I would like to mock a components state and pass in a custom state before the component gets render. How can I achieve this?</p>

<p>My component starts off with some initial state:</p>

<pre><code>constructor(props) {
   super(props);
   this.state = {
     sample: ""hello""
   }
}
</code></pre>

<p>I want to overwrite the value of sample before render happens by mocking a fake state and before calling shallow().</p>
",https://stackoverflow.com/questions/53230352/how-can-i-mock-a-components-state-for-unit-testing,"['reactjs', 'unit-testing', 'jestjs', 'enzyme']",1427,FALSE,1,1
unit testing default method calling abstract method in an interface,"<p>I have an interface which has two methods - convertList and convert.</p>

<p><code>convertList</code> has a default implementation that calls <code>convert</code> for each input in its inputList.</p>

<p>I want to write a unit test for convertList that -</p>

<ul>
<li>test if it calls convert method as many times as the size of inputlist</li>
<li>test if it passes on convertedOutput object for each input to the list of convertedOutputs</li>
</ul>

<p>Following is my interface -</p>

<pre><code>public interface MyConverter {
    ConverterOutput convert(final MyDTO input, final String myParam) throws MyDTOConversionException;

    default Collection&lt;ConverterOutput&gt; convertList(
        final Collection&lt;? extends MyDTO&gt; inputList,
        final String myParam)
        throws MyDTOConversionException {
        try {
            List&lt;ConverterOutput&gt; converterOutputs = new ArrayList&lt;&gt;();

            for (MyDTO input : inputList) {
                converterOutputs.add(this.convert(input, myParam));
            }
            return converterOutputs;
        } catch (NullPointerException npe) {
            throw new MyDTOConversionException(""Unable to convert dto to converter output"", npe);
        }
    }
}
</code></pre>

<p>I am unable to achieve 1 while mocking the interface and stubbing its convert method. Following is my test class.</p>

<pre><code>@SpringBootTest(classes = MyConverter.class)
public class MyConverterTest extends BaseTest {

    class MyDTOImpl extends MyDTO {
        @Override
        public void someAbstractMethod(String param) {
        }
    }

    @Mock
    private ConverterOutput converterOutput;

    @Mock
    private MyConverter myConverter;

    @Mock
    private MyDTOImpl myDTO;

    @Test
    public void testConvertListOfSizeOne() {

        String myParam = ""1234"";

        Collection&lt;MyDTO&gt; myDTOS = new ArrayList&lt;&gt;();
        myDTOS.add(myDTO);

        try {
            when(myConverter.convert(myDTO, myParam)).thenReturn(converterOutput);
            Collection&lt;ConverterOutput&gt; actualConverterOutputs = myConverter.convertList(myDTOS, myParam);

            // check if times convert method was called is as expected
            verify(myConverter, times(1)).convert(myDTO, myParam);

            // check if number of items in output object are as expected
            Assert.assertEquals(actualConverterOutputs.size(), 1);

            // check if output object is as expected
            for (ConverterOutput c: actualConverterOutputs) {
                Assert.assertSame(c, converterOutput);
            }
        } catch (MyDTOConversionException exception) {
            throw new AssertionError(""MyDTOConversionException should not have occurred"");
        }
    }
}
</code></pre>

<p>Following is the error I got</p>

<blockquote>
  <p>Wanted but not invoked: myConverter.convert(myDTO, ""1234"");
  -> at com.abc.project.converters.MyConverterTest.testConvertListOfSizeOne(MyConverterTest.java:49)</p>
  
  <p>However, there were other interactions with this mock:
  myConverter.convertList(
      [myDTO],
      ""1234"" );</p>
</blockquote>
",https://stackoverflow.com/questions/49658257/unit-testing-default-method-calling-abstract-method-in-an-interface,"['java', 'spring-boot', 'junit', 'interface', 'mockito']",1429,TRUE,1,1
How can I remove LeaseRenewer error in spark unit testing?,"<p>I'm running spark unit tests with a shared instance of local spark from sbt console.</p>

<p>Scala version: 2.11.11
Spark version: 2.0.2_cdh5.8.0_1
Sbt version:  0.13.16</p>

<p>I have multiple modules. The tests are not failing but it retries until it fails with OutOfMemory exception.
When I ran sbt test for a single module everything works fine. But when I'm running sbt test for all then I get the fallowing exception:</p>

<pre><code>LeaseRenewer: Failed to renew lease for [DFSClient_NONMAPREDUCE_-465806268_61] for 76 seconds.  Will retry shortly ...
java.net.ConnectException: Call From C02TM0QGG8WL/10.120.214.244 to localhost:52634 failed on connection exception: java.net.ConnectException: Connection refused; For more details see:  http://wiki.apache.org/hadoop/ConnectionRefused
    at sun.reflect.GeneratedConstructorAccessor197.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.apache.hadoop.net.NetUtils.wrapWithMessage(NetUtils.java:792)
    at org.apache.hadoop.net.NetUtils.wrapException(NetUtils.java:732)
    at org.apache.hadoop.ipc.Client.call(Client.java:1479)
    at org.apache.hadoop.ipc.Client.call(Client.java:1412)
    at org.apache.hadoop.ipc.ProtobufRpcEngine$Invoker.invoke(ProtobufRpcEngine.java:229)
    at com.sun.proxy.$Proxy43.renewLease(Unknown Source)
    at org.apache.hadoop.hdfs.protocolPB.ClientNamenodeProtocolTranslatorPB.renewLease(ClientNamenodeProtocolTranslatorPB.java:590)
    at sun.reflect.GeneratedMethodAccessor124.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.hadoop.io.retry.RetryInvocationHandler.invokeMethod(RetryInvocationHandler.java:191)
    at org.apache.hadoop.io.retry.RetryInvocationHandler.invoke(RetryInvocationHandler.java:102)
    at com.sun.proxy.$Proxy44.renewLease(Unknown Source)
    at org.apache.hadoop.hdfs.DFSClient.renewLease(DFSClient.java:892)
    at org.apache.hadoop.hdfs.LeaseRenewer.renew(LeaseRenewer.java:423)
    at org.apache.hadoop.hdfs.LeaseRenewer.run(LeaseRenewer.java:448)
    at org.apache.hadoop.hdfs.LeaseRenewer.access$700(LeaseRenewer.java:71)
    at org.apache.hadoop.hdfs.LeaseRenewer$1.run(LeaseRenewer.java:304)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.ConnectException: Connection refused
    at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
    at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717)
    at org.apache.hadoop.net.SocketIOWithTimeout.connect(SocketIOWithTimeout.java:206)
    at org.apache.hadoop.net.NetUtils.connect(NetUtils.java:531)
    at org.apache.hadoop.net.NetUtils.connect(NetUtils.java:495)
    at org.apache.hadoop.ipc.Client$Connection.setupConnection(Client.java:614)
    at org.apache.hadoop.ipc.Client$Connection.setupIOstreams(Client.java:712)
    at org.apache.hadoop.ipc.Client$Connection.access$2900(Client.java:375)
    at org.apache.hadoop.ipc.Client.getConnection(Client.java:1528)
    at org.apache.hadoop.ipc.Client.call(Client.java:1451)
    ... 16 more
</code></pre>

<p>How can I resolve this issue? I tried to increase memory in tests also but with no luck.
Thanks.</p>
",https://stackoverflow.com/questions/48943462/how-can-i-remove-leaserenewer-error-in-spark-unit-testing,"['scala', 'unit-testing', 'apache-spark', 'sbt']",282,FALSE,1,0
Do unit testing files increase app size for released version,"<p>Needed to know whether including unit testing into the app will affect the size of released version once it's ready for production.</p>

<p>If YES, Is there a way to not include unit testing files during release phase of the app like some sort of build script ? </p>
",https://stackoverflow.com/questions/48659704/do-unit-testing-files-increase-app-size-for-released-version,"['ios', 'swift', 'xcode', 'unit-testing', 'app-store']",234,TRUE,1,1
Unit Testing Google Cloud Datastore using Cloud Datastore Client library,"<p>I'm developing a Java application in the App Engine Flexible environment that requires access to Datastore. I've had no trouble setting this up, however when it comes to unit testing I am unable to test any of the Datastore code (without an external connection to Google Cloud, which would be an integration test).</p>

<p>I am using the <a href=""https://cloud.google.com/datastore/docs/reference/libraries#client-libraries-install-java"" rel=""nofollow noreferrer"">Cloud Datastore client library</a> to connect to Datastore, which doesn't appear to work with the <code>LocalServiceTestHelper</code> as indicated <a href=""https://cloud.google.com/appengine/docs/standard/java/tools/localunittesting#datastore-memcache"" rel=""nofollow noreferrer"">in this guide</a>. </p>

<p>The client library I'm using is in the <code>com.google.cloud</code> package, whereas the unit testing tools are in <code>com.google.appengine</code>, so they are incompatible. Is there a way to use the <code>LocalServiceTestHelper</code> with the <code>com.google.cloud</code> libraries (or an alternate in-memory datastore for testing)?</p>
",https://stackoverflow.com/questions/51188792/unit-testing-google-cloud-datastore-using-cloud-datastore-client-library,"['java', 'google-app-engine', 'google-cloud-datastore', 'app-engine-flexible']",1037,TRUE,1,1
Error &#39;Cannot read property &#39;triggerEventHandler&#39; of null&#39; in Karma unit testing,"<p>I am trying to test if a closeModal function in a Modal component is working when clicking a ""close button"" on the modal, however this test shows my button element as null. I am getting the error ""Cannot read property 'triggerEventHandler' of null."" How can I resolve this?</p>

<p>modal.component.ts</p>

<pre><code>import { AppComponent } from ""./../app.component"";
import { async, ComponentFixture, TestBed } from ""@angular/core/testing"";
import { ModalComponent } from ""./modal.component"";
import { By } from '@angular/platform-browser';

describe(""ModalComponent"", () =&gt; {
  let component: ModalComponent;
  let fixture: ComponentFixture&lt;ModalComponent&gt;;

  beforeEach(
    async(() =&gt; {
      TestBed.configureTestingModule({
        declarations: [ModalComponent, AppComponent]
      }).compileComponents();
    })
  );

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(ModalComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it(""should create"", () =&gt; {
    expect(component).toBeTruthy();
  });

  it(""should test closeModal method on close button"", () =&gt; {
    spyOn(component, ""closeModal"")
    let el = fixture.debugElement.query(By.css('#close'))
    el.triggerEventHandler('click', null)

    fixture.detectChanges()

    fixture.whenStable().then(() =&gt; {
      expect(component.closeModal).toHaveBeenCalled();
    });
  });
});
</code></pre>

<p>modal.component.html</p>

<pre><code>&lt;div class=""ds-c-dialog-wrap""[ngClass]=""hideModal ? 'hide' : 'show'""&gt;
  &lt;div&gt;
    &lt;header role=""banner""&gt;
      &lt;h1 id=""dialog-title""&gt;{{modalTitle}}&lt;/h1&gt;
      &lt;button
      id=""button""
      (click)=""closeModal()""
      *ngIf=""enableClose""&gt;Close&lt;/button&gt;
    &lt;/header&gt;
    &lt;main&gt;
      &lt;p class=""ds-text""&gt;
        {{modalBody}}
    &lt;/main&gt;
    &lt;aside role=""complementary""&gt;
      &lt;button&gt;Dialog action&lt;/button&gt;
      &lt;button *ngIf=""enableCancel"" (click)=""closeModal()""&gt;Cancel&lt;/button&gt;
    &lt;/aside&gt;
  &lt;/div&gt;
&lt;/div&gt;
</code></pre>
",https://stackoverflow.com/questions/48426944/error-cannot-read-property-triggereventhandler-of-null-in-karma-unit-testing,"['javascript', 'angular', 'unit-testing', 'karma-jasmine']",13879,TRUE,7,1
How to perform Unit testing and Code coverage in IAR,"<p>I am using IAR embedded workbench 8.0. I would like to use C-spy debugger to perform unit testing and code coverage.Is there any way so that i can generate xml files and use it with jenkins to display the coverage report?</p>

<p>Thanks,
Apoorva</p>
",https://stackoverflow.com/questions/52200639/how-to-perform-unit-testing-and-code-coverage-in-iar,"['unit-testing', 'jenkins', 'code-coverage', 'iar']",2770,FALSE,1,2
Mocking timers when unit testing a communication library with timeouts,"<p>I have to maintain a rather big library implementing a communication protocol with different layers. Fortunately, there are thousands of unit tests for many different situations.</p>
<p>I have problems with those unit tests probing for timeouts within the library. The timeouts are in the range of a few seconds which is unacceptably long for unit-testing.</p>
<p>What we already did is to implement a single central clock service which can be configured to run faster by a certain factor. By this, the tests complete much faster. But we cannot choose this factor too large, as then some tests begin to fail randomly because the performance of the test machine varies. Also, it is a nightmare to debug.</p>
<p>I feel that it is wrong to use any kind of independently running clock for testing timeouts. It would be better if this is completely under the control of the unit test.</p>
<p>Is there a way I can implement this without having to change too much in the library code, that can be added to the unit tests?</p>
<p>The library code with timeout is more or less structured as:</p>
<pre><code>var startTime = TimeService.CurrentTime;
while (TimeService.CurrentTime &lt; startTime + timeout)
{
    // do something
    Thread.Sleep(50); // or so
}
</code></pre>
<p>and it would be difficult to change this structure.</p>
",https://stackoverflow.com/questions/53246706/mocking-timers-when-unit-testing-a-communication-library-with-timeouts,"['.net', 'unit-testing', 'time', 'timeout']",65,FALSE,1,0
Unit Testing with a singleton inside a validation method in Laravel,"<p>I have registered a singleton in a Service Provider (which uses a Guzzle Client in it's constructor):</p>

<pre><code>public function register()
{
    $this-&gt;app-&gt;singleton(Channel::class, function ($app) {
        return new ChannelClient(new Client([
            'http_errors'=&gt; false,
            'timeout' =&gt; 10,
            'connect_timeout' =&gt; 10
        ]));
    });
}
</code></pre>

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

<pre><code> public static function validateChannel($attribute, $value, $parameters, \Illuminate\Validation\Validator $validator)
    {
        $dataloader = app()-&gt;make(\App\Client\Channel::class);
        if($dataloader-&gt;search($value)){
            return true;
        }
    }
</code></pre>

<p>In the PHPUnit Test, how can I replace the <code>app()-&gt;make(\App\Client\Channel::class);</code> with a mocked <code>Client</code> class but still test the validation function within the test?</p>
",https://stackoverflow.com/questions/50312395/unit-testing-with-a-singleton-inside-a-validation-method-in-laravel,"['laravel', 'validation', 'phpunit']",3325,TRUE,7,1
unit testing asynchronous code and code without externally visible effects,"<p>Actually, I have two questions, although a bit related:</p>

<ul>
<li><p>I know that unit tests should test the public API. However, if I have a close method that closes sockets and shuts down executors, however, neither sockets nor executors are exposed to users of this API, should I test if this is done, or only that the method executed without error? Where is the borderline between public api/behavior and impl details?</p></li>
<li><p>if I test a method that performs some checks, then queues a task on executor service, then returns a future to monitor operation progress, should I test both this method and the task, even if the task itself is a private method or otherwise not exposed code? Or should I instead test only the public method, but arrange for the task to be executed in the same thread by mocking an executor? In the latter case, the fact that task is submitted to an executor using the execute() method would be an implementation detail, but tests would wait for tasks to complete to be able to check if the method along with it's async part works properly.</p></li>
</ul>
",https://stackoverflow.com/questions/53034194/unit-testing-asynchronous-code-and-code-without-externally-visible-effects,"['java', 'multithreading', 'asynchronous', 'testing']",59,TRUE,1,1
Mocking a global object when unit testing function with jasmine,"<p>I need to write tests for legacy JavaScript script which runs from <code>node.js</code>. It has a global object which is initialised in one function and then accessed from another. I mean <code>script.js</code> looks like:</p>

<pre><code>var object;

function first() {
    object = Initialise.object();
    ...
}

function second() {
    object.doSomething();
    ...
}
</code></pre>

<p>I need to write a unit test for the <code>second()</code> function. We are using a jasmine test framework and I am struggling to create a mock (stub) for the <code>object</code>. It is because I don't know how can I access it from <code>script-spec.js</code>. I have tried</p>

<pre><code>var script = require(""../src/script.js"");
var testObject = script.object;
</code></pre>

<p>but <code>testObject</code> is <code>undefined</code>. </p>

<p>My knowledge of <code>JavaScript</code> is limited which doesn't help me as well (I have <code>Java</code> background).</p>

<p>How can I test <code>second()</code> function? I understand that I might need to refactor/redesign <code>script.js</code> which I am OK with.</p>
",https://stackoverflow.com/questions/49682026/mocking-a-global-object-when-unit-testing-function-with-jasmine,"['javascript', 'node.js', 'jasmine']",1195,TRUE,1,2
Error with Spring Kafka Unit Testing: Failed to determine TestUtils.createBrokerConfig(),"<p>I'm using spring-kafka and spring-kafka-test 2.1.5.RELEASE, and I'm running the unit test example on the spring-kafka documentation, specifically this one: <a href=""https://docs.spring.io/spring-kafka/docs/2.1.5.RELEASE/reference/html/_reference.html#_example"" rel=""nofollow noreferrer"">Code</a></p>

<p>On this line:</p>

<pre><code>@ClassRule
public static KafkaEmbedded embeddedKafka = new KafkaEmbedded(1, true, TEMPLATE_TOPIC);
</code></pre>

<p>I'm getting this error:</p>

<pre><code>java.lang.ExceptionInInitializerError ... Caused by: java.lang.RuntimeException: Failed to determine TestUtils.createBrokerConfig() method
</code></pre>

<p>I'm at a loss why the example test on the official documentation isn't working, and I can't seem to find any reference on this error online. I'll be grateful if anyone has any idea what could be wrong.</p>

<p>This is my pom.xml, in case there is an issue I'm missing with my dependencies: <a href=""https://pastebin.com/nT8j5LQ5"" rel=""nofollow noreferrer"">https://pastebin.com/nT8j5LQ5</a></p>
",https://stackoverflow.com/questions/50179109/error-with-spring-kafka-unit-testing-failed-to-determine-testutils-createbroker,"['spring', 'unit-testing', 'apache-kafka', 'spring-kafka']",1315,TRUE,1,1
Unit Testing EF Core with In Memory and Dependency Injection?,"<p>Have been trying to leverage EF core in-memory provider with .Net Dependency injection. Modified <a href=""https://learn.microsoft.com/en-us/ef/core/miscellaneous/testing/in-memory"" rel=""nofollow noreferrer"">original documentation</a> example, to include .Net core in built, dependency injection.</p>

<blockquote>
  <p>However having disposed the context, and instantiating again, not able to retrieve the object,
  back. Could you point out me in right direction.</p>
</blockquote>

<pre><code>[TestMethod]
public void Find_searches_url()
{
    var options = new DbContextOptionsBuilder&lt;BloggingContext&gt;()
        .UseInMemoryDatabase(databaseName: ""LkBlogs"")
        .Options;
    ServiceCollection services = new ServiceCollection();
    services.AddDbContext&lt;BloggingContext&gt;((y) =&gt; y.UseInMemoryDatabase(databaseName: ""LkBlogs""), ServiceLifetime.Transient);

    ServiceProvider serviceProvider = services.BuildServiceProvider();

    using (var context = serviceProvider.GetService&lt;BloggingContext&gt;())
    {
        context.Blogs.Add(new Blog { Url = ""http://sample.com/cats"" });
        context.Blogs.Add(new Blog { Url = ""http://sample.com/catfish"" });
        context.Blogs.Add(new Blog { Url = ""http://sample.com/dogs"" });
        context.SaveChanges();
        var result = context.Blogs.Find(1);
        Assert.IsNotNull(result, ""From same context (which was used for writing, could not retrieve)"");
    }

    using (var context = serviceProvider.GetService&lt;BloggingContext&gt;())
    {
        var result = context.Blogs.Find(1);
        Assert.IsNotNull(result, ""From new context, instantiated with DI could not retrieve"");
    }

    using (var context = new BloggingContext(options))
    {
        var result = context.Blogs.FirstOrDefault();
        //Error: Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException: 'Assert.IsNotNull failed. '
        Assert.IsNotNull(result, ""From new context, instantiated without DI could not retrieve"");
    }
}
</code></pre>

<p><strong>EDIT: Documentation example:</strong></p>

<pre><code>[TestMethod]
        public void Find_searches_url()
        {
            var options = new DbContextOptionsBuilder&lt;BloggingContext&gt;()
                .UseInMemoryDatabase(databaseName: ""Find_searches_url"")
                .Options;

            // Insert seed data into the database using one instance of the context
            using (var context = new BloggingContext(options))
            {
                context.Blogs.Add(new Blog { Url = ""http://sample.com/cats"" });
                context.Blogs.Add(new Blog { Url = ""http://sample.com/catfish"" });
                context.Blogs.Add(new Blog { Url = ""http://sample.com/dogs"" });
                context.SaveChanges();
            }

            // Use a clean instance of the context to run the test
            using (var context = new BloggingContext(options))
            {
                var service = new BlogService(context);
                var result = service.Find(""cat"");
                Assert.AreEqual(2, result.Count());
            }
        }
</code></pre>

<p><strong>EDIT: 2</strong>
Have tried all service life times, SingleTon, Transient &amp; Scoped. Exception remains same.</p>

<p><strong>EDIT: 3</strong>
As per @Chris advice, removed usings for Context. Didn't help:</p>

<pre><code>[TestMethod]
    public void Find_searches_url()
    {
        var options = new DbContextOptionsBuilder&lt;BloggingContext&gt;()
            .UseInMemoryDatabase(databaseName: ""LkBlogs"")
            .Options;
        ServiceCollection services = new ServiceCollection();
        services.AddDbContext&lt;BloggingContext&gt;((y) =&gt; y.UseInMemoryDatabase(databaseName: ""LkBlogs""),
            ServiceLifetime.Transient);

    ServiceProvider serviceProvider = services.BuildServiceProvider();

    var context = serviceProvider.GetService&lt;BloggingContext&gt;();
    context.Blogs.Add(new Blog {Url = ""http://sample.com/cats""});
    context.Blogs.Add(new Blog {Url = ""http://sample.com/catfish""});
    context.Blogs.Add(new Blog {Url = ""http://sample.com/dogs""});
    context.SaveChanges();
    var result = context.Blogs.Find(1);
    Assert.IsNotNull(result, ""From same context (which was used for writing, could not retrieve)"");

    var context2 = serviceProvider.GetService&lt;BloggingContext&gt;();
    var result2 = context2.Blogs.Find(1);
    Assert.IsNotNull(result2, ""From new context, instantiated with DI could not retrieve"");

    var context3 = new BloggingContext(options);
    var result3 = context3.Blogs.FirstOrDefault();
    //Error: Microsoft.VisualStudio.TestTools.UnitTesting.AssertFailedException: 'Assert.IsNotNull failed. '
    Assert.IsNotNull(result3, ""From new context, instantiated without DI could not retrieve"");
}
</code></pre>
",https://stackoverflow.com/questions/52718550/unit-testing-ef-core-with-in-memory-and-dependency-injection,"['c#', 'unit-testing', '.net-core', 'entity-framework-core', '.net-core-2.1']",1790,FALSE,1,0
Unit testing of shell commands called in a python script,"<p>I am writing unit tests (using Python 3.7, Pytest 3.6 and tox 3.0) for a function that compiles a series of shell commands as a list of strings, and then executes them using the <code>subprocess</code> module. The shell commands do the following:</p>

<ul>
<li>creates a filename from the function arguments.</li>
<li><code>cd</code> into a given directory.</li>
<li>checks for a file with a certain name and removes it if it exist.</li>
<li>creates a new file with the same name.</li>
<li>executes a program and pipes the output into the new file.</li>
</ul>

<p>My test right now is mocking the subprocess module, and then asserting that it was called with a list of strings that contains all the expected commands given some test arguments. </p>

<p><strong>Is there a way to test that the commands do what they are supposed to?</strong> Right now my test is only checking if the list of commands I feed to the subprocess module is the same as the one I have asserted it to be. This does not tell me whether the commands are <em>the right ones for what I am trying to achieve</em>. Rather it only serves as a test on whether I can write down the same string in two different source files.</p>

<p><strong>Can I simulate the side effects that I expect the shell commands to have?</strong></p>
",https://stackoverflow.com/questions/52072544/unit-testing-of-shell-commands-called-in-a-python-script,"['python-3.x', 'shell', 'unit-testing', 'zsh']",2357,TRUE,1,2
Angular 5 Unit Testing cannot read property &#39;http&#39; of undefined,"<p>I am attempting to write a helper function in an Angular test leveraging <code>HttpTestingController</code>.  The reason being is because I will eventually have a series of endpoints within my Angular service, <code>RequestService</code>, that I want to test within this testing file.  I do not want to repeatedly inject my <code>RequestService</code> and <code>HttpTestingController</code> instances into each test function that tests the service.  That is redundant.  Rather, I would prefer to have a single test function that takes the injected <code>RequestService</code> and <code>HttpTestingController</code> instances and repeatedly passes them into the helper function I have created, <code>requestHelper</code>.  This way when I want to test additional endpoints, all I need to do is make a call to the helper function and provide the parameters that are needed.     </p>

<p>The problem I am bumping into is that when the helper function runs, the service's instance for some reason does not appear to exist,  Even though the test is able to access the service's functions.  When it reaches my service method's call to the <code>http.get</code> within the <code>callEndpoint</code> function, it gives me the below error:</p>

<p><code>Failed: Cannot read property 'http' of undefined</code></p>

<p>This does not make sense to me because the <code>this</code> keyword is referring to the instance of the Angular service, and the test case is able to reach the service's function, so how could <code>this</code> possibly be undefined?</p>

<p>Here is my test spec:</p>

<pre><code>import { TestBed, async, inject } from '@angular/core/testing';
import { HttpClientModule, HttpRequest, HttpParams } from '@angular/common/http';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import {  RequestService } from './request.service';

describe(`RequestService`, () =&gt; {

      beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
          imports: [
            HttpClientModule,
            HttpClientTestingModule
          ],
          providers: [
            RequestService
          ]
        });
      }));

      afterEach(async(inject([HttpTestingController], (backend: HttpTestingController) =&gt; {
        backend.verify();
      })));

      it(`TESTING INJECTION`, async(inject([RequestService, HttpTestingController],
        (service: RequestService, backend: HttpTestingController) =&gt; {

         requestHelper(service.callEndpoint,'https://endpointurl.com',backend);
      })));

      function requestHelper(serviceCall: Function, url: string,  backendInstance: any) {
        serviceCall(...serviceParams).subscribe();
        backendInstance.expectOne((req: HttpRequest&lt;any&gt;) =&gt; {
          return req.url === url
              &amp;&amp; req.method === 'GET';
        }, 'GET');
      }
});
</code></pre>

<p>And the respective service that the spec is testing</p>

<pre><code>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';

    @Injectable()
    export class RequestService {

      private requestOptions = {
        headers: new HttpHeaders({'Locale': 'en_US'})
      };

      constructor(private http: HttpClient) { }

      callEndpoint(state: string, countryCode: string): Observable&lt;Object&gt; {
        return this.http.get(`https://endpointurl.com`,this.requestOptions);
      }
}
</code></pre>

<p>Thank you for your help!</p>
",https://stackoverflow.com/questions/49058864/angular-5-unit-testing-cannot-read-property-http-of-undefined,"['javascript', 'angular', 'jasmine', 'karma-runner']",1200,TRUE,0,1
Unit testing: How much should you cover (when whitebox testing)?,"<p>Assume I have the following class:</p>

<pre><code>class WeirdCalculator
{
  public:
    WeirdCalculator() { };

    int addWithOffset(int a, int b)
    {
        OffsetProvider provider;
        if (provider.applyOffset())
            return a + b + provider.getOffset();
        else
            return a + b;
    };
}
</code></pre>

<p>Further assume that <code>OffsetProvider::applyOffset()</code> and <code>OffsetProvider::getOffset()</code> not necessary <strong>always</strong> return the same values (<code>applyOffset()</code> is <code>false</code> on leap-years, and <code>getOffset()</code> normally returns <code>42</code> but yields a different value on Monday 13th).</p>

<p>Putting this class under unit-test (so you can refactor it), you will quickly notice that it is hard to cover the <code>else</code> path (but you can do it with some trickery). Looking closer you also notice that the result of <code>addWithOffset()</code> is dependent on the result of <code>getOffset()</code>.</p>

<p>Should your test coverage include those possible divergence points (i.e. also simulate a test in leap years and on Monday 13th)? The impending refactorings might render those tests soon obsolete, but if you do not cover them you might not spot that you accidently hardcoded that <code>42</code> instead of using the value from <code>getOffset()</code>.</p>
",https://stackoverflow.com/questions/51966187/unit-testing-how-much-should-you-cover-when-whitebox-testing,"['c++', 'unit-testing', 'refactoring']",72,TRUE,0,1
No results while using save of JPA in unit testing,"<p>I am having a weird situation while doing some unit testing. When I am using save method of JPA it's not returning anything, neither it's throwing any error.</p>

<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@DataJpaTest
@SpringBootTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class MerchantRepoTest {

    private Long personID = 12333333l;
    @Mock
    private ABC abcRepo;
    @Mock
    private Person personRepo;
    @Autowired
    private TestEntityManager testEntityManager;
    private Gson gson = new Gson();

    @Test
    public void testPerson() {

        System.out.println(""Starting................"");
        Person person = new Person();

        TxnLimit txnLimit = new TxnLimit();
        txnLimit.setType(""MONTHY"");
        txnLimit.setValue(1000000000l);
        List&lt;TxnLimit&gt; txnLimits = new ArrayList&lt;&gt;();
        txnLimits.add(txnLimit);
        person.setTxnLimits(gson.toJson(txnLimits));

        ABC abc = new ABC();
        abc.setPersonId(personId);
        Metadata metaData = new Metadata();
        metaData.setDescription(""DESC"");
        metaData.setName(""MUKUL"");
        person.setMetadata(metaData);
        person.setId(personId);
        person.setType(""Food"");
        person.accountToken(""hgh-hhjds-hdbhj"");

        try {
            Person per1=  personRepo.save(merchant);
            ABC savedA = abcRepo.save(abc);
            Thread.sleep(1000);
            System.out.println(""SAVED @@@@@@@@@@@@@@@@@@"");
            System.out.println(""ID1 + "" + per1.getId());
            System.out.println(""###############"");
        }  catch (Throwable t) {
            t.printStackTrace();
        }

        Person found = personRepo.findOne(personID);
        System.out.println(""FOUND..."" + found);
        String name = found.getMetadata().getName();
        Assert.assertEquals(name, ""MUKUL"");
    }
}
</code></pre>

<p>My test case is failing and I am getting NullPointerException at             <code>String name = found.getMetadata().getName();</code>, As I am getting found as null. I have tried to print middle steps and out of my surprise, something is wrong, while saving the details.</p>

<p>I am able to print                 <code>System.out.println(""SAVED @@@@@@@@@@@@@@@@@@"");</code> line but after that line I am not getting next two lines. i am also not getting any exception in <strong>catch</strong> block. The next message I am getting on my screen is roll-back of transaction.</p>

<pre><code>2018-10-31 18:17:14.759 [] [] [Test worker] INFO  t.context.transaction.TransactionContext:106 - Began transaction (1) for test context [DefaultTestContext@780636f3 testClass = MerchantRepoTest, testInstance = com.paytm.paylite.merchant.repo.MerchantRepoTest@735dc46, testMethod = testOK1@MerchantRepoTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@8006101 testClass = MerchantRepoTest, locations = '{}', classes = '{class com.paytm.paylite.merchant.MerchantServiceApp}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer@503407f6, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer@351584c0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@73b73c3d, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@6bc7795, [ImportsContextCustomizer@4342f78e key = [org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration, org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration, org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManagerAutoConfiguration]], org.springframework.boot.test.context.SpringBootTestContextCustomizer@67aa907e, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@50394650, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@63f5badc, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]]; transaction manager [org.springframework.orm.jpa.JpaTransactionManager@40ec0c87]; rollback [true]
Starting................
...
...
..
SAVED @@@@@@@@@@@@@@@@@@
FOUND...null
2018-10-31 18:17:15.829 [] [] [Test worker] INFO  t.context.transaction.TransactionContext:140 - Rolled back transaction for test: [DefaultTestContext@780636f3 testClass = MerchantRepoTest, testInstance = com.paytm.paylite.merchant.repo.MerchantRepoTest@735dc46, testMethod = testOK1@MerchantRepoTest, testException = java.lang.NullPointerException, mergedContextConfiguration = [WebMergedContextConfiguration@8006101 testClass = MerchantRepoTest, locations = '{}', classes = '{class com.paytm.paylite.merchant.MerchantServiceApp}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer@503407f6, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer@351584c0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@73b73c3d, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@6bc7795, [ImportsContextCustomizer@4342f78e key = [org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration, org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration, org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration, org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration, org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration, org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManagerAutoConfiguration]], org.springframework.boot.test.context.SpringBootTestContextCustomizer@67aa907e, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@50394650, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@63f5badc, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]]
</code></pre>

<p>I am unable to figure out what may be the reason behind this?</p>
",https://stackoverflow.com/questions/53085314/no-results-while-using-save-of-jpa-in-unit-testing,"['java', 'spring-boot', 'junit', 'jpa-2.0']",1360,FALSE,0,2
NUnit: Unit testing with complex object as test method parameter,"<p>I'm trying to perform a Unit testing on a controller method as below,</p>

<pre><code>[TestFixture]
public class HomeControllerTests
{
    static object[] TestData =
    {
        new object[] { new EmployeeAgreementRequest(), 1, 4 }
    };

    [Test, TestCaseSource(""TestData"")]
    public void AgreetoParticipate(EmployeeAgreementRequest employeeAgreementRequest, int brandID, int employeeID)
    {
        HomeController controller = new HomeController();
        IHttpActionResult actionResult = controller.AgreeToParticipateInSP(employeeAgreementRequest, brandID, employeeID);
        var contentResult = actionResult as OkNegotiatedContentResult&lt;Boolean&gt;;
        NUnit.Framework.Assert.IsNotNull(contentResult.Content);
        NUnit.Framework.Assert.AreEqual(true, contentResult.Content);
    }
}
</code></pre>

<p>This method is not getting picked up, when i say debug tests. Please let me know what am i missing here.</p>

<p>Also please let me know if this the right way to run test method with multiple test data.</p>

<p>Visual studio output: </p>

<pre><code>No tests found to run.
</code></pre>
",https://stackoverflow.com/questions/51247276/nunit-unit-testing-with-complex-object-as-test-method-parameter,"['unit-testing', 'nunit']",1555,TRUE,0,1
creating unit testing for write to file method in junit.,"<p>I am trying to write test methods in Intellij with jUnit. I can succesfully write to the file, however, I need to show that I can write a test method for this. I push in the write direction would be great. My ServerController class write to a file, checks a file for a username, and verifies username and password. This project is for a class and it appears that the most important lesson is learning about documentation (requirements, design, and testing). So, here I am trying to test.</p>

<pre><code>package appLayer;

import java.io.*;
import java.util.Scanner;

public class ServerController {
    public void writetoFile(String writeUsername, String writePassword) throws IOException {
        PrintWriter fileWriting = new PrintWriter(new FileOutputStream(""/Users/dannielsotelo/Documents/database.txt"", true));
        fileWriting.println(writeUsername + "","" + writePassword); //
        System.out.println(writeUsername + "" was saved to database.txt"");
        fileWriting.close();
    }

    public boolean findUsername(String fUsername) {
        File file = new File(""/Users/dannielsotelo/Documents/database.txt"");
        try{
            Scanner scanner = new Scanner(file);
            int lineNum = 0;
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                lineNum++;
                if(line.contains(fUsername))
                    return true;
            }
        } catch (FileNotFoundException e) {
            System.out.println(""File not found"");
        }
        return false;
    }

    public boolean verifyCredentials(String lUsername, String lPassword) {
        File file = new File(""/Users/dannielsotelo/Documents/database.txt"");
        try{
            Scanner scanner = new Scanner(file);
            int lineNum = 0;
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                lineNum++;
                if(line.contains(lUsername) &amp;&amp; line.contains(lPassword))
                    return true;
            }
        } catch (FileNotFoundException e) {
            System.out.println(""File not found"");
        }
        return false;
    }
}
</code></pre>

<p>and my ServerControllerTest class</p>

<pre><code>package appLayer;

import org.junit.Test;


import static org.junit.Assert.*;

public class ServerControllerTest {
    @Test
    public void testwritetoFile() {
    }

    @Test
    public void findUsername() {
    }

    @Test
    public void verifyCredentials() {


    }
}
</code></pre>
",https://stackoverflow.com/questions/50537536/creating-unit-testing-for-write-to-file-method-in-junit,"['java', 'junit4']",3302,TRUE,0,2
How to resolve TypeError in formgroup in Unit Testing Angular,"<p>I am trying to test my forms fields in angular with unit testing but karma says my property is <code>undefined</code>. I did a console log on the <code>formGroup</code> and it was <code>undefined</code>. But when I console logged my component, I get all the parameters.</p>

<p><strong>This is my component:</strong></p>

<pre><code>constructor(
  private _fb: FormBuilder,
  private donationService: DonationService,
  private formValidationMessages: ValidationserviceService,
  private ziptoLocationService: ZiptolocationService,
  private http: HttpClient,
  private snack: MatSnackBar,
  private cd: ChangeDetectorRef,
  private nservice: NService) { }

ngOnInit() {
  this.donationForm = this._fb.group({
  gross_gift_amount: ['', [Validators.required, Validators.pattern('^[0-9]+([.][0-9]{1,2})?$')]],
  billing_first_name: ['', [Validators.required, Validators.minLength(3)]],
  billing_last_name: ['', [Validators.required, Validators.maxLength(50)]],
</code></pre>

<p><strong>This is my Test</strong></p>

<pre><code>import { FormBuilder } from '@angular/forms';
import { DonationComponent } from './donation.component';

describe('Donation Form', () =&gt; {
  let component: DonationComponent;

beforeEach(() =&gt; {
      component = new DonationComponent( new FormBuilder(), null, null, null, null, null, null, null );
  });

it('should create a form with 10 controls', () =&gt; {
      expect(component.donationForm.contains('gross_gift_amount')).toBeTruthy();
  });
});
</code></pre>

<p><strong>This is my error</strong></p>

<blockquote>
  <p>TypeError: Cannot read property 'contains' of undefined</p>
</blockquote>
",https://stackoverflow.com/questions/48292318/how-to-resolve-typeerror-in-formgroup-in-unit-testing-angular,"['javascript', 'angular', 'unit-testing', 'karma-jasmine', 'formbuilder']",1954,TRUE,0,2
Unit testing multiple dependency injections without using constructor in Guice,"<p>I have written a class like following:</p>

<pre><code>public class MyClass {
@Inject
@Named(""MyMap1"")
private Map&lt;String, IEmployeeManager&gt; myMap1;

@Inject
@Named(""MyMap2"")
private Map&lt;String, ICustomerManager&gt; myMap2;

@Inject
private ConfigManager configManager;

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

<p>This class has no constructor. I cannot figure out how to inject depencies for this. In above code two map binders MyMap1 and MyMap2 I am constructing in module as follows:</p>

<pre><code>public class ManagerConfigModule extends AbstractModule {
@Override
protected void configure() {

    MapBinder&lt;String, IEmployeeManager&gt; myMap1 = MapBinder.newMapBinder(binder(), String.class,
            EmployeeManager.class, Names.named(""MyMap1""));

    myMap1.addBinding(SDEObj.class.getName()).to(SDManager.class)
            .asEagerSingleton();
    myMap1.addBinding(ASObj.class.getName()).to(VPManager.class)
            .asEagerSingleton();

    MapBinder&lt;String, ICustomerManager&gt; myMap2 = MapBinder.newMapBinder(binder(), String.class,
            CustomerManager.class, Names.named(""MyMap2""));
    ...
 }
</code></pre>
",https://stackoverflow.com/questions/48257742/unit-testing-multiple-dependency-injections-without-using-constructor-in-guice,"['java', 'guice']",223,FALSE,0,0
Laravel unit testing calling a method that calls that database,"<p>I have been trying to set up a unit test that calls a method where the database is called.  I have looked up mocking and faker and am confused about what to do.</p>

<p>In my test I call</p>

<pre><code>Logic::lookForClassificationException($exception_array, $content);
</code></pre>

<p>In my method there is a call to my ClassificationException model</p>

<pre><code>$exceptions = ClassificationException::select('exception')-&gt;get(); 
</code></pre>

<p>I am confused about how to set up a mock for this. ClassificationException is a table that has an id,  exception, previous_word, and after_word.  </p>

<p>How do I mock or fake the setup?</p>
",https://stackoverflow.com/questions/52883806/laravel-unit-testing-calling-a-method-that-calls-that-database,"['laravel', 'unit-testing', 'mocking', 'faker']",203,TRUE,0,1
Django Unit Testing (with DRF): How to test a Passwordresetview?,"<p>I'm currently trying to write my unittest for a successfull password reset.</p>

<p><strong>TLDR:</strong> I can't figure out how to handle the injection of the form data in the post request in the set-password view.</p>

<p>For context, let me give you my code first, since a line of code speaks more than 1000 words.</p>

<p>accounts/api/views.py:</p>

<pre><code>class PasswordResetView(generics.GenericAPIView):
    """"""(POST) Expects email. Sends a password reset mail to email.""""""
    permission_classes = (permissions.AllowAny,)
    serializer_class = PasswordResetSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            user = User.objects.get(email=serializer.data['email'])
            if user.is_active and user.has_usable_password():
                send_password_reset_email(user, request)
                return Response(
                    {""detail"": ""A password reset email has been send.""},
                    status=status.HTTP_204_NO_CONTENT
                )
            else:
                return Response(
                    {""detail"": ""This users password can't be reset.""},
                    status=status.HTTP_406_NOT_ACCEPTABLE
                )
</code></pre>

<p>accounts/api/urls.py:</p>

<pre><code>url(r'^password_reset/$', views.PasswordResetView.as_view(),
    name=""password_reset""),
</code></pre>

<p>accounts/api/serializers.py:</p>

<pre><code>class PasswordResetSerializer(serializers.Serializer):
    email = serializers.EmailField()

    def validate_email(self, value):
        if User.objects.filter(email__iexact=value).exists():
            return value
        else:
            raise serializers.ValidationError(""Email not found."")
</code></pre>

<p>accounts/utils.py:</p>

<pre><code>from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.contrib.sites.shortcuts import get_current_site
from django.utils import six
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode

from templated_email import send_templated_mail

password_reset_token = PasswordResetTokenGenerator()


def build_email_context(user_obj, request):
    current_site = get_current_site(request)
    context = {
        ""name"": """",
        ""domain"": current_site.domain,
        ""uid"": urlsafe_base64_encode(force_bytes(user_obj.pk)),
        'token': password_reset_token.make_token(user_obj)
    }
    if user_obj.name != """":
        context[""name""]: "" "" + user_obj.name
    return context


def send_password_reset_email(user_obj, request):
    context = build_email_context(user_obj, request)
    send_templated_mail(
        template_name=""password_reset"",
        from_email=""noreply@ordersome.com"",
        recipient_list=[user_obj.email],
        context=context
    )
</code></pre>

<p>The views that are linked to the route in the email are the standard CBV PasswordResetConfirmView and PasswordResetDoneView from django.contrib.auth.</p>

<p>And here is the test I wrote for this password reset sequence:</p>

<p>api/tests/test_views.py:</p>

<pre><code>from django.contrib.auth import get_user, get_user_model
from django.core import mail
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.reverse import reverse as api_reverse
from rest_framework.test import APITestCase

User = get_user_model()


class UserAPIViewsTestCase(APITestCase):
    def setUp(self):
        User.objects.create_user(
            email=""testuser@test.com"", password=""test1234"")
        self.login_url = api_reverse(""api:auth:login"")
        self.register_url = api_reverse(""api:auth:register"")
        self.password_reset_url = api_reverse(""api:auth:password_reset"")
        self.password_change_url = api_reverse(""api:auth:password_change"")
        self.user_delete_url = api_reverse(""api:auth:user_delete"")

    def test_api_auth_password_reset_success(self):
        """"""Test if a password reset successfully resets password.""""""
        pre_user = User.objects.get(email=""testuser@test.com"")
        self.assertEqual(pre_user.check_password(""test1234""), True)
        email_data = {
            ""email"": ""testuser@test.com"",
        }
        email_response = self.client.post(
            self.password_reset_url, email_data, format=""json"")
        self.assertEqual(email_response.status_code,
                         status.HTTP_204_NO_CONTENT)
        password_reset_data = {
            ""new_password1"": ""newtest1234"",
            ""new_password2"": ""newtest1234""
        }
        password_reset_response = self.client.get(
            mail.outbox[0].body[-94:-37], format=""json"", follow=True)
        path = password_reset_response.request[""PATH_INFO""]
        done_url = ""http://testserver"" + path
        password_reset_done_response = self.client.post(
            done_url, password_reset_data, format=""json"")
        post_user = User.objects.get(email=""testuser@test.com"")
        self.assertEqual(post_user.check_password(""newtest1234""), True)
</code></pre>

<p>The last <code>self.assertEqual</code> fails. But when I test the view manually, it works, so the code should be correct. How should I modify the test?</p>

<p>When I log out <code>done_url</code> it gives me <code>http://testserver/auth/reset/MQ/set-password/</code>, which should be the correct path.</p>

<p>And when I log out <code>password_reset_done_response</code> it says, that it is a TemplateResponse and the status_code is 200 (which should mean successful, but it's not). Also this response still seems to have the path <code>/auth/reset/MQ/set-password/</code> which should not be the case anymore.</p>
",https://stackoverflow.com/questions/50315432/django-unit-testing-with-drf-how-to-test-a-passwordresetview,"['django', 'django-rest-framework', 'django-views', 'django-testing', 'django-tests']",1158,TRUE,0,1
Unit testing a class that calls out to external service,"<p>I have the following class:</p>

<pre><code>public class SomeClass {

    private Dependency dependency;

    public SomeClass(Dependency dep){
        this.dependency = dep;
    }


    public void doSomething(String s){
        Foo f = dependency.getFoo(s);
        f.doWork(); // fails because f is null
    }
}
</code></pre>

<p>I am trying to write a unit tests that will cover the doSomething method in which getFoo is an external call that I am trying to mock as follows:</p>

<pre><code>@Mock
private Dependency dep;

@InjectMocks
private SomeClass _sc;


@Test
public void testSimple() {

Foo ff = new Foo();

when(dep.getFoo(""abc"")).thenReturn(ff);


SomeClass sc = new SomeClass();

sc.doSomething(""abc""); // fails on null pointer exception

}
</code></pre>

<p>Unfortunately, I am getting a null reference exception in my unit test - since the mock class isn't being returned. How can I fix it?</p>
",https://stackoverflow.com/questions/53621318/unit-testing-a-class-that-calls-out-to-external-service,"['java', 'unit-testing', 'mocking', 'mockito', 'powermock']",455,TRUE,0,2
without removing source file annotations verify code coverage unit testing,"<p>Every time I check test coverage with Jacoco, I need to comment/remove annotations from my source files. </p>

<p>Suppose I have a class with Spring annotations, I need to comment them. Only then, I can see the correct coverage. Otherwise, it shows wrong coverage.</p>

<pre><code>@RequestMapping(value=""/method3"", method={RequestMethod.POST,RequestMethod.GET})
@ResponseBody 
public String method3() {
    return ""method3"";
}
</code></pre>

<p>Let's say this is a method in a controller class. I want to write a JUnit test for it. When I check coverage while keeping the annotations it gives the wrong result.</p>

<p>If I remove the annotations from the method it will show the correct coverage.</p>

<p>How can I get correct coverage without removing the annotation?</p>
",https://stackoverflow.com/questions/49007927/without-removing-source-file-annotations-verify-code-coverage-unit-testing,"['java', 'junit', 'code-coverage', 'jacoco']",38,FALSE,0,0
"Mock tgz, tar, gz files for unit testing in C#","<p>I have been using System.IO.Abstractions for unit testing.
<a href=""https://github.com/tathamoddie/System.IO.Abstractions"" rel=""nofollow noreferrer"">https://github.com/tathamoddie/System.IO.Abstractions</a></p>

<p>Example from what i am doing now with System.IO.Abstractions</p>

<pre><code>MockFileSystem selectedFileSystem = new MockFileSystem(
               new Dictionary&lt;string, MockFileData&gt;
               {
                    { @""c:\test\"", new MockDirectoryData()},
                    { @""c:\test\test.txt"", new MockFileData(""file content"")},
               });
</code></pre>

<p>I am searching for a way to mock tgz, tar and gz files in the same way as files and directorys in the code above so i can test my extract methods.</p>

<p>I want to do something like this, is there a nuget packet or some other solution?</p>

<pre><code>MockTGZ mytgz = new MockTGZ(
               new Dictionary&lt;string, MockFileData&gt;
               {
                    { @""folderInsideTGZ\"", new MockDirectoryData()},
                    { @""test.txt"", new MockFileData(""file content"")},
               });
</code></pre>
",https://stackoverflow.com/questions/50172745/mock-tgz-tar-gz-files-for-unit-testing-in-c,"['c#', 'unit-testing']",193,FALSE,0,0
Unit Testing UWP app that references unmanaged dll causes System.TypeLoadException,"<p>Trying to Unit Test a UWP app that has a dependency on a .winmd file.
If the unit test calls a method in the app that makes a call on a class in the unmanaged dll then I get a System.TypeLoadException. I've tried referencing different .winmd files and using either MSTest framework or xunit but always get the same error. Other unit tests work fine.</p>

<p>Issue can be reproduced.. </p>

<ul>
<li>Create a new solution with a Universal Windows test project.</li>
<li>Add the required nuget packages for xunit(xunit, xunit.runner.visualstudio) or MSTest(MSTest.TestFramework, MSTest.TestAdapter) - it fails with either framework.  </li>
<li>Add a reference to an unmanaged dll. I used SamplesNative.winmd that can be found as part
of the Windows UI Dev Labs -
<a href=""https://github.com/Microsoft/WindowsUIDevLabs"" rel=""nofollow noreferrer"">https://github.com/Microsoft/WindowsUIDevLabs</a>.</li>
<li>Create a unit test that calls on the unmanaged dll. Using SamplesNative above I added:<br>
var helper = new DeviceLostHelper();</li>
<li>Run unit test and it should fail with - System.TypeLoadException: Requested Windows Runtime type 'SamplesNative.DeviceLostHelper' is not registered. ---> System.Runtime.InteropServices.COMException: Class not registered </li>
</ul>

<p>Any help would be great. Thanks.</p>
",https://stackoverflow.com/questions/48178676/unit-testing-uwp-app-that-references-unmanaged-dll-causes-system-typeloadexcepti,"['c#', 'unit-testing', 'uwp', 'mstest', 'xunit']",251,TRUE,1,1
Rspec: unit testing for the merge! method in Ruby hash,"<p>I have a piece of code which has:</p>

<pre><code>requests.each do |request|
  request.each do |rqst|
    select_keys = [""author"", ""author_name""]
    selected_unit_req = rqst.select { |m| select_keys.include?(m) }
    user = Etl::Models::User.where(username: selected_unit_req[""author""][""username""] )
    user.merge!({ author_name: selected_unit_req[""author""][""name""] })
  end
end
</code></pre>

<p>I am unable to test the merge! method , getting <code>NoMethodError:undefined method '[]' for nil:NilClass</code> when I run my existing unit tests. Any suggestions?</p>
",https://stackoverflow.com/questions/53841404/rspec-unit-testing-for-the-merge-method-in-ruby-hash,"['ruby', 'unit-testing', 'rspec']",433,FALSE,-1,1
apache storm unit testing a bolt in a live topology,"<p>I have a storm topology that have a spout that connects to a kafka queue and the forwards the tuple to my bolt for processing. I want to do unit testing on the bolt only, not the whole segment from <code>kafka -&gt; spout -&gt; bolt</code>. However, I also want to test the bolt in a storm topology instance, not just the pure functionality of it. The reason is that the bolt actually sends the processed data to a cassandra database. </p>

<p>So one way for me to achieve this is to make a test spout, connect it to the bolt, and send test tuples through the test spout to the bolt. However, that seems like maybe too much work for a test. Is there a better way to do this? Like hijacking the original spout in test to send some test tuples?</p>
",https://stackoverflow.com/questions/48712824/apache-storm-unit-testing-a-bolt-in-a-live-topology,"['unit-testing', 'apache-storm']",513,TRUE,0,1
Unit-testing VueJS component doesn&#39;t seem to register click() invocation,"<p>I have a fairly simple VueJS component called ""Reveal""; it hides a message until somebody clicks on it, like so:</p>

<pre><code>&lt;template&gt;
&lt;div&gt;
    &lt;div v-show=""!isShowing""&gt;
        &lt;span v-on:click=""show""&gt;ANSWER (Click to reveal)&lt;/span&gt;
    &lt;/div&gt;
    &lt;div v-show=""isShowing""&gt;
        &lt;span v-on:click=""hide""&gt;{{ message }} (Click to hide)&lt;/span&gt;
    &lt;/div&gt;
&lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
export default {
    props: ['message'],
    data() {
        return {
            isShowing: false
        };
    },
    methods: {
        show: function() {
            this.isShowing = true;
        },
        hide: function() {
            this.isShowing = false;
        }
    }
}
&lt;/script&gt;
</code></pre>

<p>Now I'm trying to test it with the following Reveal.spec.js, using Mocha+Chai, like so:</p>

<pre><code>import { expect } from 'chai'
import { shallowMount } from '@vue/test-utils'
import Reveal from '@/components/Reveal.vue'

describe('Reveal.vue', () =&gt; {
  it('doesn\'t reveal the message when instantiated', () =&gt; {
    const msg = 'secret message'
    const wrapper = shallowMount(Reveal, {
      propsData: { 
        message: msg
      }
    })

    const spans = wrapper.findAll('span')
    expect(spans.length).to.equal(2);

    expect(spans.at(0).text()).to.include(""ANSWER"");
    expect(spans.at(0).isVisible()).to.be.true;

    expect(spans.at(1).text()).to.include(msg);
    expect(spans.at(1).isVisible()).to.be.false;
  })

  it('reveals the message when clicked', () =&gt; {
    const msg = 'secret message'
    const wrapper = shallowMount(Reveal, {
      propsData: {
        message: msg 
      }
    })
    wrapper.trigger('click')

    const spans = wrapper.findAll('span')
    expect(spans.length).to.equal(2);

    expect(spans.at(0).text()).to.include(""ANSWER"");
    expect(spans.at(0).isVisible()).to.be.false;

    expect(spans.at(1).text()).to.include(msg);
    expect(spans.at(1).isVisible()).to.be.true;
  })
})
</code></pre>

<p>My problem is that the call to wrapper.trigger() doesn't seem to actually trigger the click--or, perhaps more accurately, the ""v-show"" doesn't seem to be accurately reflected in the resulting DOM nodes, since the first span appears to remain visible even though after the click the isShowing boolean should be flipping its value.</p>

<p>I'm absolutely certain I'm misunderstanding what's going on here, because something this simple should be blindingly straightforward. Where am I going wrong?</p>
",https://stackoverflow.com/questions/53466988/unit-testing-vuejs-component-doesnt-seem-to-register-click-invocation,"['vuejs2', 'vue-component']",278,TRUE,0,1
How to mock memcache in go lang for unit testing?,"<p>I want to mock memcache cache data in go lang to avoid authhorization
 i tried with gomock but couldn't work out as i dont have any interface for it.</p>

<pre><code>func getAccessTokenFromCache(accessToken string)

func TestSendData(t *testing.T) {
mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()
mockObj := mock_utils.NewMockCacheInterface(mockCtrl)
mockObj.EXPECT().GetAccessToken(""abcd"") 
var jsonStr = []byte(`{
    ""devices"": [
        {""id"": ""avccc"",

        ""data"":""abcd/""
        }
            ]
}`)
req, err := http.NewRequest(""POST"", ""/send/v1/data"", 
bytes.NewBuffer(jsonStr))
req.Header.Set(""Content-Type"", ""application/json"")
 req.Header.Set(""Authorization"", ""d958372f5039e28"")

rr := httptest.NewRecorder()
handler := http.HandlerFunc(SendData)
handler.ServeHTTP(rr, req)
if status := rr.Code; status != 200 {
    t.Errorf(""handler returned wrong status code: got %v want %v"",
        status, http.StatusOK)
}
expected := `{""error"":""Invalid access token""}`
body, _ := ioutil.ReadAll(rr.Body)

if string(body) != expected {
    t.Errorf(""handler returned unexpected body: got %v want %v"",
        string(body), expected)
}




func SendData(w http.ResponseWriter, r *http.Request) {

accessToken := r.Header.Get(constants.AUTHORIZATION_HEADER_KEY)

t := utils.CacheType{At1: accessToken}
a := utils.CacheInterface(t)
isAccessTokenValid := utils.CacheInterface.GetAccessToken(a, accessToken)

if !isAccessTokenValid {
    RespondError(w, http.StatusUnauthorized, ""Invalid access token"")
    return
}
response := make(map[string]string, 1)
response[""message""] = ""success""
RespondJSON(w, http.StatusOK, response)

}
</code></pre>

<p>tried to mock using gomock </p>

<pre><code>package mock_utils
</code></pre>

<p>gen mock for utils for get access controler
(1) Define an interface that you wish to mock.</p>

<p>(2) Use mockgen to generate a mock from the interface.
(3) Use the mock in a test:</p>
",https://stackoverflow.com/questions/49688682/how-to-mock-memcache-in-go-lang-for-unit-testing,"['go', 'memcached', 'gomock']",2036,FALSE,0,1
Unit testing @Asynchronous method in a spy in java 7,"<p>I am trying to test some awful legacy code (Java 7)<br>
I need to spy on a stateless service, but call an asynchronous method</p>

<p>I get the error</p>

<blockquote>
  <p><strong>Object does not represent an actual Future</strong></p>
</blockquote>

<p>How should I try and test this?</p>

<pre><code>@InjectMocks
private OrderDataImport spyImporter;

/* has spyImporter as a dependency */
@InjectMocks
private ImportService sut; /* system under test */

@Before
public void setUp() {
    // create spy
    spyImporter = Mockito.spy(new OrderDataImport());
    MockitoAnnotations.initMocks(this);
}

@Test
public Test() {
   sut.import();
}
</code></pre>

<p>Import Code</p>

<pre><code>class ImportService {
   @EJB
   private OrderDataImport dependency;


   public boolean import() {
       List&lt;Future&lt;Result&gt;&gt; resultList = new ArrayList&lt;&gt;();

       int THREAD_COUNT = 3;
       while (THREAD_COUNT-- &gt; 0)
           resultList.add(dependency.create(...));

       for (int i = 0; i &lt; resultList.size(); i++) {
           /* Object does not represent an actual Future */
           Result result = resultList.get(i).get(60, TimeUnit.MINUTES);
       }           
   }
}
</code></pre>
",https://stackoverflow.com/questions/53221689/unit-testing-asynchronous-method-in-a-spy-in-java-7,"['java', 'junit', 'mockito', 'future']",174,TRUE,0,2
.NET Core 2.1 Unit Testing with NHibernate and InMemory SQLite,"<p>I'm getting the following error when I run my XUnit tests</p>

<blockquote>
  <p>FluentNHibernate.Cfg.FluentConfigurationException : An invalid or incomplete configuration was used while creating a SessionFactory. Check PotentialReasons collection, and InnerException for more detail.</p>
  
  <p>NHibernate.HibernateException : Could not create the driver from NHibernate.Driver.SQLite20Driver, NHibernate, Version=5.1.0.0, Culture=neutral, PublicKeyToken=aa95f207798dfdb4.
      System.Reflection.TargetInvocationException : Exception has been thrown by the target of an invocation.
          NHibernate.HibernateException : The DbCommand and DbConnection implementation in the assembly System.Data.SQLite could not be found. Ensure that the assembly System.Data.SQLite is located in the application directory or in the Global Assembly Cache. If the assembly is in the GAC, use  element in the application configuration file to specify the full name of the assembly.</p>
</blockquote>

<p>I'm referencing FluentHNHibernate v2.1.2, NHibernate 5.1.3, System.Data.SQLite.Core v1.0.109.1 as Nuget Packages and working with Visual Studio 2015.</p>

<p>All other solutions I've seen here have been fixed with adding System.Data.SQLite but I have not been able to get this to work.</p>

<p>I also tried setting the test project to Build x64 only but that did not work.</p>

<p>Thank you for your assistance with this issue.</p>
",https://stackoverflow.com/questions/52137768/net-core-2-1-unit-testing-with-nhibernate-and-inmemory-sqlite,"['.net-core', 'fluent-nhibernate', 'xunit.net', 'system.data.sqlite']",478,FALSE,0,1
iOS - Unit Testing asynchronous private function in Presenter of MVP,"<p>Hello I'm trying to unit testing a private function which located in Presenter </p>

<p>This is my Presenter Codes and I'm using Networking Singleton Object <code>APIService</code></p>

<pre><code>class MyPresenter {
  weak var vc: MyProtocol?

  func attachView(vc: MyProtocol?) {
     self.vc = vc
  }

  func request(_ id: String) {
    if id.count == 0 {
      vc?.showIDEmptyAlert()
      return
    }
    fetch(id)
  }

  private func fetch(_ id:String) {
    DispatchQueue.global.async {
      APIService.shared.fetch(id) { (data, err) in 
        if let err = err {
          self.vc?.showErrorAlert()
          return
        }
        self.vc?.update(data)
      }
    }
  }
}
</code></pre>

<p>and this is my ViewController codes </p>

<pre><code>class MyViewController: UIViewController, MyProtocol {
  private var presenter: MyPresenter = MyPresenter()

  override func viewDidLoad() {
    super.viewDidLoad()
    presenter.attachView(vc: self)
  }

  func showIDEmptyAlert() {
    self.present .. 
  }

  func showErrorAlert() {
    self.present .. 
  }

  func update(data: String) {
    self.label.text = data 
  }

  @IBAction func handleRegisterButton(_ sender: UIButton) {
    guard let id = idTextField.text else { return }
    presenter.request(id)
  }
}
</code></pre>

<p>These are my Presenter and View. And I wrote Test Code like this</p>

<p>First, I made Mock PassiveView Like this</p>

<pre><code>class MyViewMock: MyProtocol {
  private (set) var showEmptyIdAlertHasBeenCalled = false
  private (set) var showErrorAlertHasBeenCalled = false
  private (set) var updateHasBeenCalled = false

  func showEmptyIdAlert() {
    showEmptyIdAlertHasBeenCalled = true
  }
  func showErrorAlert() {
    showErrorAlertHasBeenCalled = true
  }
  func update(data: String) {
    updateHasBeenCalled = true
  }

}
</code></pre>

<p>So I expected that if I could test Presenter's <code>request(_:)</code> methods with valid id and invalid</p>

<p>but because <code>request(_:)</code> didn't get handler parameter and <code>APIService.shared.fetch</code> is asynchronous,  I couldn't get 
 correct result by calling <code>request(_:)</code>. (Always false)</p>

<p>How can I test this kind of Presenter? </p>
",https://stackoverflow.com/questions/52761008/ios-unit-testing-asynchronous-private-function-in-presenter-of-mvp,"['ios', 'swift', 'unit-testing', 'mvp', 'presenter']",680,TRUE,0,2
Unit testing : Error: TypeError: Cannot read property &#39;displayName&#39; of undefined,"<p>Test is updated. Able to do some other tests using the same format. 
This is what I have so far
headers.test.js</p>

<pre><code>import React, {Component} from 'react';
import   {Headers}  from './Headers';
import {configure} from 'enzyme';
import Adapter from 'enzyme-adapter-react-15';
import  renderer from 'react-test-renderer';

configure({adapter: new Adapter()});

describe('Headers', () =&gt; {

let tree;
let baseProps;
let mockauthKeyValues;
let mockheaderKeyValues;       
let mockaddNewKeyValue;

beforeEach(() =&gt; {
    baseProps = { // assing all of the props into MOCK
       authKeyValues: mockauthKeyValues,
       headerKeyValues: mockheaderKeyValues,
       addNewKeyValue: mockaddNewKeyValue
    }
})

 it('should render with all of the props', () =&gt; {  
    tree = renderer.create(&lt;Headers {...baseProps} /&gt;)
    let treeJson = tree.toJSON()
    expect(treeJson).toMatchSnapshot();
    tree.unmount()
  });
});
</code></pre>

<p>I will be testing each props and make sure it renders without it.
I believe I am making at mistake when I mock all of this.props. Especially mockheaderKeyValues. I dont think i am setting up correctly.</p>

<p>This is the current code: headers.js</p>

<pre><code>export class Headers extends Component {

 componentDidMount () {
if (this.props.authKeyValues == null) {
  this.setState({
    useDefaultData: false
  })
} else {
  this.setState({
    useDefaultData: true
  })
}
 }

generateKeyValues = () =&gt; {
if (this.props.headerKeyValues == null) {
  return (
    &lt;KeyValue
      id={shortid.generate()}
      type='headers'
      addNewKeyValue={this.props.addNewKeyValue}
    /&gt;
  )
} else {
  let defaultKeyValues = Object.keys(this.props.headerKeyValues).map   ((headerKey, idx) =&gt; {
    return (
      &lt;KeyValue
        key={headerKey}
        id={headerKey}
        type={this.props.headerKeyValues[headerKey].type}
        addNewKeyValue={this.props.addNewKeyValue}
        defaultData={this.props.headerKeyValues[headerKey]}
      /&gt;
    )
  })
  defaultKeyValues.push(
    &lt;KeyValue
      id={shortid.generate()}
      type='headers'
      addNewKeyValue={this.props.addNewKeyValue}
    /&gt;
  )
  return defaultKeyValues
 }
 }

 render () {
 return (
  &lt;div&gt;
    {this.generateKeyValues()}
  &lt;/div&gt;
)
</code></pre>

<p>}
}</p>
",https://stackoverflow.com/questions/53934059/unit-testing-error-typeerror-cannot-read-property-displayname-of-undefined,"['reactjs', 'unit-testing', 'jestjs', 'enzyme']",4973,TRUE,0,1
Unit testing when using a kotlin extension function with receiver,"<p>Is it possible to pass a specific value into an extension function with receiver, in a unit test?</p>

<p>I'm trying to test the folowing <strong>subscribe method</strong>:</p>

<pre><code>...
private lateinit var subscription: SubscriptionReceiveChannel&lt;UiStateModel&gt;

suspend fun subscribe(model: MainViewModel) {
        subscription = model.connect()
        subscription.consumeEach { value -&gt; loadView(value) /** or loadView(it) */ }
    }

private fun loadView(uiState: UiStateModel) {
        when(uiState) {
            is Loading -&gt; view.isLoading()
            is Error -&gt; view.isError(uiState.exception.localizedMessage)
            is Success -&gt; when {
                uiState.result != null -&gt; view.isSuccess(uiState.result)
                else -&gt; view.isEmpty()
            }
        }
    }
</code></pre>

<p>I want to be able to apply a specific value to the <code>consumeEach</code> function, but how can this be done?</p>

<p>Here's my unit test:</p>

<pre><code>...
private val view = mock&lt;MainView&gt;()
    private val model = mock&lt;MainViewModel&gt;()
    private val subscription = mock&lt;SubscriptionReceiveChannel&lt;UiStateModel&gt;&gt;()

    private val presenter = MainPresenter(view)

    @Test
    fun `When uistate is loading, view should show loading message`() = runBlocking {
        // Given
        val state = UiStateModel.Loading()
        whenever(model.connect()).thenReturn(subscription)
        whenever(subscription.consumeEach { any() }).thenAnswer({ state })

        // When
        presenter.subscribe(model)

        // Then
        verify(model).connect()
        verify(view).isLoading()
        verify(view, never()).isSuccess(anyString())
        verify(view, never()).isEmpty()
        verify(view, never()).isError(anyString())
    }
...
</code></pre>
",https://stackoverflow.com/questions/48788859/unit-testing-when-using-a-kotlin-extension-function-with-receiver,"['unit-testing', 'kotlin', 'kotlinx.coroutines']",267,FALSE,0,0
Unit Testing: Testing a class which has an outside method,"<pre><code>class A {
    int a;

    public int add() {
        B b = new B();
        a = b.calculate(4, 5);
        return a;
    }
}

class B {
    public int calculate(int x, int y) {
        return x * y;
    }
}
</code></pre>

<p>I want to test class A, where and did not want to test the b.calculate() in the add() method.
So I need to mock the class B.</p>

<p>Here is my code.</p>

<pre><code>@Mock
B bclass;

A aclass;

@Before
public void setUp() {
    bclass = new B();
    aclass = new A();
}

@Test
public void testAClass() {
    when(bclass.calculate(4, 5)).thenReturn(45);
    assertEquals(45, aclass.add());
}
</code></pre>

<p>The test getting failed. What's wrong with it?</p>
",https://stackoverflow.com/questions/52070379/unit-testing-testing-a-class-which-has-an-outside-method,"['java', 'android', 'unit-testing', 'android-testing']",217,TRUE,0,4
How Spring unit testing is done with annotation based implementation,"<p>I have been learning Spring and what I understood is that biggest advantage of Spring is that it simplifies the unit testing because of its dependency injection feature ... here is what i understood, please correct me if I am wrong - suppose I have all the beans configuration in my Spring bean XML file and all my classes under <code>src</code> folder, now if I want to do unit testing (stand alone or through junit) then I will inject the test classes (having test data) into the main classes by having a Spring bean configuration file defined for my test classes.</p>

<p>Now, where I am confused is how I am going to achieve same when instead of having Spring XML based bean configuration I am having annotation based configuration. Suppose in my class if I have used <code>@Autowired</code> for <code>com.abc.TestData</code> which is under <code>src</code> folder then Spring will always inject the <code>TestData</code> object from <code>src</code> folder, even if I create <code>test</code> folder and there I create <code>com.abc.TestData_jUnit</code> then also I will not be able to inject this object.</p>

<p>So, does it mean that Spring's advantage of simplified unit testing fades when annotations are used instead of Spring bean XML file? I am quite sure that is not the case, so need your help to understand the things better. </p>
",https://stackoverflow.com/questions/51754832/how-spring-unit-testing-is-done-with-annotation-based-implementation,"['java', 'spring']",173,TRUE,0,1
How to test my views function using Django unit testing?,"<p>I have a Django app called sample. I need to check a function inside sample app's views.py file. When I try to import the function , I get an error saying sample.views is not a package.
I am trying to import the function like this :
<strong>from sample.views import samplefunc</strong></p>

<p>What am I doing wrong ? Thanks in advance</p>
",https://stackoverflow.com/questions/48860043/how-to-test-my-views-function-using-django-unit-testing,"['django', 'django-unittest']",67,FALSE,0,0
Unit testing of Spring ApplicationEventPublisher fails to consume the events,"<p>I want to integration test a Spring Boot 1.5.4 service that uses an @EventListener. My problem is: when the test is run, the events are correctly published, but they are not consumed.</p>

<p>My ultimate purpose is to use a @TransactionEventListener, but for simplicity I start with an @EventListener.</p>

<p>Here is my service class:</p>

<pre><code>@Service
public class MyService {

  private static final Logger logger = // ...

  private final ApplicationEventPublisher eventPublisher;

  @Autowired
  public MyService(ApplicationEventPublisher eventPublisher) {
    this.eventPublisher = eventPublisher;
  }

  @Transactional
  public void publish() {
    logger.warn(""Publishing!"");
    eventPublisher.publishEvent(new MyEvent());
  }

  // @TransactionalEventListener
  @EventListener
  public void consume(MyEvent event) {
    logger.warn(""Consuming!"");      // this is never executed in the test
  }

  public static class MyEvent {
  }
}
</code></pre>

<p>Here is my JUnit test class:</p>

<pre><code>@RunWith(SpringRunner.class)
@SpringBootTest
@SpringBootConfiguration
public class MyServiceIT {

  @Autowired
  MyService myService;

  @Test
  public void doSomething() {
    myService.publish();
  }

  static class TestConfig {

    @Bean
    public MyService myService() {
      return new MyService(eventPublisher());
    }

    @Bean
    public ApplicationEventPublisher eventPublisher() {
      ApplicationEventPublisher ctx = new GenericApplicationContext();
      ((AbstractApplicationContext)ctx).refresh();
      return ctx;
    }
  }
}
</code></pre>

<p>Note: the call to refresh() prevents an IllegalStateException with message ""ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context"" from occurring.</p>

<p>Does anyone have a clue? Many thanks in advance.</p>
",https://stackoverflow.com/questions/48286751/unit-testing-of-spring-applicationeventpublisher-fails-to-consume-the-events,"['spring-boot', 'spring-boot-test']",1323,FALSE,0,1
how to perform unit testing with route::resource Laravel 5.2,"<p>i want to perform unit testing on index page</p>

<p>this is my sample test code:</p>

<pre><code>public function testBasicExample()
{
   $this-&gt;visit('/admin/newsmaster')-&gt;seePageIs('NewsMaster.index');
}
</code></pre>

<p>this is my route:</p>

<pre><code>Route::resource('admin/newsmaster','FeedController',['only'  =&gt; ['index']]);
</code></pre>

<p>when i do <strong>phpunit</strong> in terminal i am getting message as:</p>

<p>FAILURES!</p>

<ul>
<li>Tests: 1, Assertions: 1, Failures: 1.</li>
<li>what is the problem with this..??</li>
</ul>
",https://stackoverflow.com/questions/49003160/how-to-perform-unit-testing-with-routeresource-laravel-5-2,"['php', 'laravel', 'unit-testing']",249,FALSE,0,1
"JSData 3.0.0, AngularJS 1.x unit testing with $http mocks","<p>I'm trying to figure out the current preferred way of unit testing modules which use js-data to gather data.</p>

<p>As I was starting to use jsdata I noticed that the adapter can take in a http method to use,  in the examples it shows the angularjs $http being used and I assumed (seemily incorrectly) that my existing test may actually work.  However, it doesn't appear to be and I'm finding most referring people to the js-data-mocks. </p>

<p>I want to verify that testing with the $http mocked is not going to work and perhaps why.</p>

<p>Also for js-data-mocks all the references don't appear to be using the 3.0 version of js-data and they seem to need js-data-angular which does not support 3.0</p>

<p>I'm assuming that I'm exploring this library in a transitional period.  It's a bit tough to know what is still applicable. </p>
",https://stackoverflow.com/questions/49735394/jsdata-3-0-0-angularjs-1-x-unit-testing-with-http-mocks,"['angularjs', 'unit-testing', 'jsdata']",27,FALSE,0,1
Unit testing capture failure not shown in istanbul code coverage,"<p>I'm trying to capture an error with my tests. I have istanbul showing that a current path is not covered by my tests. I think I have it covered but I'm curious why it's not showing in my coverage report.</p>

<p>This is the bit of code i'm testing, It says that my error if route is never covered.</p>

<pre><code>pool.getConnection((err, connection) =&gt; {
if (err) {
  console.log(err.message)
  return false
}
else{
   console.log('Connected!!');
 }
});
</code></pre>

<p>and here is the test I have for that</p>

<pre><code>it(""Should fail to provide a test database connection"" , function(done){
let pool  = mysql.createPool({
  connectionLimit : 200,
  host     : '***',
  user     : 'correctuser',
  password : 'WRONGPASSWORD',
  database : 'db'
});
pool.getConnection(function(err, connection) {
  if(err){
    console.log(err.message);
    done();
  }
});
})
</code></pre>
",https://stackoverflow.com/questions/48995672/unit-testing-capture-failure-not-shown-in-istanbul-code-coverage,"['javascript', 'unit-testing', 'testing', 'mocha.js', 'istanbul']",212,FALSE,0,1
grunt test - Fatal error: Unit testing is not implemented yet,"<p>I already setup the project environment, and install grunt succeed. In terminal I tried run <code>grunt</code> that showing this for me:</p>

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

<p>Then I follow the step.</p>

<ol>
<li>grunt build --env uat (this step running succeed)</li>
<li>grunt watch --env uat (this step got problem and I post <a href=""https://stackoverflow.com/questions/49874258/node-js-running-watch-default-task-waiting"">here</a>)</li>
<li>grunt test (this step showing error for me: <strong>Fatal error: Unit testing is not implemented yet</strong>)</li>
</ol>

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

<p>This project include: angularJS, jade, coffeescript, I already setup all environment, but still don't know how to run this project.</p>

<pre><code>###
    Build script for ** project.

    USAGE INSTRUCTIONS:
    Run `grunt` on the command line, from the same directory as this file
    or any subfolder to see usage instructions.

    TODO:
    - Fix totally broken `--debug` mode.
    - Unit testing support.
###

module.exports = (grunt) -&gt;

    ## Config ------------------------------------------------------------------

    Instructions = """"""
        Usage:
        1) Build all files once.
            grunt build --env Environment [--debug]
        2) Builds files and automatically re-build when any file changes are detected.
            grunt watch --env Environment [--debug]
        3) Builds and runs Unit Tests.
            grunt test

        Where:
        - debug: to compile for development (leave out to compile for production)
        - Environment can be the filenam (minus extension) of any environment
          file in the Environments/ directory.
    """"""


    ## Command Line options ----------------------------------------------------

    Debug = grunt.option(""debug"")?
    Env = grunt.option(""env"")

    if grunt.cli.tasks.length and grunt.cli.tasks[0] isnt ""test""
        unless Env? and grunt.file.exists ""Environments/#{Env}.litcoffee""
            grunt.fail.fatal ""Please specify a valid environment!""
            return


    ## Helpers -----------------------------------------------------------------

    usage = -&gt;
        grunt.log.writeln Instructions


    ## Grunt config ------------------------------------------------------------

    grunt.initConfig

        autoprefixer:
            options:
                browsers: [""last 3 versions""]
                map:
                    inline: false
            all:
                expand: true
                cwd: ""Build""
                src: [""*.css""]
                dest: ""Build""

        browserify:
            all:
                expand: true
                cwd: ""Build/Temp/CoffeeTemp""
                src: [""*.js""]
                dest: ""Build""
                ext: "".js""

        clean:
            all:
                src: [""Build""]
            temp:
                src: [""Build/Temp""]
            production: [
                ""Build/**/*.js.map""
                ""Build/**/*.css.map""
            ]
            stylesheets:
                src: [""Build/*.css""]
            scripts:
                src: [""Build/*.js""]
            jade:
                src: [
                    ""Build/*.html""
                    ""Build/templates/**/*.html""
                ]

        coffee:
            options:
                bare: true
                # sourceMap: Debug
            env:
                src: [""Environments/#{Env}.litcoffee""]
                dest: ""Build/Temp/CoffeeTemp/services/env.js""
            all:
                expand: true
                cwd: ""Source Code""
                src: [""**/*.litcoffee""]
                dest: ""Build/Temp/CoffeeTemp""
                ext: "".js""

        copy:
            static:
                expand: true
                cwd: ""Source Code""
                src: [ ""static/**/*"" ]
                dest: ""Build""

        cssmin:
            options:
                sourceMap: true
            build:
                expand: true
                cwd: ""Build""
                src: [""*.css""]
                dest: ""Build""

        htmlmin:
            all:
                options:
                    removeComments: true
                    collapseWhitespace: true
                    conservativeCollapse: true
                files: [
                    {
                        expand: true
                        cwd: ""Build""
                        src: [
                            ""*.html"",
                            ""templates/**/*.html""
                        ]
                        dest: ""Build""
                        ext: "".html""
                        filter: ""isFile""
                    }
                ]

        jade:
            options:
                doctype: ""html"" # keeps attributes with no value as-is (i.e.
                    # prevents div(md-raised) from becoming
                    # &lt;div md-raised=""md-raised""&gt;...)
                data: {}
                pretty: false
            all:
                files: [
                    expand: true
                    cwd: ""Source Code""
                    src: [
                        ""*.jade""
                        ""admin/*.jade""
                        ""activate/*.jade""
                        ""activation/*.jade""
                        ""cargoTrackingMobile/*.jade""
                        ""templates/**/*.jade""
                    ]
                    dest: ""Build""
                    ext: "".html""
                ]

        stylus:
            all:
                options:
                    linenos: true
                    compress: !Debug
                    sourcemap:
                        comment: true
                        inline: false
                        sourceRoot: "".""
                        basePath: "".""
                files: [
                    expand: true
                    cwd: ""Source Code/styles""
                    src: [
                        ""**/*.styl""
                        ""!**/_*.styl""
                    ]
                    dest: ""Build""
                    ext: "".css""
                ]

        uglify:
            options:
                mangle: {}
                sourceMap: Debug
            all:
                expand: true
                cwd: ""Build""
                src: [""*.js""]
                dest: ""Build""

        watch_default:
            scripts:
                files: [
                    ""Source Code/*.litcoffee""
                    ""Source Code/**/*.litcoffee""
                    ""!Source Code/static/**/*.litcoffee""
                ]
                tasks: [""scripts""]
            stylesheets:
                files: [""Source Code/styles/**/*""]
                tasks: [""stylesheets""]
            html:
                files: [
                    ""Source Code/*.jade""
                    ""Source Code/admin/*.jade""
                    ""Source Code/activate/*.jade""
                    ""Source Code/activation/*.jade""
                    ""Source Code/cargoTrackingMobile/*.jade""
                    ""Source Code/templates/**/*.jade""
                ]
                tasks: [""jade:all""]
            static:
                files: [""Source Code/static/**/*""]
                tasks: [""copy:static""]

    grunt.loadNpmTasks ""grunt-autoprefixer""
    grunt.loadNpmTasks ""grunt-browserify""
    grunt.loadNpmTasks ""grunt-contrib-clean""
    grunt.loadNpmTasks ""grunt-contrib-coffee""
    grunt.loadNpmTasks ""grunt-contrib-copy""
    grunt.loadNpmTasks ""grunt-contrib-cssmin""
    grunt.loadNpmTasks ""grunt-contrib-htmlmin""
    grunt.loadNpmTasks ""grunt-contrib-jade""
    grunt.loadNpmTasks ""grunt-contrib-stylus""
    grunt.loadNpmTasks ""grunt-contrib-uglify""
    grunt.loadNpmTasks ""grunt-contrib-watch""


    ## Custom tasks ------------------------------------------------------------

    grunt.task.renameTask ""watch"", ""watch_default""

    grunt.registerTask ""default"", ""Usage"", usage

    grunt.registerTask ""scripts"", ""Compiles the JavaScript files."", [
        ""clean:scripts""
        ""coffee:all""
        ""coffee:env""
        ""browserify:all""
        ""clean:temp""
    ].concat unless Debug then [""uglify:all""] else []

    grunt.registerTask ""stylesheets"", ""Compiles the stylesheets."", [
        ""clean:stylesheets""
        ""stylus:all""
        ""autoprefixer:all""
    ].concat unless Debug then [""cssmin""] else []

    grunt.registerTask ""test"", ""Run unit testing."", -&gt;
        grunt.fail.fatal ""Unit testing is not implemented yet"" # TODO

    grunt.registerTask ""build"", ""Compiles all of the assets and copies the files to the Build directory."", [
        ""clean:all""
        ""copy:static""
        ""jade:all""
        ""htmlmin:all""
        ""stylesheets""
        ""scripts""
    ].concat unless Debug then [""clean:production""] else []

    grunt.registerTask ""watch"", ""Builds and watches the project for changes."", [
        ""build""
        ""watch_default""
    ]
</code></pre>
",https://stackoverflow.com/questions/49956702/grunt-test-fatal-error-unit-testing-is-not-implemented-yet,"['angularjs', 'node.js', 'coffeescript', 'gruntjs', 'grunt-contrib-jade']",255,TRUE,0,1
Unit Testing Typescript/React that has Imported SVGs with Jasmine,"<p>I'm using Jasmine to write unit tests for a Typescript/React project. I'm having trouble because in one of the TSX files, I import an SVG. I am running my unit tests with the command <code>ts-node node_modules/.bin/jasmine</code> and when ts-node goes to transpile the .ts files, it fails on the error <code>Cannot find module './demo.svg'.</code></p>

<p>I'm fairly sure that if I build my project (I'm using webpack) then I could run tests against that build, but I'd rather run against the original source if possible, and write my tests in typescript as well. What am I missing? Is there any way to accomplish this?</p>

<p>Here is my sample code:</p>

<pre><code>import * as demoImg from './demo.svg'

const demo = {
   generate: (records: ForcedRecord[], groupings: Group[], params:any) =&gt; {

   return (
      &lt;div&gt;
         &lt;img src={demoImg}/&gt;
      &lt;/div&gt;
   )
}

export default demo
</code></pre>

<p>Here is my (abridged and trivialized) sample test:</p>

<pre><code>import demoCmp from '../../src/processors/demo/demo'

describe('demo', () =&gt; {

    let result

    beforeEach(() =&gt; {
        result = demoCmp.generate([], [], {})
    })

    it('should return a non-null result', () =&gt; {
        expect(result).not.toBeUndefined()
    })
})
</code></pre>
",https://stackoverflow.com/questions/52935561/unit-testing-typescript-react-that-has-imported-svgs-with-jasmine,"['reactjs', 'typescript', 'unit-testing', 'jasmine']",157,FALSE,0,1
Android Unit Testing with Mockito for External REST API calls,"<p>I am new to JUnit test cases in Android. I heard that by using Mockito we can achieve easily.</p>
<p>My Android Class makes an external call to a REST API Service (Retrofit) that returns a JSON response. I have to mock that response (hardcoded JSON) and write test cases.</p>
<p>Please share your idea how to achieve this.</p>
<p>i am able to achieve.</p>
<p>updating with a piece of code.</p>
<pre><code>class GenerateTripViewModelTest {

    @Mock
    private lateinit var mockRepository: GenerateTripRepository

    private val schedulerProvider = SchedulerProvider(Schedulers.trampoline(), Schedulers.trampoline())

    private lateinit var generateTripViewModel: GenerateTripViewModel
    
    @Before
    fun setUp() {
        MockitoAnnotations.initMocks(this)
        generateTripViewModel = GenerateTripViewModel(mockRepository, schedulerProvider)
    }

    @Test
    fun SearchSuccessCase() {
        val tripReq = GenerateTripReqModel(ArrayList&lt;String&gt;(),&quot;123&quot;,&quot;xxxx&quot;,&quot;xxxx&quot;)

        Mockito.`when`(mockRepository.generateTrip(tripReq)).thenReturn(Observable.just(GenerateTripResModel(&quot;&quot;)))

        val testObserver = TestObserver&lt;GenerateTripResModel&gt;()

        generateTripViewModel.generateTrip(tripReq).subscribe(testObserver)

        testObserver.assertNoErrors()
    }
</code></pre>
<p>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX</p>
<pre><code>class GenerateTripViewModel @Inject constructor(private val generateTripRepository: GenerateTripRepository,private val schedulerProvider: SchedulerProvider) : ViewModel() {
    
    fun generateTrip(reqModel: GenerateTripReqModel) = generateTripRepository.generateTrip(reqModel) 
}
</code></pre>
<p>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX</p>
<pre><code>@Singleton
class GenerateTripRepository @Inject constructor(
    private val apiServices: ApiServices, private val context: Context,
    private val appExecutors: AppExecutors = AppExecutors()) {

    /**
     * Generate Trip
     */
    fun generateTrip(reqModel: GenerateTripReqModel): Observable&lt;GenerateTripResModel&gt; = apiServices.generateTrip(reqModel)
}
</code></pre>
",https://stackoverflow.com/questions/52699729/android-unit-testing-with-mockito-for-external-rest-api-calls,"['android', 'junit', 'mockito', 'retrofit2', 'android-testing']",3369,TRUE,-2,2
Laravel Unit Testing Disable Policie / Error: This action is unauthorized,"<p>I'm new to Laravel, that's my first application. After a lot of readings about Unit Testing in Laravel, I decide to develop my own.</p>

<p>I have a controller which look like this:</p>

<pre><code>public function edit($id)
{
  $project = $this-&gt;projectRepository-&gt;getById($id);
  $types = $this-&gt;typeRepository-&gt;getAll();
  $thematics = $this-&gt;thematicRepository-&gt;getAll();
  $this-&gt;authorize('manage',$project);
  return view('project.edit',compact(['project','thematics','types']));
}
</code></pre>

<p>The purpose is to show the form for project editing. The problem is about this line: <code>$this-&gt;authorize('manage',$project);</code> which refer to this policie:</p>

<pre><code>&lt;?php

namespace App\Policies;

use App\Models\Project;
use App\Models\User;
use Illuminate\Auth\Access\HandlesAuthorization;

class ProjectPolicy extends Policy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can manage the project.
     *
     * Request made with Eloquent
     *
     * @param \App\Models\User $user
     * @param \App\Models\Project $project
     * @return mixed
    */
    public function manage(User $user, Project $project)
    {
        return $user-&gt;project-&gt;contains($project-&gt;id);
    }
}
</code></pre>

<p>In fact, when I try to test the edit method of the controller, I get: </p>

<blockquote>
  <p>Tests\Unit\Http\Controllers\ProjectControllerTest::test_edit_project
  Illuminate\Auth\Access\AuthorizationException: This action is
  unauthorized.</p>
</blockquote>

<p>My Test look like this:</p>

<pre><code>&lt;?php
namespace Tests\Unit\Http\Controllers;
use App\Http\Controllers\ProjectController;
use App\Http\Requests\ProjectCreateRequest;
use App\Models\Project;
use App\Repositories\ProjectRepository;
use App\Repositories\ThematicRepository;
use App\Repositories\TypeRepository;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\Database\Connection;
use Symfony\Component\HttpFoundation\ParameterBag;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Tests\ControllerTestCase;
use Mockery as m;
use Gate;
use Illuminate\Foundation\Testing\WithoutMiddleware;

class ProjectControllerTest extends ControllerTestCase
{
    use DatabaseTransactions;
    use WithoutMiddleware;
    /**
     * @var \App\Repositories\ProjectRepository
     * @var \App\Repositories\ThematicRepository
     * @var \App\Repositories\TypeRepository
     * @var \App\Models\Project
     * @var \Mockery\Mock
     */
    protected $projectRepoMock;
    protected $thematicRepoMock;
    protected $typeRepoMock;
    protected $projectMock;
    protected $db;

    public function setUp()
    {
        $this-&gt;afterApplicationCreated(function () {
            $this-&gt;db = m::mock(
                Connection::class.'[select,update,insert,delete]',
                [m::mock(\PDO::class)]
            );
            $manager = $this-&gt;app['db'];
            $manager-&gt;setDefaultConnection('mock');
            $r = new \ReflectionClass($manager);
            $p = $r-&gt;getProperty('connections');
            $p-&gt;setAccessible(true);
            $list = $p-&gt;getValue($manager);
            $list['mock'] = $this-&gt;db;
            $p-&gt;setValue($manager, $list);
            $this-&gt;projectRepoMock = m::mock(ProjectRepository::class);
            $this-&gt;thematicRepoMock = m::mock(ThematicRepository::class);
            $this-&gt;typeRepoMock = m::mock(TypeRepository::class);
            $this-&gt;projectMock = m::mock(Project::class . '[update, delete]');
        });
        parent::setUp();
    }
public function test_edit_project()
    {
        $projectInfo = [
            'thematic_id' =&gt; 1,
            'type_id' =&gt; 1,
            'state_id' =&gt; 1,
            'entity_id' =&gt; 1,
            'application_max' =&gt; 3,
            'title' =&gt; 'Ceci est un titre de projet',
            'description' =&gt; 'Ceci est une description de projet',
            'deliverable' =&gt; 'Ceci est un livrable de projet',
            'context' =&gt; 'Ceici est un contexte de projet',
            'topic' =&gt; 'Ceci est une problématique de projet',
            'technical_constraint' =&gt; 'Contraintes techniques',
            'financial_constraint' =&gt; 'Contraintes financières',
            'time_constraint' =&gt; 'Contraintes temporelles'
        ];
        $project = new Project($projectInfo);
        $controller = new ProjectController($this-&gt;projectRepoMock,$this-&gt;thematicRepoMock,$this-&gt;typeRepoMock);
        $this-&gt;thematicRepoMock-&gt;shouldReceive('getAll')-&gt;once();
        $this-&gt;typeRepoMock-&gt;shouldReceive('getAll')-&gt;once();
        $types = $this-&gt;typeRepoMock-&gt;getAll();
        $thematics = $this-&gt;thematicRepoMock-&gt;getAll();
        $this-&gt;thematicRepoMock-&gt;shouldReceive('getAll')-&gt;once()-&gt;andReturn($thematics);
        $this-&gt;typeRepoMock-&gt;shouldReceive('getAll')-&gt;once()-&gt;andReturn($types);
        $this-&gt;projectRepoMock-&gt;shouldReceive('getById')
            -&gt;once()
            -&gt;with($project-&gt;id)
            -&gt;andReturn($project);
        $view = $controller-&gt;edit($project-&gt;id);
        $this-&gt;assertEquals('project.edit', $view-&gt;getName());
        $this-&gt;assertArraySubset(['project' =&gt; $project], $view-&gt;getData());
        $this-&gt;assertArraySubset(['types' =&gt; $types], $view-&gt;getData());
        $this-&gt;assertArraySubset(['thematics' =&gt; $thematics], $view-&gt;getData());
    }
</code></pre>

<p>I've tried to do a lot of things but without success. One of them is to use:</p>

<pre><code>$this-&gt;withoutMiddleware();
</code></pre>

<p>Any ideas on how to disable the policie for testing?</p>
",https://stackoverflow.com/questions/48767070/laravel-unit-testing-disable-policie-error-this-action-is-unauthorized,"['php', 'unit-testing', 'laravel-5.5']",1011,FALSE,0,1
AngularJS 1.5 unit testing UI-Router state changes within controller,"<p>I have a AngularJS 1.5 app in which I use the UI-Router. The problem I'm having is with unit testing my state changes within the controller.</p>

<p>I have the following logic in my controller</p>

<pre><code>CostingsController = ($scope, $http, $state, flash) -&gt;

  if $state.current.name == ""costing_new""
    if $scope.current_division
      $http.get('/costings/new').then ((response) -&gt;
        $scope.costing = response.data
      )
    else
      flash(""alert"", ""Please select a division"", 2000)
      $state.go ""divisions""
</code></pre>

<p>I'm trying to test that the state changes to divisions when there is no division selected. This code works in practice but not in the tests. Here is my Jasmine test</p>

<pre><code>  describe ""when division is not selected"", -&gt;
    beforeEach(inject ( ($controller, $rootScope, $location, $state, $httpBackend) -&gt;
      @state = $state
      @redirect = spyOn(@state, 'go')
      @state.transitionTo('costing_new')

      ctrl = $controller('CostingsController', {
        $scope: @scope,
        $location: $location,
        $state: @state
      })
    ))

    it ""redirects to division"", -&gt;
      expect(@state.go).toHaveBeenCalledWith('divisions')
</code></pre>

<p>The error I get is;</p>

<pre><code>Chrome 63.0.3239 (Linux 0.0.0) CostingsController Controller: costings_controller new when division is not selected redirects to division FAILED
    Expected spy go to have been called with [ 'divisions' ] but it was never called.
        at Object.&lt;anonymous&gt; (/home/map7/code/pais/spec/javascripts/unit/costing_controller_spec.js.js:47:40)
Chrome 63.0.3239 (Linux 0.0.0): Executed 1 of 394 (1 FAILED) (skipped 393) ERROR (0.403 secs / 0.197 secs)
</code></pre>

<p><strong>Update: using angular.copy</strong></p>

<pre><code>  describe ""when division is not selected"", -&gt;
        beforeEach(inject ( ($controller, $rootScope, $location, $state, $httpBackend) -&gt;
          @state = angular.copy({current: {name: 'costing_new'}}, $state)
          @redirect = spyOn(@state, 'go')

          ctrl = $controller('CostingsController', {
            $scope: @scope,
            $location: $location,
            $state: @state
          })
        ))

        it ""redirects to division"", -&gt;
          expect(@state.go).toHaveBeenCalledWith('divisions')
</code></pre>

<p>If I use the above with angular.copy I get the following error;</p>

<pre><code>TypeError: Cannot set property current of #&lt;StateService&gt; which has only a getter
</code></pre>
",https://stackoverflow.com/questions/48738930/angularjs-1-5-unit-testing-ui-router-state-changes-within-controller,"['angularjs', 'unit-testing', 'coffeescript', 'angular-ui-router', 'jasmine']",197,FALSE,0,1
is it bad-practice for unit-testing for different outcome?,"<p>talking with a colleague about the following:</p>

<pre><code>[Theory(DisplayName = ""Notify if success only"")]
[InlineData(false)]
[InlineData(true)]
public async Task IngestAsync(bool isSuccess)
{
    if (!isSuccess)
    {
        _transfererMock.Setup(t =&gt; t.TransferAsync(It.IsAny&lt;Ingest&gt;(), It.IsAny&lt;CancellationToken&gt;()))
            .ReturnsAsync(Result.Fail(""testError""));
    }

    var res = await _ingester.IngestAsync(new Ingest());

    Assert.Equal(res.IsSuccess, isSuccess);

    if (isSuccess)
    {
        _ingestNotifierMock.Verify(inn =&gt; inn.Notify(It.IsAny&lt;string&gt;(), It.IsAny&lt;bool&gt;()), Times.Once);
    }
    else
    {
        _ingestNotifierMock.Verify(inn =&gt; inn.Notify(It.IsAny&lt;string&gt;(), It.IsAny&lt;bool&gt;()), Times.Never);
    }
}
</code></pre>

<p>Is it a bad practice to test the outcome for different result or is this just fine? </p>
",https://stackoverflow.com/questions/48186523/is-it-bad-practice-for-unit-testing-for-different-outcome,"['c#', 'unit-testing', 'xunit']",74,TRUE,0,1
Unit Testing with Mock. Parent does not have a default constructor,"<p>I'm trying to write a unit test and coming across the error, </p>

<blockquote>
  <p>Parent does not have a default constructor. The default constructor must be explicitly defined.</p>
</blockquote>

<p>I've had a look to see what this means and I see it mentioned that there is no public constructor.  Only thing is, my code does have this so I'm confused why there is this error.</p>

<p>This is the unit test..</p>

<pre><code>public void CalculateVat_ReturnsCorrectAmount()
{
    // Arrange
    const decimal expectedResult = 2;

    _mockSingleValueParameter = new Mock&lt;ISingleValueParameterService&gt;();
    _mockItemCache = new Mock&lt;ItemCache&gt;();
    _mockReferenceDataService = new Mock&lt;ReferenceDataService&gt;();

    _Calculator = new CostCalculator(_mockSingleValueParameter.Object, _mockItemCache.Object,
        _mockReferenceDataService.Object);
    // end

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

<p>The line </p>

<pre><code>_calculator = new CostCalculator(_mockSingleValueParameter.Object, _mockItemCache.Object,
            _mockReferenceDataService.Object)
</code></pre>

<p>is the one that throws the error.</p>

<p>This is the constructor of <code>CostCalculator</code>..</p>

<pre><code>public CostCalculator(
    ISingleValueParameterService singleValueParameterService, ItemCache cache, ReferenceDataService referenceDataService);
{
    _itemCache = cache;
    _singleValueParamService = singleValueParameterService;
    _refDataService = referenceDataService;
}
</code></pre>

<p>There is other code in the project that looks just like this as well but works..I can't understand what the difference is between them.</p>

<p>TIA!</p>
",https://stackoverflow.com/questions/51247458/unit-testing-with-mock-parent-does-not-have-a-default-constructor,"['c#', 'unit-testing', 'nunit', 'moq']",6471,TRUE,5,1
Cannot read property &#39;getters&#39; of undefined - VueJS unit testing with jest,"<p>I am writing unit tests for VueJS components and have consulted the ""Applying Global Plugins and Mixins"" section of <a href=""https://vue-test-utils.vuejs.org/guides/common-tips.html"" rel=""nofollow noreferrer"">Vue Test Utils Common Tips</a>. I have a component that depends on the Vuex store so it makes sense that I would transpose the example under that section for my purposes.</p>

<p>Here is my code for that component's specific .spec.js file:</p>

<pre><code>import { createLocalVue, mount } from '@vue/test-utils'
import AppFooter from '@/components/AppFooter/AppFooter'
import store from '@/store'

describe('AppFooter component', () =&gt; {
    const localVue = createLocalVue()
    localVue.use(store)

    it('AppFooter should have header slot', () =&gt; {
        const AppFooterComponent = mount(AppFooter, {
            localVue
        })

        /* TODO: Replace with a more appropriate assertion */
        expect(true).toEqual(true)
    })
})
</code></pre>

<p>This is pretty faithful to the example provided in the link above. However, the error I receive when I run the test suite is as follows:</p>

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

<p>Should I be installing the Vue store differently?</p>
",https://stackoverflow.com/questions/51483415/cannot-read-property-getters-of-undefined-vuejs-unit-testing-with-jest,"['unit-testing', 'vue.js', 'vuejs2', 'jestjs', 'vuex']",9207,FALSE,5,2
Unit testing that items get filtered out of Observable (Jasmine/RxJS),"<p>I'm doing unit testing with Jasmine/Karma against an Angular service. I'd like to confirm that my service properly filters items.</p>

<p>For example, if I have a service to get people over a certain age, it </p>

<ol>
<li>should return people over the minimum age (positive case)</li>
<li>should NOT return people under a the minimum age (negative case)</li>
</ol>

<p>It's #2 that I'm struggling to test.</p>

<p>The service:</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>    getPeople(minAge: number): Observable&lt;string&gt; {
        const source = Observable.from([
            { name: 'Joe', age: 30 },
            { name: 'Frank', age: 20 },
            { name: 'Ryan', age: 50 }
        ]);
        return source
            .filter(person =&gt; person.age &gt;= minAge)
            .map(person =&gt; person.name);
    }</code></pre>
</div>
</div>
</p>

<p>The Positive 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-js lang-js prettyprint-override""><code>    it('should return people over 30', () =&gt; {
        const service = new MyService();
        const minAge = 30;
        service.getPeople(minAge).subscribe(people =&gt; {
            expect(people.length).toBeGreaterThan(0);
        });
    });</code></pre>
</div>
</div>
</p>

<p>And the Negative 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-js lang-js prettyprint-override""><code>it('should not return people over 55', () =&gt; {
        const service = new MyService();
        const minAge = 55;
        service.getPeople(minAge).subscribe(people =&gt; {
            expect(people.length).toBe(0); // WE NEVER GET HERE!
        });
    });</code></pre>
</div>
</div>
</p>

<p>In the negative case, the Observable never returns anything, and rightly so.  But, how do I write a unit test to confirm this?</p>
",https://stackoverflow.com/questions/48389737/unit-testing-that-items-get-filtered-out-of-observable-jasmine-rxjs,"['angular', 'unit-testing', 'jasmine', 'rxjs', 'observable']",3100,TRUE,4,2
How to create new event for unit testing in Angular 2?,"<p>Hi I am writing unit test case for my angular code. I am trying to update textbox in gridview. Below is my gridview code.</p>

<pre><code>&lt;input *ngIf=""editing[rowIndex + '-scopevalue']"" class=""inline-editor"" autofocus (blur)=""updateValue($event, 'scopevalue', value, rowIndex)"" type=""text"" [value]=""value"" /&gt;
</code></pre>

<p>Below function performs update.</p>

<pre><code> updateValue(event, cell, cellValue, rowIndex) {
        this.editing[rowIndex + '-' + cell] = false;
        this.rows[rowIndex][cell] = event.target.value;
        this.rowsCache[rowIndex][cell] = event.target.value;
        this.scopeEdit = this.rows[rowIndex];
        this.updateScope();
    }
</code></pre>

<p>Below unit test case I am writing to check above code.</p>

<pre><code> it('update scope name value', () =&gt; {
        var row = component.rows[0];
        let cell = 'scopevalue';
        let cellValue = row.scopevalue;
        let rowIndex = 0;
        component.updateValue('/bmw', cell, cellValue, rowIndex);
    });
</code></pre>

<p>In the above method, first parameter supposed to be event. Can someone help me how to create event? Any help would be appreciated. Thank you</p>
",https://stackoverflow.com/questions/50463378/how-to-create-new-event-for-unit-testing-in-angular-2,"['angular', 'typescript', 'karma-jasmine', 'angular-test']",13791,TRUE,4,3
unit testing native custom elements v1 web component with shadow dom,"<p>I have created a native custom element as web component with pure JS/HTML/CSS following the guide <a href=""https://developer.mozilla.org/en/docs/Web/Web_Components/Custom_Elements"" rel=""nofollow noreferrer"">here</a>. </p>

<p>Now I am wondering how can I write unit tests for such a component. There is an excellent library web component tester but I believe it is only meant for the components created with polymer.</p>

<p>As my component is not a polymer web component, rather a native one, can somebody please point me to the right direction for unit testing.</p>
",https://stackoverflow.com/questions/52157715/unit-testing-native-custom-elements-v1-web-component-with-shadow-dom,"['javascript', 'web-component', 'custom-element', 'web-component-tester', 'native-web-component']",2047,TRUE,4,1
unit-testing component whose props gets value from react navigation component,"<p>How can I write a unit test for a React Native component which gets its state's value from <strong>React Navigation</strong>, more specific <code>this.props.navigation.state.params</code>? This is the component class:</p>



<pre class=""lang-js prettyprint-override""><code>  class RecAreas extends Component{ 
    static navigationOptions =({navigation}) =&gt; ({
        title: navigation.state.params.title,

        headerStyle: {
            backgroundColor: ""#000000"",
        }, 
          headerTintColor: '#facf33',
    });
    constructor(props){
        super(props); 
        const params = this.props.navigation.state.params;
        this.state={
            key:params.gymId,
            dataSource: new ListView.DataSource({
                rowHasChanged: (row1, row2) =&gt; row1 !== row2
            }),
        };
        this.mainRef = db.ref(""facilities"");

    }
    componentDidMount(){
        this.listenForItem(this.mainRef)
    }
</code></pre>

<p>I Could not figure out how to pass the nested function as props for the unit test. In this case <code>this.props.navigation</code>, <code>this.props.navigation.state</code>, <code>this.props.navigation.state.params</code> are all objects. How do I mock them for unit test? In the below example I get <strong>TypeError: Cannot read property 'gymId' of undefined</strong> which makes sense because <code>params</code> is not defined. I need help to resolve this. This is a unit test for the component. Thank you in advance! 
(PS: it would be great to know as well how to mock <code>dataSource</code> props as well. One way I thought I could do this is to make a fake <code>dataSource</code> data structure  (print out the <code>dataSource</code> and look at its structure). Any pointers would be helpful. Thanks!) </p>

<pre class=""lang-js prettyprint-override""><code>import React from ""react"";
import RecAreas from ""../../app/screens/RecAreas"";
import renderer from ""react-test-renderer"";

    describe (""&lt;RecAreas"", () =&gt; {
        it(""renders without crashing"", () =&gt; {
        const navigationMock = {state: jest.fn()};



        const rendered = renderer.create(&lt;RecAreas navigation= 
                         {navigationMock}/&gt;).toJSON();

        expect(rendered).toBeTruthy();
        expect(rendered).toMatchSnapshot();
      });
    }
</code></pre>
",https://stackoverflow.com/questions/50096654/unit-testing-component-whose-props-gets-value-from-react-navigation-component,"['unit-testing', 'react-native', 'jestjs']",1136,FALSE,4,1
How to spy on Apollo Client cache calls for unit testing?,"<p>I am using enzyme to ""mount"" a component wrapped with <code>withApollo</code>, hence it has a <code>client</code> object in context that it finds available in the props. The component writes on the client cache using <code>writeQuery</code> conditionally, and I am writing a unit test that simulates those conditions, I would like to be able to assert that this cache method has been called with the expected arguments.</p>

<p>Following Apollo-Client guidelines, I am using the  <a href=""https://www.apollographql.com/docs/react/recipes/testing.html#MockedProvider"" rel=""nofollow noreferrer"">MockedWrapper</a>. I think this would a good place to intercept the client object and replace its <code>writeQuery</code> function with a mock function. I do not know how or if it is even possible.</p>

<p>Alternatively, I could ditch the <code>MockedProvider</code> and simulate the context entirely, but I do not know the expected object inside the context nor its shape/schema.</p>
",https://stackoverflow.com/questions/53566682/how-to-spy-on-apollo-client-cache-calls-for-unit-testing,"['jestjs', 'enzyme', 'react-apollo', 'apollo-client']",562,FALSE,4,0
Unit-testing a service that uses the EntityManagerInterface in Symfony 3.3,"<p>I have a service that uses the EntityManagerInterface:</p>

<pre><code>class DocFinderService
{
   protected $em;

   public function __construct(EntityManagerInterface $entityManager)
   {
     $this-&gt;em = $entityManager;
   }

  public function findDocs($specialtyCodes, $city, $state, $zip)
  {...}
</code></pre>

<p>How can I test the service using PHPUnit, specifically, how can I pass the <em>EntityManagerInterface</em> parameter from the test function?</p>
",https://stackoverflow.com/questions/48775662/unit-testing-a-service-that-uses-the-entitymanagerinterface-in-symfony-3-3,"['symfony', 'doctrine', 'phpunit']",1518,TRUE,3,2
Matching varargs in Mockito for unit testing in an overloaded method,"<p>I am not able to mock varargs on an overloaded constructor in Mockito. This is the method I want to test</p>

<pre><code>@Override
  public List&lt;User&gt; fetchDataFromExternalService() {
    return Arrays.asList(this.restTemplate.getForObject(URL, User[].class));
  }
</code></pre>

<p><code>User</code> is a POJO class that has attributes, getters and setters. RestTemplate instance is <a href=""https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html"" rel=""nofollow noreferrer"">Spring's Rest Template.</a>.</p>

<p>This function is an overloaded function and has the the following methods</p>

<pre><code>1) public &lt;T&gt; T getForObject(java.lang.String url,
                                    java.lang.Class&lt;T&gt; responseType,
                                    java.lang.Object... uriVariables)
                             throws RestClientException

2) public &lt;T&gt; T getForObject(java.lang.String url,
                                    java.lang.Class&lt;T&gt; responseType,
                                    java.util.Map&lt;java.lang.String,?&gt; uriVariables)
                             throws RestClientException
</code></pre>

<p>I am trying to mock the first function to return an array of users, but not matter what I try, it always returns <code>null</code>. I don't know what I am doing wrong.</p>

<p>My mocking function.</p>

<pre><code>User user = new User();
Mockito.when(this.restTemplate.getForObject(
        Mockito.anyString(), Mockito.eq(User[].class), (Object[]) Mockito.any())).thenReturn(new User[] {user});
</code></pre>

<p>I tried using a custom argument matcher as follows, </p>

<pre><code>Mockito.when(this.restTemplate.getForObject(
        Mockito.anyString(), Mockito.eq(User[].class),
        Mockito.argThat(new MyVarargMatcher()))).thenReturn(new User[] {user});
</code></pre>

<p>but it still returned <code>null</code> for me.</p>

<pre><code>  class MyVarargMatcher implements ArgumentMatcher&lt;Object[]&gt;, VarargMatcher {

    @Override
    public boolean matches(Object[] argument) {
      return true;
    }
  }
</code></pre>

<p>I tried using the approach in this post, but the method is deprecated.</p>

<p><a href=""https://stackoverflow.com/questions/2631596/how-to-properly-match-varargs-in-mockito"">How to properly match varargs in Mockito</a></p>

<p><a href=""https://static.javadoc.io/org.mockito/mockito-core/2.2.7/org/mockito/ArgumentMatchers.html#any()"" rel=""nofollow noreferrer"">https://static.javadoc.io/org.mockito/mockito-core/2.2.7/org/mockito/ArgumentMatchers.html#any()</a></p>

<p>Maven configuration</p>

<pre><code>&lt;dependency&gt;
    &lt;groupId&gt;org.mockito&lt;/groupId&gt;
    &lt;artifactId&gt;mockito-core&lt;/artifactId&gt;
    &lt;version&gt;2.13.0&lt;/version&gt;
    &lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
</code></pre>

<p>How can I resolve this issue?</p>
",https://stackoverflow.com/questions/48616261/matching-varargs-in-mockito-for-unit-testing-in-an-overloaded-method,"['java', 'unit-testing', 'mockito', 'spring-rest']",6307,TRUE,3,2
Unit testing Entity Framework Core 2.0 if using a stored procedure,"<p>I have a problem with unit testing data access layer. I query the database via stored procedures, so now I can't use Entity Framework in-memory database because in-memory database is not a relational database. Also, I read that I have to use integration tests but I can't find any example with testing using stored procedure. </p>

<p>So my question is how to test data access layer, do I need to create a test database that is same as my real database? </p>

<p>This is my code for data access layer: </p>

<pre><code>public class Repository&lt;TEntity&gt; : IRepository&lt;TEntity&gt; where TEntity : Domains.Users
{
    private DbSet&lt;TEntity&gt; dbSet;

    private readonly DbContext context;

    public Repository(DbContext context)
    {
        this.context = context;
        dbSet = context.Set&lt;TEntity&gt;();
    }

    public void Add(TEntity entity)
    {
        if (entity is Domains.Users)
        {
            SqlParameter param1 = new SqlParameter();
            param1.ParameterName = ""@Adress"";
            param1.DbType = System.Data.DbType.String;
            param1.Value = (entity as Domains.Users).Adress;

            SqlParameter param2 = new SqlParameter();
            param2.ParameterName = ""@Email"";
            param2.DbType = System.Data.DbType.String;
            param2.Value = (entity as Domains.Users).Email;

            SqlParameter param3 = new SqlParameter();
            param3.ParameterName = ""@Name"";
            param3.DbType = System.Data.DbType.String;
            param3.Value = (entity as Domains.Users).Name;

            SqlParameter param4 = new SqlParameter();
            param4.ParameterName = ""@Lastname"";
            param4.DbType = System.Data.DbType.String;
            param4.Value = (entity as Domains.Users).Lastname;

            context.Database.ExecuteSqlCommand(""sp_AddUser @Adress, @Email, @Name, @Surname"", param1, param2, param3, param4);
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/48972952/unit-testing-entity-framework-core-2-0-if-using-a-stored-procedure,"['c#', 'unit-testing', 'entity-framework-core']",1473,TRUE,4,1
Angular Unit Testing - Mock async calls of injected services with TestBed,"<p>I need to write unit tests for the following <code>DataService</code> ,</p>

<pre><code>@Injectable()
export class DataService {
   constructor(private config: ConfigService, private http: HttpClient) {

   }

   .....

   someMethod(){
        let apiUrl = this.config.get('api').url;   // LINE 1
   }
}
</code></pre>

<p>The <code>ConfigService</code> is injected to <code>DataService</code> that has a <code>load</code> function which gets the configuration from a json file. This <code>load</code> function will be invoked when the app is initialized. </p>

<pre><code>export function configServiceFactory(config: ConfigService) {
    return () =&gt; config.load();
}

...

providers: [
        ConfigService,
        {
            provide: APP_INITIALIZER,
            useFactory: configServiceFactory,
            deps: [ConfigService],
            multi: true
        }
    ]
</code></pre>

<p>Here's a part of <code>data-service.spect.ts</code> file,</p>

<pre><code>...

beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule
      ],
      providers: [DataService, ConfigService]
    });

    mock = TestBed.get(HttpTestingController);
    service = TestBed.get(DataService);
  });

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

<p>so when i run the test, in <code>LINE 1</code> i get that the <code>this.config.get('api')</code> is undefined. I can understand that it is because the <code>ConfigService</code> did not load the data from JSON. So now how i can i make the injected services also make the async calls during unit tests? </p>
",https://stackoverflow.com/questions/50817239/angular-unit-testing-mock-async-calls-of-injected-services-with-testbed,"['angular', 'karma-jasmine', 'angular-unit-test', 'angular-test']",3809,TRUE,3,1
Unit Testing verifying a companion object method is called (mocking a companion object),"<p>When switching to Kotlin, static methods are moved into a companion object. However, there is no obvious way to unit test other methods which call these ""static method"".</p>

<p>In Java, we could use PowerMockito's MockStatic(SomeClass.class) to verify a static method is called in the method under test. PowerMock loses its magic in Kotlin. </p>

<p>For testing, I have create the following classes.</p>

<pre><code>public class DummyJava {
    static public Void staticMechod(){
          System.out.print(""Dummy method is called"");
          return null;
     }
}

class DummyCompanion {
    companion object {
        fun someCompanionMethod(){
            System.out.printf(""companion method is called\n"")
        }
    }
}
</code></pre>

<p>Now there is a another class which calls the <code>DummyCompanion.someCompanion</code></p>

<pre><code>public class DummyWrapper {
    public void callAStaticMethod(){
        DummyJava.staticMechod();
    }

    public void callCompanionMethod(){
        DummyCompanion.Companion.someCompanionMethod();
    }
}
</code></pre>

<p>To unit test <code>callAStaticMethod()</code> We used the following</p>

<pre><code>@RunWith(PowerMockRunner.class)
@PrepareForTest({DummyJava.class, DummyCompanion.Companion.class})
public class staticClassTest {
    //This case works
    @Test 
    public void testForStaticMethod() {
        PowerMockito.mockStatic(DummyJava.class);   
        DummyWrapper testObject = new DummyWrapper();

        Mockito.when(DummyJava.staticMechod()).thenCallRealMethod();

        testObject.callAStaticMethod();

        PowerMockito.verifyStatic(Dummy.class);
        DummyJava.staticMechod();
    }

    //This case doesn't work. It always passes.
    @Test
    public void testForCompanionMethod() {
        PowerMockito.mockStatic(DummyCompanion.Companion.class);
        DummyWrapper testObject = new DummyWrapper();
        testObject.callCompanionMethod();
PowerMockito.verifyStatic(DummyCompanion.Companion.class,Mockito.times(1));
        DummyCompanion.Companion.someCompanionMethod();
}
</code></pre>

<p>My question is how to verify the companion method is called.</p>
",https://stackoverflow.com/questions/53174839/unit-testing-verifying-a-companion-object-method-is-called-mocking-a-companion,"['java', 'unit-testing', 'kotlin']",21189,TRUE,14,3
Check Unit testing in C: Best way to test static methods,"<p>I am using Check framework do to unit testing of my C code, and I couldn't find a proper way to test the static methods. </p>

<p>My work around, is not ideal at all and would like if someone can point me in the right direction on how to do it properly. My work around is simply by add #ifdef macro that changes the static methods to extern in case I pass -D DEBUG at compile time.</p>

<p>In the source file </p>

<pre><code>#ifdef DEBUG
unsigned ds_roundup_to_prime (const unsigned bsize) {
#else
static inline unsigned ds_roundup_to_prime (const unsigned bsize) {
#endif
</code></pre>

<p>And in the header file I do </p>

<pre><code>#ifdef DEBUG
unsigned ds_roundup_to_prime (const unsigned bsize);
#endif
</code></pre>

<p>Ideally source code shouldn't change to cater for unit tests. Unit-test framework, should must be capable of testing the source code as it will look in production. </p>

<p>Thanks</p>
",https://stackoverflow.com/questions/53146066/check-unit-testing-in-c-best-way-to-test-static-methods,"['c', 'unit-testing', 'static-methods']",1636,TRUE,2,2
Is endpoint unit testing possible based on only OpenAPI 3.0 file?,"<p>After some googling I decided to directly ask this:</p>

<p>Is it possible to run REST API endpoint ""build tests"" based on solely an OpenAPI 3.0 specification file?</p>

<p>I would like to add example request-response pairs to the OpenAPI spec file and have either an existing or self-written library run through all the such defined tests and report any failures.</p>

<p>As far as I understand the standard, it would be easily possible to include examples for requests and test the response in a schematic way (thinking <a href=""http://json-schema.org/"" rel=""nofollow noreferrer"">http://json-schema.org/</a>). But I don't yet see a way to incorporate more specific tests, such as testing a number in a specific response field to be an exact value. Also, it would be nice to have a way to sequentially test requests, but I don't expect to achieve that just from the spec file.</p>

<p>An optimal solution would be included in my repository and run the tests on localhost. Thank you all very much in advance.</p>
",https://stackoverflow.com/questions/49918250/is-endpoint-unit-testing-possible-based-on-only-openapi-3-0-file,"['rest', 'api', 'testing', 'build', 'openapi']",1064,TRUE,2,1
how to avoid decorators while unit testing in python flask application,"<p>I am new to python and flask. I wanted to create unit tests for an api written. We have used <code>jwt</code> for authentication.</p>

<p>To unit test, I don't want the flow to enter <code>@jwt_required</code> decorator. In addition to that I have chained a few other decorators for that method. </p>

<pre><code>class A():

   @jwt_required()
   @mandatory_fields_check
   @unlock_and_lock()
   def get(self, address, name): 
      ..
      ..
      ..
       return jsonify(
            {""payload"": data,
             ""message"": ""data received successfully""}), 200
</code></pre>

<p>Unit test I am trying to write </p>

<pre><code>def test_get():
   a_obj = A()
   a_obj.get(""address123"", 'xyz')
</code></pre>

<p>When I run above test using py.test, I am getting Runtime error</p>

<pre><code>    def _find_app():
            top = _app_ctx_stack.top
            if top is None:
               raise RuntimeError(_app_ctx_err_msg)
     RuntimeError: Working outside of application context.
E
E           This typically means that you attempted to use functionality that needed
E           to interface with the current application object in some way. To solve
E           this, set up an application context with app.app_context().  See the
E           documentation for more information.
</code></pre>

<p>Below are my objectives:</p>

<ol>
<li><p>I don't want flow to enter decorators logic</p></li>
<li><p>Jwt decorator is asking for context. However my intention is to unit test this method as a normal class method without any flask features. </p></li>
<li><p>How can I mock objects created inside the method under test?</p></li>
</ol>
",https://stackoverflow.com/questions/52400853/how-to-avoid-decorators-while-unit-testing-in-python-flask-application,"['python', 'unit-testing', 'flask', 'pytest', 'python-decorators']",3084,TRUE,2,3
Objective C - Best practice for Unit Testing with multiple test inputs,"<p>I'm writing unit test codes for an existing project. The project is in Objective-C and I have to test few functions with a number of inputs to the test cases. For example, I have a test case to test a function calculator where two parameters are inputted. Currently I create array to store the set of input values to run the test. The code used are as follows:</p>

<pre><code>- (void)setUp {
    [super setUp];
    self.vcToTest = [[BodyMassIndexVC alloc] init];
    input1 = [[NSMutableArray alloc] initWithObjects:@""193"", @""192"", @""192"", @""165"", @""155"", @""154"", nil];
    input2 = [[NSMutableArray alloc] initWithObjects:@""37"", @""37"", @""36"", @""80"",@""120"", @""120"", nil];
}



- (void)testCalculatorSuccess {
    for (int i=0; i&lt;input1.count; i++) {
        NSArray *expectedResult = [[NSArray alloc] initWithObjects: @""9.93"", @""10.04"", @""9.77"", @""29.38"", @""49.95"", @""50.60"", nil];
        NSString *actualResult = [self.vcToTest calculateResult:input1[i] andInput2:input2[i]];
        XCTAssertEqualObjects(actualResult, expectedResult[i]);
    }

}
</code></pre>

<p>I searched for best practices online but was not able to find any. Can someone help me with this? Am I running the test in the right way? What is the best practice to be followed in such cases? Should I create a test case for every set of input?</p>
",https://stackoverflow.com/questions/50927652/objective-c-best-practice-for-unit-testing-with-multiple-test-inputs,"['ios', 'objective-c', 'xctest']",2222,TRUE,2,3
How to get props of component when unit testing using jestjs,"<p>I am using shallow from enzyme. I want to get props that I have passed to component in my testing file. Like so in example but I am getting undefined.</p>

<pre><code>console.log(wrapper.props()) 
</code></pre>

<p>should return object of props but it returning some jsx object.</p>

<p>Kindly assist how to get props of some component for which I want to write test cases.</p>

<p>Here is my 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 from 'react';
import {
    configure,
    shallow
} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

import MenuList from './MenuList';
import {
    Link
} from 'react-router-dom';

configure({
    adapter: new Adapter()
});

const footerItem = {
    label: '',
    links: [{
        label: '',
        link: '/'
    }]
}

describe('&lt;MenuList /&gt;', () =&gt; {

            let wrapper;
            beforeEach(() =&gt; {
                    wrapper = shallow( &lt; MenuList footerItem = {
                            footerItem
                        }
                        / &gt; );
                    });

                it('should render Link', () =&gt; {
                    console.log(wrapper.props().footerItem); // This should print footerItem object but returning  undefined
                    expect(wrapper.find(Link).length).toBeGreaterThan(0);
                });
            });

// and here is the code of menulist component/


import React from 'react';
import { Link } from 'react-router-dom';

const menuList = (props) =&gt; {
    let linkArray=[];
        linkArray = props.footerItem.links.map((item,index)=&gt;{
            return &lt;li key={index}&gt;
                    &lt;Link to={item.link}&gt;
                        {item.label}
                    &lt;/Link&gt;&lt;/li&gt;
        })

   return (
        &lt;div className=""footer-link""&gt;
            &lt;h6&gt;{props.footerItem.label}&lt;/h6&gt;
                &lt;ul&gt;
                    {linkArray}
                &lt;/ul&gt;
        &lt;/div&gt;
   )
}
export default menuList;</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/51999411/how-to-get-props-of-component-when-unit-testing-using-jestjs,"['reactjs', 'facebook', 'testing', 'jestjs', 'enzyme']",5706,TRUE,2,1
Angular 5 unit testing: How to make change detection work properly?,"<p>How to make change detection in unit tests work properly?
From sources, changeDetection should be ran after microtasks are empty (including event tasks?).</p>

<pre><code>this._onMicrotaskEmptySubscription = ngZone.onMicrotaskEmpty.subscribe({
    next: () =&gt; {
        if (this._autoDetect) {
            // Do a change detection run with checkNoChanges set to true to check
            // there are no changes on the second run.
            this.detectChanges(true);
        }
    }
});
</code></pre>

<p>In this short example, change detection ran after setTimeout, but not after manually clicking on the element. Is there a proper way to trigger change detection after event dispatching (inside fakeAsync zone, without fixture.detectChanges because in this case change detection will not be the same as in real life)?</p>

<pre><code>import {
    fakeAsync, tick, ComponentFixture, TestBed, ComponentFixtureAutoDetect
} from '@angular/core/testing';
import {
    Component, QueryList, ViewChildren
} from '@angular/core';
import { By } from '@angular/platform-browser';
import { CommonModule } from '@angular/common';
describe('bug', () =&gt; {
    let host: Host;
    let fixture: ComponentFixture&lt;Host&gt;;
    @Component({
        selector: 'child',
        template: ``,
    })
    class Child {}
    @Component({
        template: `
            &lt;ng-container *ngFor=""let show of shows""&gt;
                &lt;child *ngIf=""show""&gt;&lt;/child&gt;
            &lt;/ng-container&gt;
            &lt;button (click)=""shows[1] = true""&gt;show&lt;/button&gt;`
    })
    class Host {
        shows = [false, false];
        @ViewChildren(Child) children: QueryList&lt;Child&gt;;
        constructor() {
            setTimeout(() =&gt; this.shows[0] = true, 50);
        }
    }
    fit('test', fakeAsync(() =&gt; {
        TestBed.configureTestingModule({
            imports: [
                CommonModule,
            ],
            declarations: [
                Host, Child,
            ],
            providers: [{
                provide: ComponentFixtureAutoDetect,
                useValue: true,
            }]
        });
        fixture = TestBed.createComponent(Host);
        host = fixture.componentInstance;
        tick(10);
        expect(host.children.length).toEqual(0);
        tick(50);
        expect(host.children.length).toEqual(1);
        const button = fixture.debugElement.query(By.css('button'));
        button.triggerEventHandler('click', new Event('click'));
        tick(50);
        // fixture.detectChanges();
        expect(host.children.length).toEqual(2); // fails here
    }));
});
</code></pre>
",https://stackoverflow.com/questions/49100634/angular-5-unit-testing-how-to-make-change-detection-work-properly,"['angular', 'angular5', 'angular2-testing', 'angular2-changedetection']",4188,TRUE,2,1
Handling external page redirection on unit testing - jasmine with code coverage,"<p>writing the unit testing for angular application, login mechanism works on single sing on concept, page will redirect to external url and set the cookie value for the login success (based on cookie setting local storage).</p>

<p>while testing that scenario browser redirects to external page and stops the unit test execution. Currently while doing the unit test commented the redirection and testing the remaining test cases. </p>

<p>While deploying to live again i have to uncomment the redirect code. </p>

<p>How can I handle this scenario in jasmine?</p>

<pre><code>    @Injectable()
export class AuthGuard implements CanActivate {
    constructor(
        private router: Router,
        private location: Location
    ) { }

    canActivate(): boolean {
        if (!localStorage.getItem('API_TOKEN')) {
            this.redirectTOLogin();
            return false;
        } else {
            return true;
        }
    }

    redirectTOLogin() {
        window.location.href = environment.appLoginUrl + environment.appUrl;
    }
}
</code></pre>

<blockquote>
  <p>spec.ts</p>
</blockquote>

<pre><code>    describe('Logged in guard should', () =&gt; {
    let loggedInGuard: AuthGuard;
    const router = {
        navigate: jasmine.createSpy('navigate')
    };

    // async beforeEach
    beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
            imports: [FormsModule, CommonModule],
            providers: [AuthGuard, Location, { provide: LocationStrategy, useClass: PathLocationStrategy },
                { provide: APP_BASE_HREF, useValue: '/' },
                { provide: Router, useValue: router }
            ]
        })
            .compileComponents(); // compile template and css
    }));

    // synchronous beforeEach
    beforeEach(() =&gt; {
        loggedInGuard = TestBed.get(AuthGuard);
    });

    it('be able to hit route when user is logged in', () =&gt; {
        localStorage.setItem('API_TOKEN', 'fgsdhfhg4359854dsfsdf#@dfg4545nvnsjfjkh');
        expect(loggedInGuard.canActivate()).toBe(true);
    });

    it('not be able to hit route when user is not logged in', () =&gt; {
        localStorage.removeItem('API_TOKEN');
        spyOn(loggedInGuard, 'redirectTOLogin');
        expect(loggedInGuard.redirectTOLogin).toHaveBeenCalled();
    });
});
</code></pre>
",https://stackoverflow.com/questions/49443092/handling-external-page-redirection-on-unit-testing-jasmine-with-code-coverage,"['angular', 'karma-jasmine']",10262,TRUE,2,1
Unit-testing with Jasmine/Karma on an Angular Google Charts component,"<p>I haven't found any way of doing an unit-test with Jasmine/Karma on an Angular2component which renders a chart from Google Charts. So I propose my own Q&amp;A in the hope that it could help other people also testing it:</p>

<p><em>What could be a good way to write a reliable test for a component like the one on the example below, that has a function to update the chart view when window is resized?</em></p>

<pre><code>import { Component, OnInit, Input } from '@angular/core';
import { Router } from '@angular/router';

declare var google: any;

@Component({
  selector: 'app-chart',
  templateUrl: './chart.component.html',
  styleUrls: ['./chart.component.scss'],
})
export class ChartComponent implements OnInit {
  @Input()
  chartData: string[][];

  options: {} = {
    height: 320,
  };

  constructor(private router: Router) {}

  ngOnInit() {
    google.charts.load('current', { packages: ['corechart'] });
    google.charts.setOnLoadCallback(() =&gt; this.drawChart(this.chartData));
    window.addEventListener('resize', () =&gt; {
      if (this.router.url === '/chart') {
        return this.drawChart(this.chartData);
      }
    });
  }

  drawChart(chartData) {
    const data = google.visualization.arrayToDataTable(chartData);
    const chart = new google.visualization.LineChart(
      document.querySelector('#chart'),
    );
    chart.draw(data, this.options);
  }
}
</code></pre>
",https://stackoverflow.com/questions/53781956/unit-testing-with-jasmine-karma-on-an-angular-google-charts-component,"['angular', 'unit-testing', 'charts', 'google-visualization', 'karma-jasmine']",2643,TRUE,2,2
PHP - Unit testing method with unmockable class in its body (PHPUnit),"<p>I have a method that uses another class to calculate its outcome, that I want to test using PHPUnit.</p>

<pre><code>/**
 * Returns true if the given user has been granted the given permission.
 *
 * @param User $user
 * @param AbstractPermission $permission
 * @return bool
 */
public function userPermissionGranted(User $user, AbstractPermission $permission) : bool
{
    // Retrieve model from database.
    $user_permission = UserPermission::scopeUser($user)
        -&gt;scopePermission($permission)
        -&gt;first();

    return $user_permission ? $user_permission-&gt;isGranted() : $permission-&gt;isGrantedByDefault();
}
</code></pre>

<p>Leaving out of consideration what this method actually does, I am wondering how to test this method. I can pass mocks of the <code>User</code> and <code>AbstractPermission</code> classes to the method, but the <code>UserPermission</code> class that is used inside the method's body (to retrieve a model from the database) I can do nothing with.</p>

<p>On top of that, if I pass mocks of the <code>User</code> and <code>Permisson</code> classes, they won't exist in the database, so when <code>UserPermission</code> queries the database, it will receive no results and the method will fail.</p>

<p>What do I do here? Is it considered good practice to simply mock the database (i.e. copying the live db structure and filling it with test data) and let my model query that database, and just trusting that everything is OK? Any suggestions on what to do here?</p>

<p>On a side note, <code>UserPermission</code> is an Eloquent model. I am merely making use of Eloquent here - without Laravel.</p>
",https://stackoverflow.com/questions/49649619/php-unit-testing-method-with-unmockable-class-in-its-body-phpunit,"['php', 'unit-testing', 'eloquent', 'phpunit']",345,TRUE,2,2
How to do unit testing for nested &quot;using&quot; statements in C#?,"<p>I'm working with big legacy projects.
I've started writing unit tests with xUnit. 
Also, I'm using the Moq framework.
I've read a lot of articles here, but have not found a clear answer. I stuck with understanding how can I do mocks for two IDisposable objects inside a tested method? The method I would like to test:</p>

<pre class=""lang-cs prettyprint-override""><code>public class SomeService: ISomeService
{
  ...
  public async Task&lt;Settings&gt; GetSettings(UserIdentity user)
    {
        SettingsDBModel dbModel;
        using (DBHelperAsync dbHelper = new DBHelperAsync(user))
        {
            using (DBHelperReaderAsync reader = await dbHelper.ExecuteReader(""Stored procedure Name"", new { UserID = user.UserID }))
            {
                dbModel = await reader.GetResult&lt;SettingsDBModel&gt;();
            }
        }
        var settings = new Settings(dbModel);
        return settings;
    }
  ...
}
</code></pre>

<p>I want to <code>reader.GetResult()</code> method returns some fake data. Any thought how should be implemented of mocks for DBHelperAsync and DBHelperReaderAsync objects?</p>
",https://stackoverflow.com/questions/52502314/how-to-do-unit-testing-for-nested-using-statements-in-c,"['c#', 'unit-testing', 'moq', 'xunit']",509,TRUE,1,1
How can I put List value in thenReturn for unit testing?,"<p>I use mockito to test a data get from a website. It will return a list. I put a list below but it does not work. </p>

<pre><code>  @Test
  void getData() throws IOException {
    when(dataService.getData()).thenReturn(""123123"" ,""fghf"",""fghgfh"");
</code></pre>

<p>Intellj popped up it requires <code>List&lt;String&gt;t, list&lt;String&gt;...ts</code></p>

<p>Any suggestion?</p>
",https://stackoverflow.com/questions/53767495/how-can-i-put-list-value-in-thenreturn-for-unit-testing,"['java', 'unit-testing']",2365,TRUE,1,2
Spring Boot + Unit testing a function using UUID in local scope,"<p>I have the following function that I want to write unit test for:</p>

<pre><code>@SpringBootTest
@RunWith(SpringRunner.class)
public class MyMessageServiceTests {    

    @Autowired
    MyMessageService  myMessageService;


    @MockBean
    MyMessageRepository myMessageRepository;    

    public List&lt;MyMessage&gt; updateAndSelect() {
                UUID uuid = UUID.randomUUID();
                String identifier = uuid.toString();
                myMessageRepository.updateForSelect(identifier);
                //a private method of the service that returns records based on identifier            
                return findAllByIdentifier(identifier);
            }
}
</code></pre>

<p>The function first updates records and puts a <code>UUID</code> against them and then reads the records based on that <code>UUID</code> identifier, Now I cant Mock <code>UUID</code> obviously but when I run the following unit test the verify fails because the method <code>findAllByIdentifier</code> is actually called with a different <code>UUID</code> then I am passing in, because <code>updateAndSelect</code> creates a new <code>UUID</code> within itself</p>

<pre><code>        @Test
        public void testUpdateAndSelect(){
            UUID uuid = UUID.randomUUID();
            String identifier = uuid.toString();
            when(myMessageRespository.findAllByIdentifier(identifier)).thenReturn(myMessages);
            when(serviceUUID.randomUUID()).thenReturn(uuid);
            myMessageService.updateAndSelect();
            verify(myMessageRespository).findAllByIdentifier(identifier);

        }
</code></pre>
",https://stackoverflow.com/questions/53410539/spring-boot-unit-testing-a-function-using-uuid-in-local-scope,"['java', 'unit-testing', 'mockito']",930,FALSE,1,0
ag-grid unit testing in angular2- fixture.nativeElement.query is not a function,"<p>I wrote a test case by using Karma/Jasmine for ag-grid in angular. In my test case just checking the ag-grid headers and getting error like ""fixture.nativeElement.query is not a function"" but i am not confident enough whether this is a right approach or not which i have written. If any one having idea please help me. </p>

<p>This is my test case</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('to test the column headers',()=&gt;{
    fixture.nativeElement.query(By.css("".ag-fresh""))
    .map(function (header){
      return header.getText()
    }).then(function(headers){
      expect(headers).toEqual(['color','qty','price']);
    });
  });</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/52050317/ag-grid-unit-testing-in-angular2-fixture-nativeelement-query-is-not-a-function,"['angular', 'karma-jasmine', 'ag-grid']",2719,TRUE,1,2
Angular Unit Testing : How to unit test validation template driven form?,"<p>I have the component code as below :</p>

<pre><code>&lt;form name=""form"" (ngSubmit)=""f.form.valid &amp;&amp; login()"" #f=""ngForm"" novalidate&gt;
   &lt;div class=""form-group"" &gt;
      &lt;input type=""text"" class=""form-control"" name=""username"" [(ngModel)]=""model.username"" #username=""ngModel"" required /&gt;
      &lt;input type=""password"" class=""form-control"" name=""password"" [(ngModel)]=""model.password"" #password=""ngModel"" required /&gt;
   &lt;/div&gt;
   &lt;div class=""form-group""&gt;
      &lt;button type=""submit"" class=""btn btn-primary margin-top-10 no-shadow full-width""&gt;&lt;span class=""text-uppercase""&gt;{{ 'login' | translate }}&lt;/span&gt;&lt;/button&gt;
       &lt;/div&gt;
&lt;/form&gt; 
</code></pre>

<p>I tried the code below, but not working, always get failure result.</p>

<pre><code>it('test invalid', () =&gt; {
  const hostElement = fixture.nativeElement;
  const username: HTMLInputElement = hostElement.querySelector('input[name=""username""]');

  username.value = 'jhon';
  username.dispatchEvent(new Event('input[name=""username""]'));

  fixture.detectChanges();

  let form = component.f.form.controls;
  expect(form.username.invalid).toBe(false);

});
</code></pre>

<p>Is there any suggestion code for unit test?</p>
",https://stackoverflow.com/questions/49664111/angular-unit-testing-how-to-unit-test-validation-template-driven-form,"['javascript', 'angular', 'unit-testing']",1406,FALSE,1,0
Symfony Unit testing Service with mocks doesn&#39;t find the class name,"<p>I try to test on a pure unit test my Symfony Service (located in <code>src/AppBundle/Services/CapthaServiceAdapter</code>):</p>

<pre><code>namespace AppBundle\Services;

use AppBundle\Interfaces\CapthaBuilderInterface;
use Symfony\Component\HttpFoundation\Session\Session;
use Gregwar\Captcha\CaptchaBuilder;

/**
* The following class is an adapter for Gregwar Captcha Builder
* I do not set Gregwar's Captha Builder as a Service
* Because I want to stay hidden fromt he service container.
*/
class CapthaServiceAdapter implements CapthaBuilderInterface
{

  const IMAGE_INLINE=0;
  const IMAGE_NORMAL=1;

  /**
  * @var Session;
  */
  private $session=null;

  /**
  * @var CaptchaBuilder
  */
  private $capthaBuilder=null;

  public function __construct(Session $sessionManager)
  {
    $this-&gt;session=$sessionManager;
    $this-&gt;capthaBuilder=new CaptchaBuilder();
  }

  /**
  * @inheritdoc
  * @throws \InvalidArgumentException when type is not either self::IMAGE_INLINE or self::IMAGE_NORMAL
  */
  public function build($identifier,$type)
  {
    if($type!==self::IMAGE_INLINE || $type!==IMAGE_NORMAL){
      throw new \InvalidArgumentException(""Type should be either CapthaService::IMAGE_INLINE or CapthaService::IMAGE_NORMAL you provided the value: "".$type);
    }

    $this-&gt;builder-&gt;build();
    $this-&gt;session-&gt;set($sessionKey,$this-&gt;builder-&gt;getPhrase());

    if($type==self::IMAGE_INLINE){
      return $this-&gt;builder-&gt;inline();
    }

    return $this-&gt;builder-&gt;output();
  }

  /**
  * @inheritdoc
  */
  public function verify($identifier,$value)
  {
    $capthaSessionValue=$session-&gt;get($identifier);
    return $capthaSessionValue &amp;&amp; $value===$capthaSessionValue;
  }

}
</code></pre>

<p>So I did the following Test case (located in <code>tests/AppBundle/Services/CapthcaServiceTest.php</code>):</p>

<pre><code>namespace Tests\AppBundle\Services;

use PHPUnit\Framework\TestCase;
use AppBundle\Services\CapthaServiceAdapter;
use Symfony\Component\HttpFoundation\Session\Session;


class CapthcaServiceTest extends TestCase
{

  private function getServiceForBuild()
  {
    $mock=$this-&gt;createMock(Session::class);
    return new CapthaServiceAdapter($mock);
  }

  public function testBuildInline()
  {
    $service=$this-&gt;getServiceForBuild();
    $capthaValue=$service-&gt;build('somevalue',CapthaService::IMAGE_INLINE);

     $this-&gt;assertRegExp('/^data:image\/jpeg;base64,(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)$/i',$element);
  }
}
</code></pre>

<p>But when I try to run it I get the following error: </p>

<blockquote>
  <p>Error: Class 'AppBundle\Services\CapthaServiceAdapter' not found</p>
</blockquote>

<p>So how I can make my test to look for my class?</p>

<p>Also my <code>pgpunit.xml</code> contains the following content:</p>

<pre><code>&lt;?xml version=""1.0"" encoding=""UTF-8""?&gt;

&lt;!-- https://phpunit.de/manual/current/en/appendixes.configuration.html --&gt;
&lt;phpunit xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
         xsi:noNamespaceSchemaLocation=""http://schema.phpunit.de/4.8/phpunit.xsd""
         backupGlobals=""false""
         colors=""true""
         bootstrap=""vendor/autoload.php""
&gt;
    &lt;php&gt;
        &lt;ini name=""error_reporting"" value=""-1"" /&gt;
        &lt;server name=""KERNEL_CLASS"" value=""AppKernel"" /&gt;
    &lt;/php&gt;

    &lt;testsuites&gt;
        &lt;testsuite name=""Project Test Suite""&gt;
            &lt;directory&gt;tests&lt;/directory&gt;
            &lt;exclude&gt;./tests/Appbundle/Controller/DefaultControllerTest.php&lt;/exclude&gt;
        &lt;/testsuite&gt;
    &lt;/testsuites&gt;

    &lt;filter&gt;
        &lt;whitelist&gt;
            &lt;directory&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;/filter&gt;
&lt;/phpunit&gt;
</code></pre>

<h1>Edit 1</h1>

<p>By doing changes mentioned in the comments (updated the code above) I get the error:</p>

<blockquote>
  <p>Error: Class 'Tests\AppBundle\Services\CapthaService' not found</p>
</blockquote>

<p>Do you know how I can fix that?</p>

<h1>Edit 2:</h1>

<p>I also have seen this <a href=""https://stackoverflow.com/a/23398135/4706711"">answer</a> so I post my <code>composer.json</code> as well:</p>

<pre><code>{
    ""name"": ""pcmagas/ellakcy_member_app"",
    ""license"": ""AGPL-v3"",
    ""type"": ""project"",
    ""autoload"": {
        ""psr-4"": {
            ""AppBundle\\"": ""src/AppBundle""
        },
        ""classmap"": [
            ""app/AppKernel.php"",
            ""app/AppCache.php""
        ]
    },
    ""autoload-dev"": {
        ""psr-4"": {
            ""Tests\\"": ""tests/""
        },
        ""files"": [
            ""vendor/symfony/symfony/src/Symfony/Component/VarDumper/Resources/functions/dump.php""
        ]
    },
    ""require"": {
        ""php"": ""&gt;=5.5.9"",
        ""captcha-com/symfony-captcha-bundle"": ""4.*"",
        ""doctrine/doctrine-bundle"": ""^1.6"",
        ""doctrine/orm"": ""^2.5"",
        ""dunglas/angular-csrf-bundle"": ""^1.1"",
        ""gregwar/captcha"": ""^1.1"",
        ""sensio/distribution-bundle"": ""^5.0.19"",
        ""sensio/framework-extra-bundle"": ""^5.0.0"",
        ""symfony/dom-crawler"": ""^4.1"",
        ""symfony/monolog-bundle"": ""^3.1.0"",
        ""symfony/polyfill-apcu"": ""^1.0"",
        ""symfony/swiftmailer-bundle"": ""^2.6.4"",
        ""symfony/symfony"": ""3.4.*"",
        ""symfony/templating"": ""^3.4"",
        ""symfony/twig-bundle"": ""^4.1"",
        ""twig/twig"": ""^1.0||^2.0""
    },
    ""require-dev"": {
        ""doctrine/doctrine-fixtures-bundle"": ""^3.0"",
        ""felixfbecker/language-server"": ""^5.4"",
        ""jetbrains/phpstorm-stubs"": ""dev-master"",
        ""phpunit/phpunit"": ""^6.5"",
        ""sensio/generator-bundle"": ""^3.0"",
        ""symfony/phpunit-bridge"": ""^4.1""
    },
    ""scripts"": {
        ""symfony-scripts"": [
            ""Incenteev\\ParameterHandler\\ScriptHandler::buildParameters"",
            ""Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap"",
            ""Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache"",
            ""Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets"",
            ""Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile"",
            ""Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::prepareDeploymentTarget""
        ],
        ""post-install-cmd"": [
            ""@symfony-scripts""
        ],
        ""post-update-cmd"": [
            ""@symfony-scripts""
        ]
    },
    ""config"": {
        ""sort-packages"": true
    },
    ""extra"": {
        ""symfony-app-dir"": ""app"",
        ""symfony-bin-dir"": ""bin"",
        ""symfony-var-dir"": ""var"",
        ""symfony-web-dir"": ""web"",
        ""symfony-tests-dir"": ""tests"",
        ""symfony-assets-install"": ""relative"",
        ""branch-alias"": null
    }
}
</code></pre>

<p>As you can see it has the autoloading class as well:</p>

<pre><code>""autoload"": {
            ""psr-4"": {
                ""AppBundle\\"": ""src/AppBundle""
            },
            ""classmap"": [
                ""app/AppKernel.php"",
                ""app/AppCache.php""
            ]
        },
        ""autoload-dev"": {
            ""psr-4"": {
                ""Tests\\"": ""tests/""
            },
            ""files"": [
                ""vendor/symfony/symfony/src/Symfony/Component/VarDumper/Resources/functions/dump.php""
            ]
        },
</code></pre>

<p>Also By changing into this:</p>

<pre><code>""autoload"": {
        ""psr-4"": {
            ""AppBundle\\"": ""src/AppBundle"",
            ""AppBundle\\Services"":""src/AppBundle/Services"",
        },
        ""classmap"": [
            ""app/AppKernel.php"",
            ""app/AppCache.php""
        ]
    },
</code></pre>

<p>Results into this error:</p>

<blockquote>
  <p>Error: Class 'Tests\AppBundle\Services\CapthaService' not found</p>
</blockquote>

<p>Hos I can make the phphunit to look into the appropriate namespace?</p>
",https://stackoverflow.com/questions/52228165/symfony-unit-testing-service-with-mocks-doesnt-find-the-class-name,"['php', 'unit-testing', 'mocking', 'phpunit', 'symfony-3.4']",1333,TRUE,1,1
Unit testing if methods find and return a view in ASP.NET,"<p>I'm new to ASP.NET and I'm refactoring some functionalities in my MVC-structured ASP.NET application into area's. This has already lead to controller-methods not able to find their views anymore, which results in the following page:</p>

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

<p>To test if all controllers can find their views, I'd like to write some automated unit tests for this.</p>

<p>I have came up with the following:</p>

<pre><code>[TestMethod]
public void AboutTest()
{
    var controller = new HomeController();
    var result = controller.About() as ViewResult;
    Assert.IsNotNull(result);
}
</code></pre>

<p>which tests the About-method in the following code:</p>

<pre><code>public class HomeController : Controller
{
    public ActionResult About()
    {
        return View();
    }

    public ActionResult Contact()
    {
        return View(""~/Views/SomeFolder/Contact.cshtml"");
    }
}
</code></pre>

<p>But even when the HomeControllers About-method can not find a view, this assert succeeds, so this does not work for me.</p>

<p>I have found <a href=""https://stackoverflow.com/a/947086/5437768"">a solution online</a> to use use ViewEngine.FindView() here. I don't think I can use this, since in some controllers the views are referenced by a hardcoded string (see the contact method in the example controller above) instead of just returning the default view (simularly named as its method). The ViewEngine.FindView(controller.ControllerContext, ""about"", ""about""); will then fail, but the controller-method would not.</p>

<p><a href=""https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/unit-testing/creating-unit-tests-for-asp-net-mvc-applications-cs#testing-the-view-returned-by-a-controller"" rel=""nofollow noreferrer"">Another solution</a> states to use Assert.IsEqual() and check if the result.ViewName is equal to a hardcoded string (for example: ""About""). Since I do not set or know the title of the views I'm expecting to get returned, this would not be a solution either.</p>

<p>(How) would I be able to test my application for this?</p>
",https://stackoverflow.com/questions/50466446/unit-testing-if-methods-find-and-return-a-view-in-asp-net,"['asp.net', 'asp.net-mvc']",159,TRUE,1,1
How to write jasmine unit testing for configfactory function in angular2+,"<p><strong>Config service &amp; Factory service.ts file</strong></p>

<pre><code>import { Injectable, Injector } from '@angular/core';
import { AppConfig } from './app.config';
import { environment } from '../../environments/environment';
import { LOCATION_INITIALIZED } from '@angular/common';
import { HttpClient } from '@angular/common/http';


@Injectable()
export class ConfigService {
  public config: AppConfig;
  public constructor() {}
}

export function configFactory(http: HttpClient, injector: Injector, configSrv: ConfigService) {
  const configFileName = environment.configFilePath;
     return () =&gt; new Promise&lt;any&gt;((resolve: any) =&gt; {
       const locationInitialized = injector.get(LOCATION_INITIALIZED, Promise.resolve(null));
       locationInitialized.then(() =&gt; {
         http.get(configFileName).subscribe(res =&gt; {
         configSrv.config = &lt;AppConfig&gt;res;
           resolve(null);
         }, error =&gt; {
           console.error('INITIALIZATION:', error);
           resolve(null);
         });
       });
     });
 }
</code></pre>

<hr>

<p><strong>environment File</strong></p>

<pre><code>export const environment = {
  production: false,
  configFilePath: 'config/app.config.json',
};
</code></pre>

<p><strong>app.config.json</strong></p>

<pre><code>{    
    ""apiBaseUrl"": ""http://localhost:9999/api/""
}
</code></pre>

<p>while writing testcase facing error as 
ERRORS TypeError: Cannot read property '<strong>apiBaseUrl</strong>' of undefined​</p>

<p>How to write jasmine unit testcase for the above code?</p>

<p>Code Unittesting Code</p>

<pre><code>import { TestBed, inject, fakeAsync } from '@angular/core/testing';
import { ConfigService, configFactory } from './config.service';

import { Injector, APP_INITIALIZER } from '@angular/core';
import { MockBackend, MockConnection } from '@angular/http/testing';
import { BaseRequestOptions, ConnectionBackend, Http, HttpModule, Response, ResponseOptions, RequestOptions } from '@angular/http';
import { HttpClient } from '@angular/common/http';
//import { environment } from '../../environments/environment';

describe('ConfigService', () =&gt; {
  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      providers: [ConfigService]
    });
  });

  it('should be created', inject([ConfigService], (service: ConfigService) =&gt; {
    expect(service).toBeTruthy();
  }));
});
</code></pre>

<p>How to write unit testing for config factory function with mocking?</p>
",https://stackoverflow.com/questions/52042777/how-to-write-jasmine-unit-testing-for-configfactory-function-in-angular2,"['angular', 'jasmine']",456,FALSE,1,0
How to invoke AuthorizationFilterAttribute while unit testing in ASP.NET WEB API,"<p>I am testing my asp.net web api controller using Visual Studio Test project. </p>

<p>This is how my test case looks:</p>

<pre><code>[TestMethod]
public void TestMethod1()
{
    var controller = new MyController();
    //using json string for providing input
    var input = ""{some json object here}""

    var options = JsonConvert.DeserializeObject&lt;Employee&gt;(input);

    var response = controller.GetEmployee(options);

}
</code></pre>

<p>The above code is working fine. </p>

<p>I have a AuthorizationFilterAttribute. </p>

<pre><code>public class UserIdFilterAttribute : AuthorizationFilterAttribute
{
    public override void OnAuthorization(HttpActionContext filterContext)
    {
          //Logic to inject a userId to Controller
          ((Controllers.MyController) (filterContext.ControllerContext.Controller)).UserId = userId;
    }
}
</code></pre>

<p>This <code>OnAuthorization</code> function gets called every time when any endpoint (<code>GetEmployee</code> in this case) in my controller get invoked. But when I invoke endpoint in the controller using visual studio test framework, <code>OnAuthorization</code> function is not getting invoked. I am not using any external mocking framework.</p>

<p>What do i need to do to invoke <code>OnAuthorization()</code> automatically when I execute test case?</p>
",https://stackoverflow.com/questions/48433645/how-to-invoke-authorizationfilterattribute-while-unit-testing-in-asp-net-web-api,"['c#', 'unit-testing', 'asp.net-web-api']",753,TRUE,1,2
What&#39;s the best way to isolate a &#39;unit&#39; in unit testing?,"<p>For example, I'm developing a framework, consisting of 3 projects, which generate 3 dlls: A,B,C. Now I've got a feature that's implemented by method 1 in assembly A, which in turn calls method 2 in assembly B, which in turn calls method 3 in assembly C. And all of the 3 methods are public.</p>

<p>So in order to test this feature, do I need to write unit test code for all 3 methods? It may sound redundant in the first place, but all methods have their own logic, besides the invocation to the next method. And those logic also needs to be tested.</p>
",https://stackoverflow.com/questions/48476764/whats-the-best-way-to-isolate-a-unit-in-unit-testing,"['c#', 'unit-testing']",118,TRUE,1,1
"In unit testing, how to test a function having object parameters?","<p>When unit testing, do you have to send a full realistic object parameter? 
Or you just send an object parameter containing properties that are needed in the function?</p>

<p>For Example, here is a sample function that needs unit test:</p>

<pre><code>    function ChangeName(person) {
      if (person !== null) {
        let {firstName} = person.firstName;
        firstName = firstName + '_firstName';
        person.firstName = firstName;
        return person;
      }
      return person;
    }
</code></pre>

<p>Here is a sample test that sends a full object:</p>

<pre><code>    expect(
      ChangeName(
        {
          firstName: 'Juan', 
          lastName: 'dela Cruz', 
          age: 22, 
          gender: 'Male', 
          aboutMe: 'About_Me', 
          schools:[
            {id: 1, name: 'School Name 1'},
            {id: 1, name: 'School Name 1'},
            {id: 1, name: 'School Name 1'},
            {id: 1, name: 'School Name 1'}
          ]
        }
      )
    ).toEqual(
      {
        firstName: 'Juan_firstName', 
        lastName: 'dela Cruz', 
        age: 22, 
        gender: 'Male', 
        aboutMe: 'About_Me', 
        schools:[
          {id: 1, name: 'School Name 1'},
          {id: 1, name: 'School Name 1'},
          {id: 1, name: 'School Name 1'},
          {id: 1, name: 'School Name 1'}
        ]
      }
    );
</code></pre>

<p>Here is a sample test sends an object that has properties only needed in the function (includes the lastName, just for sample) :</p>

<pre><code>    expect(
      ChangeName(
        {
          firstName: 'Juan', 
          lastName: 'dela Cruz', 
        }
      )
    ).toEqual(
      {
        firstName: 'Juan_firstName', 
        lastName: 'dela Cruz', 
      }
    );
</code></pre>
",https://stackoverflow.com/questions/53665368/in-unit-testing-how-to-test-a-function-having-object-parameters,"['javascript', 'reactjs', 'unit-testing', 'testing', 'jestjs']",1018,TRUE,1,2
Unit testing verify object returned from a callback in anonymous class,"<p>I'm new to unit testing and I'm not sure how to approuch this case, so I would appreciate your input.</p>

<p>Relevant code:  </p>

<pre><code>public class Repository {

@Override
public void getUnifiedFoo(@NonNull final Foo foo1,
        @NonNull final GetUnifiedFooCallback getUnifiedFooCallback) {

    fooDataSource.getFoo2(foo1,new GetFoo2Callback() {

                @Override
                public void onGetFooSuccess(Foo foo2) {
                    UnifiedFoo unifiedFoo= createUnifiedFoo(foo1, foo2);
                    getUnifiedFooCallback.onGetSuccess(unifiedFoo);
                }

                @Override
                public void onGetMedicationCallbackFailure(Throwable t) {
                    getUnifiedFooCallback.onGetFailure(t);
                }
            });
      }
}

private createUnifiedFoo(Foo foo1, Foo foo2){

   return new UnifiedFoo(
              foo1.getMember1,
              foo1.getMember2,
              foo2.getMember3,
              foo2.getMember4,
      );
}
</code></pre>

<p>My questions are:</p>

<ol>
<li>Shoud 'createUnifiedFoo(Foo foo1, Foo foo2)' be package private and be tested separately?</li>
<li>In that context, if yes it sould, is there any point in testing that 1 methods (in this case fooDataSource.getFoo(...)) is called?</li>
<li>If it's acceptible to test 'createUnifiedFoo...' when getting called back in the anonymous class, how do I capture the callback so that when 'onGetFooSuccess(Foo foo2)' is called, I take foo1 stub, foo2 stub and assert equeal their fields to verfiy that they contain the correct values?</li>
</ol>

<p>Thank you.</p>
",https://stackoverflow.com/questions/48765117/unit-testing-verify-object-returned-from-a-callback-in-anonymous-class,"['java', 'unit-testing', 'callback', 'mocking', 'anonymous-class']",379,FALSE,1,1
Xcode 9.3 Swift Nested Custom Frameworks Unit testing and iTunesConnect uploading,"<p>I am getting tired of messing with build settings after a couple of days now...</p>

<p>I have an app, let's call it <code>MyiPhoneApp</code> that uses around 10 private/custom Frameworks (Cocoa Touch Dynamic Framework). <code>MyiPhoneApp</code> also uses Cocoapods for some dependencies (irrelevant?). My private Frameworks are themselves using themselves (being dependent on each other).</p>

<p>So my setup is (simplyfied here for readability):</p>

<h1>FRAMEWORKS (Private/Custom Cocoa Touch Dynamic):</h1>

<h2><code>Models</code></h2>

<p><strong>Targets:</strong> <code>ViewModels</code>, <code>ViewModelsTests</code><br>
<strong>Dependent on Private Frameworks</strong>: NONE</p>

<h2><code>ViewModels</code></h2>

<p><strong>Targets</strong>: <code>ViewModels</code>, <code>ViewModelsTests</code><br>
<strong>Dependent on Private Frameworks</strong>: <code>Models</code></p>

<h2><code>Views</code></h2>

<p><strong>Targets</strong>: <code>Views</code>, <code>Views</code><br>
<strong>Dependent on Private Frameworks</strong>: <code>Models</code>, <code>ViewModels</code></p>

<h1>APPS</h1>

<h2><code>MyiPhoneApp</code>:</h2>

<p><strong>Targets</strong>: <code>MyiPhoneApp</code>, <code>MyiPhoneAppTests</code>, <code>MyiPhoneAppUITests</code><br>
<strong><code>MyiPhoneApp</code> dependent on Private Frameworks</strong>: <code>Models</code>, <code>ViewModels</code>, <code>Views</code></p>

<h1>Catch 22 running Unit Tests &amp; upload to iTunesConnect</h1>

<p>With <code>ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES</code> for <strong>ALL</strong> targets I can run all unit tests in each private framework. <strong>But</strong> then I get rejection error from iTunes Connect:</p>

<blockquote>
  <p>[04:06:20]: [Transporter Error Output]: ERROR ITMS-90206: ""Invalid
  Bundle. The bundle at 'MyiPhoneApp.app/Frameworks/Models.framework'
  contains disallowed file 'Frameworks'."" [04:06:20]: [Transporter Error
  Output]: ERROR ITMS-90206: ""Invalid Bundle. The bundle at
  'MyiPhoneApp.app/Frameworks/ViewModels.framework' contains disallowed
  file 'Frameworks'."" [04:06:20]: [Transporter Error Output]: ERROR
  ITMS-90206: ""Invalid Bundle. The bundle at
  'MyiPhoneApp.app/Frameworks/Views.framework' contains disallowed file
  'Frameworks'.""</p>
</blockquote>

<p>This seems similar to: 
(SO Q958)[<a href=""https://stackoverflow.com/q/25777958/1311272]"">Validation Error: Invalid Bundle. The bundle at ... contains disallowed file &#39;Frameworks&#39;</a></p>

<p><a href=""https://stackoverflow.com/a/25789145/1311272"">The answer with over 240 upvotes</a> from Q958, suggets:
Setting <code>ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO</code> for Frameworks and Tests Targets (and Frameworks' Test Target..?) and <code>YES</code> for Apps. This is also suggested in <a href=""https://github.com/CocoaPods/CocoaPods/issues/6292#issuecomment-271002382"" rel=""nofollow noreferrer"">this Github comment</a></p>

<p>When trying that (<code>ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO</code> for frameworks and their test target) I cannot run my tests.</p>

<p>When I try to run <code>ModelTests</code> (Remember Framwork <code>Models</code> is not dependent on any other framework) the test fails/dies with:</p>

<blockquote>
  <p>dyld: Library not loaded: @rpath/libswiftCore.dylib   Referenced from:
  /Users/sajjon/Library/Developer/Xcode/DerivedData/Models-ahgxztzgogwcfheblqbzabdqxhtm/Build/Products/Debug-iphonesimulator/Models.framework/Models
  Reason: image not found</p>
</blockquote>

<h1>What is the proper setup?</h1>

<p>I have tried Xcode 9.3 and Xcode 9.4. My Frameworks and my App uses this xcconfig files:</p>

<h2>My System</h2>

<p>Macbook Pro 15"" late 2016
macOS High Sierra v 10.13.5 (17F77)</p>

<h3>Cocoapods 1.5.3 (bundler)</h3>

<p>Bundler version 1.16.1<br>
<code>bundle exec pod --version =&gt; 1.5.3</code></p>

<h2>My Podfile</h2>

<pre><code>source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '11.2'
inhibit_all_warnings!
use_frameworks!

workspace 'MyWorkspace.xcworkspace'

### PODS (sorted by name) ###

def nimble
  pod 'Nimble',  '~&gt; 7.1'
end

def rxswift           
  pod 'RxSwift', '~&gt; 4.1'
end

def viewcomposer      
  pod 'ViewComposer', :git =&gt; 'https://github.com/Sajjon/ViewComposer.git'
end

def quick
  pod 'Quick',  '~&gt; 1.3'
end

# Rest of pods removed for this StackOverFlow question for readability #

# Global Pod used by ___ALL___ targets
swiftlint

#@@ Apps (sorted by name) @@#

target 'MyiPhoneApp' do
  project 'Apps/MyiPhoneApp/MyiPhoneApp'


  # lots of pods removed for this SO question for readability
  rxswift
  tinyconstraints
  viewcomposer

  abstract_target 'Tests' do
    nimble
    quick

    target ""MyiPhoneAppTests""
    target ""MyiPhoneAppUITests""
  end
end


### PRIVATE FRAMEWORKS ###

abstract_target 'Framework-Models' do
  project 'Common/Models/Models'

  target 'Models' do
    # lots of pods removed for this SO question for readability
    rxswift
    swiftybeaver
  end

  target 'ModelsTests' do
    nimble
    quick
  end
end

abstract_target 'Framework-ViewModels' do
  project 'Common/ViewModels/ViewModels'

  target 'ViewModels' do
    # lots of pods removed for this SO question for readability
    rxswift
    viewcomposer
  end

  target 'ViewModelsTests' do
    nimble
    quick
  end
end

abstract_target 'Framework-Views' do
  project 'Common/Views/Views'

  target 'Views' do
    # lots of pods removed for this SO question for readability
    rxswift
    tinyconstraints
    viewcomposer
  end

  target 'ViewsTests' do
    nimble
    quick
  end
end
</code></pre>

<h2>My xcconfig files setup</h2>

<p>So as you can see in the Podfile above, my private Framework uses pods. But I want to use xcconfig files to share build settings between my frameworks (I only wrote three <code>ViewModels</code>, <code>Views</code>, <code>Models</code>, but in fact I have around 10.).</p>

<p>So I have investigated which xcconfig files that Xcode creates by default for Apps, for Cocoa Touch Dynamic Frameworks and how the settings for these differ between Test target and non Test target and between Debug and Release.</p>

<p>From that I have created these xcconfig files</p>

<h3><code>base_shared.xcconfig</code></h3>

<p><strong>includes configs:</strong> NONE<br>
<strong>Description</strong>: Used by ALL targets (App (Main, Test, UITest), Frameworks (Main, Test)).</p>

<h3><code>base_debug.xcconfig</code></h3>

<p><strong>includes configs:</strong> NONE<br>
<strong>Description</strong>: Used by ALL debug targets (App (Main, Test, UITest), Frameworks (Main, Test)).</p>

<h3><code>base_release.xcconfig</code></h3>

<p><strong>includes configs:</strong> NONE<br>
<strong>Description</strong>: Used by ALL release targets (App (Main, Test, UITest), Frameworks (Main, Test)).</p>

<h3><code>base_apps.xcconfig</code></h3>

<p><strong>includes configs:</strong> <code>base_shared</code><br>
<strong>Description</strong>: Used by apps targets (Main, Test, UITest)</p>

<h3><code>base_framework.xcconfig</code></h3>

<p><strong>includes configs:</strong> <code>base_shared</code><br>
<strong>Description</strong>: Used by Frameworks (Main, Test).</p>

<h3><code>base_tests.xcconfig</code></h3>

<p><strong>includes configs:</strong> <code>base_shared</code><br>
<strong>Description</strong>: Used by all Test Targets (App, Framework).</p>

<h3><code>base_uitests.xcconfig</code></h3>

<p><strong>includes configs:</strong> <code>base_shared</code><br>
<strong>Description</strong>: Used by all UITest Targets (App).</p>

<p>Then for each and app framework I include the correct combination of xcconfigs in a <code>Common</code> xcconfig. So e.g. for the Framework <code>Models</code> I create 6 config files: <code>Models-Common.xcconfig</code>, <code>Models-Debug.xcconfig</code>, <code>Models-Release.xcconfig</code>, ""ModelsTests-Common.xcconfig"", <code>ModelsTests-Debug.xcconfig</code>, <code>ModelsTests-Release.xcconfig</code>.</p>

<p>While that results in many xcconfig files, 6 for each framework, they are all tiny. And I can shared ALL build settings between all my 10+ Frameworks. It is a trade off.</p>

<h2>The contents of my xcconfig files</h2>

<p><code>base_shared.xcconfig</code>:</p>

<pre><code>// BuildSettings shared between both DEBUG and RELEASE and also identical for both FRAMEWORKS (Cocoa Touch Framework) and APPS (iOS)

// Vanilla Xcode 9.3 settings
ALWAYS_SEARCH_USER_PATHS = NO
CLANG_ANALYZER_NONNULL = YES
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE
CLANG_CXX_LANGUAGE_STANDARD = gnu++14
CLANG_CXX_LIBRARY = libc++
CLANG_ENABLE_MODULES = YES
CLANG_ENABLE_OBJC_ARC = YES
CLANG_ENABLE_OBJC_WEAK = YES
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES
CLANG_WARN_BOOL_CONVERSION = YES
CLANG_WARN_COMMA = YES
CLANG_WARN_CONSTANT_CONVERSION = YES
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR
CLANG_WARN_DOCUMENTATION_COMMENTS = YES
CLANG_WARN_EMPTY_BODY = YES
CLANG_WARN_ENUM_CONVERSION = YES
CLANG_WARN_INFINITE_RECURSION = YES
CLANG_WARN_INT_CONVERSION = YES
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES
CLANG_WARN_STRICT_PROTOTYPES = YES
CLANG_WARN_SUSPICIOUS_MOVE = YES
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE
CLANG_WARN_UNREACHABLE_CODE = YES
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES
COPY_PHASE_STRIP = NO
ENABLE_STRICT_OBJC_MSGSEND = YES
GCC_C_LANGUAGE_STANDARD = gnu11
GCC_NO_COMMON_BLOCKS = YES
SDKROOT = iphoneos
GCC_WARN_64_TO_32_BIT_CONVERSION = YES
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR
GCC_WARN_UNDECLARED_SELECTOR = YES
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE
GCC_WARN_UNUSED_FUNCTION = YES
GCC_WARN_UNUSED_VARIABLE = YES
IPHONEOS_DEPLOYMENT_TARGET = 11.2

// Custom set
CODE_SIGN_STYLE = Manual
SWIFT_VERSION = 4.1
DEVELOPMENT_TEAM = MYTEAMIDGOESHERE
ENABLE_BITCODE = NO
CODE_SIGN_ENTITLEMENTS =
CODE_SIGN_IDENTITY =
</code></pre>

<h2><code>base_debug.xcconfig</code>:</h2>

<pre><code>_DEBUG = DEBUG
GCC_PREPROCESSOR_DEFINITIONS = $(_DEBUG)
DEBUG_INFORMATION_FORMAT = dwarf
ENABLE_TESTABILITY = YES
GCC_DYNAMIC_NO_PIC = NO
GCC_OPTIMIZATION_LEVEL = 0
MTL_ENABLE_DEBUG_INFO = YES
ONLY_ACTIVE_ARCH = YES
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG
SWIFT_OPTIMIZATION_LEVEL = -Onone
SWIFT_ACTIVE_COMPILATION_CONDITIONS = $(inherited) $(_DEBUG)
</code></pre>

<h2><code>base_release.xcconfig</code>:</h2>

<pre><code>DEBUG_INFORMATION_FORMAT = dwarf-with-dsym
ENABLE_NS_ASSERTIONS = NO
MTL_ENABLE_DEBUG_INFO = NO
SWIFT_COMPILATION_MODE = wholemodule
SWIFT_OPTIMIZATION_LEVEL = -O
VALIDATE_PRODUCT = YES
</code></pre>

<h2><code>base_apps.xcconfig</code>:</h2>

<pre><code>#include ""base_shared.xcconfig""
// Apps have no specific BuildSettings that the FRAMEWORKS does not have as well. But in the future they might have, thus we have this file.

// These settings were in the TravelCompanion xcconfig
SWIFT_ACTIVE_COMPILATION_CONDITIONS[sdk=iphonesimulator*] = $(inherited) IOS_SIMULATOR
MTL_ENABLE_DEBUG_INFO = NO
SWIFT_OPTIMIZATION_LEVEL = -O
DEBUG_INFORMATION_FORMAT = dwarf-with-dsym
ENABLE_NS_ASSERTIONS = NO
VALIDATE_PRODUCT = YES
SUPPORTED_PLATFORMS = iphonesimulator iphoneos
VALID_ARCHS = arm64 armv7 armv7s
CLANG_MODULES_AUTOLINK = YES
GCC_OPTIMIZATION_LEVEL = s
CLANG_ENABLE_CODE_COVERAGE = NO
TARGETED_DEVICE_FAMILY = 1
CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES
VERSIONING_SYSTEM = apple_generic

// Custom
// The flag `ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES` should be set to `YES` for apps and `NO` for frameworks
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES
</code></pre>

<h2><code>base_framework.xcconfig</code>:</h2>

<pre><code>#include ""base_shared.xcconfig""

// BuildSettings specific for FRAMEWORKS (Cocoa Touch Framework)

// Vanilla BuildSettings
CURRENT_PROJECT_VERSION = 1
VERSIONING_SYSTEM = apple-generic
VERSION_INFO_PREFIX =

// Custom Set
PRODUCT_NAME = $(TARGET_NAME:c99extidentifier)
INSTALL_PATH = $(LOCAL_LIBRARY_DIR)/Frameworks
DYLIB_COMPATIBILITY_VERSION = 1
DYLIB_CURRENT_VERSION = 1
DEFINES_MODULE = YES
SKIP_INSTALL = YES


// The flag `ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES` should be set to `YES` for apps and `NO` for frameworks
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO

LD_RUNPATH_SEARCH_PATHS = $(inherited) @executable_path/Frameworks @loader_path/Frameworks
</code></pre>

<h2><code>base_tests.xcconfig</code>:</h2>

<pre><code>#include ""base_shared.xcconfig""

ONLY_ACTIVE_ARCH = YES

//Only used by APPS but it does not mess up build settings for test targets for FRAMEWORKS in Xcode 9.3 so will keep it here for now
BUNDLE_LOADER = $(TEST_HOST)
</code></pre>

<h2><code>base_uitests.xcconfig</code>:</h2>

<pre><code>#include ""base_shared.xcconfig""
TEST_TARGET_NAME = $(PRODUCT_NAME)
</code></pre>

<h2><code>Models-Common.xcconfig</code>:</h2>

<pre><code>#include ""../../../../Configurations/base_framework.xcconfig""

INFOPLIST_FILE = Source/SupportingFiles/Models-Info.plist
PRODUCT_BUNDLE_IDENTIFIER = com.sajjon.Models
</code></pre>

<h2><code>Models-Debug.xcconfig</code>:</h2>

<pre><code>#include ""Models-Common.xcconfig""
#include ""../../../../Configurations/base_debug.xcconfig""
#include ""../../Pods/Target Support Files/Pods-Framework-Models-Models/Pods-Framework-Models-Models.debug.xcconfig""
</code></pre>

<h2><code>Models-Release.xcconfig</code>:</h2>

<pre><code>#include ""Models-Common.xcconfig""
#include ""../../../../Configurations/base_release.xcconfig""
#include ""../../Pods/Target Support Files/Pods-Framework-Models-Models/Pods-Framework-Models-Models.release.xcconfig""
</code></pre>

<h2><code>ModelsTests-Common.xcconfig</code>:</h2>

<pre><code>#include ""../../../../Configurations/base_framework.xcconfig""
#include ""../../../../Configurations/base_tests.xcconfig""
INFOPLIST_FILE = Tests/SupportingFiles/ModelsTests-Info.plist
</code></pre>

<h2><code>ModelsTests-Debug.xcconfig</code>:</h2>

<pre><code>#include ""ModelsTests-Common.xcconfig""
#include ""../../../../Configurations/base_debug.xcconfig""
#include ""../../Pods/Target Support Files/Pods-Framework-Models-ModelsTests/Pods-Framework-Models-ModelsTests.debug.xcconfig""
</code></pre>

<h2><code>ModelsTests-Release.xcconfig</code>:</h2>

<pre><code>#include ""ModelsTests-Common.xcconfig""
#include ""../../../../Configurations/base_release.xcconfig""
#include ""../../Pods/Target Support Files/Pods-Framework-Models-ModelsTests/Pods-Framework-Models-ModelsTests.release.xcconfig""
</code></pre>

<h2><code>MyiPhoneApp-Commong.xcconfig</code>:</h2>

<pre><code>#include ""../../../../Configurations/base_apps.xcconfig""

_APP_NAME_PROD = My iPhone App
_BUNDLE_IDENTIFIER_PROD = com.sajjon.myiphoneaop
INFOPLIST_FILE = Source/SupportingFiles/MyiPhoneApp-Info.plist

DEVELOPMENT_TEAM = MYTEAMGOESHERE

PRODUCT_NAME = $(_APP_NAME_PROD)
ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage

CODE_SIGN_ENTITLEMENTS = Source/SupportingFiles/$(_APP_NAME_PROD).entitlements
SWIFT_OBJC_BRIDGING_HEADER = Source/SupportingFiles/MyiPhoneApp-Bridging-Header.h

PRODUCT_MODULE_NAME = TravelCompanion

// Overridden in Debug.xcconfig
CODE_SIGN_IDENTITY = iPhone Distribution

// Overridden in Release.xcconfig
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon-Alpha

ENABLE_TESTABILITY = YES
</code></pre>

<h2><code>MyiPhoneApp-Debug.xcconfig</code>:</h2>

<pre><code>#include ""MyiPhoneApp-Common.xcconfig""
#include ""../../../../Configurations/base_debug.xcconfig""
#include ""../../Pods/Target Support Files/Pods-MyiPhoneApp/Pods-MyiPhoneApp.debug.xcconfig""

_DEBUG = DEBUG
_CODE_SIGN_ID_DEBUG = iPhone Developer
_BUNDLE_IDENTIFIER_DEBUG = $(_BUNDLE_IDENTIFIER_PROD).dev
_PP_DEBUG = match Development $(_BUNDLE_IDENTIFIER_DEBUG)

CODE_SIGN_IDENTITY = $(_CODE_SIGN_ID_DEBUG)

PROVISIONING_PROFILE_SPECIFIER = $(_PP_DEBUG)
PRODUCT_BUNDLE_IDENTIFIER = $(_BUNDLE_IDENTIFIER_DEBUG)
APP_DISPLAY_NAME = MyiPhoneApp
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon-Debug
SWIFT_ACTIVE_COMPILATION_CONDITIONS = $(inherited) $(_DEBUG)
GCC_PREPROCESSOR_DEFINITIONS = $(_DEBUG)
GCC_OPTIMIZATION_LEVEL = 0
GCC_OPTIMIZATION_LEVEL = 0
MTL_ENABLE_DEBUG_INFO = YES
SWIFT_OPTIMIZATION_LEVEL = -Onone
GCC_DYNAMIC_NO_PIC = NO
ONLY_ACTIVE_ARCH = YES
ENABLE_NS_ASSERTIONS = YES
ENABLE_NS_ASSERTIONS[sdk=iphoneos*] = YES
VALIDATE_PRODUCT = NO
</code></pre>

<h2><code>MyiPhoneApp-Release.xcconfig</code>:</h2>

<pre><code>#include ""MyiPhoneApp-Common.xcconfig""
#include ""../../../../Configurations/base_release.xcconfig""
#include ""../../Pods/Target Support Files/Pods-MyiPhoneApp/Pods-MyiPhoneApp.release.xcconfig""

_PP_PROD = match AppStore $(_BUNDLE_IDENTIFIER_PROD)

PROVISIONING_PROFILE_SPECIFIER = $(_PP_PROD)
PRODUCT_BUNDLE_IDENTIFIER = $(_BUNDLE_IDENTIFIER_PROD)
APP_DISPLAY_NAME = $(_APP_NAME_PROD)
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon-Production
SWIFT_ACTIVE_COMPILATION_CONDITIONS = $(inherited) APP_STORE_BUILD
SWIFT_OPTIMIZATION_LEVEL = -Owholemodule
</code></pre>
",https://stackoverflow.com/questions/50746080/xcode-9-3-swift-nested-custom-frameworks-unit-testing-and-itunesconnect-uploadin,"['ios', 'swift', 'xcode', 'frameworks']",850,TRUE,1,1
How to set or test this.$parent in Vuejs unit testing?,"<p>In my component set <br></p>

<pre><code>data(){
categories: this.$parent.categories =&gt; which I set in main.js
}
</code></pre>

<p>Code file main.js </p>

<pre><code>import categories from '../config/categories';
new Vue({
    router,
    data: {
        categories: categories
}
});
</code></pre>

<p>I created 1 function unit test<br></p>

<pre><code>it(‘check component is a button’,() =&gt; {
const wrapper = shallow(FormSearch);
expect(wrapper.contains(‘button’)).toBe(true);
});
</code></pre>

<p>I run test then show error: Error in data(): ""TypeError: Cannot read property ‘categories’ of undefined""
How to fix it. Help me.</p>
",https://stackoverflow.com/questions/48638362/how-to-set-or-test-this-parent-in-vuejs-unit-testing,"['unit-testing', 'vue.js', 'vuejs2']",921,FALSE,1,4
What&#39;s the point of &quot;before&quot; hook in unit testing with Mocha?,"<p>Aren't these 2 identical?</p>

<pre><code>// ONE
describe('something', () =&gt; {
    const someConst = 'yes'

    it('should do something', () =&gt; {
        // doing something
    })

    it('should do something else', () =&gt; {
        // doing something else
    })

})

// TWO
describe('something', () =&gt; {
    let someNotConst
    before(() =&gt; {
       someNotConst = 'yes'
    })

    it('should do something', () =&gt; {
        // doing something
    })

    it('should do something else', () =&gt; {
        // doing something else
    })
})
</code></pre>

<p>This is a contrived example to demonstrate what I mean on a general level.</p>
",https://stackoverflow.com/questions/50136737/whats-the-point-of-before-hook-in-unit-testing-with-mocha,"['unit-testing', 'mocha.js']",19,TRUE,1,1
How to run dependent test alone when debugging or unit testing,"<p>I have the two methods in a class UserRegistrationTest as given below. When i run class, the two methods ran successfully(UserRegistrationTest first then followed by userLoginSuccess). But when i want to debug the test userLoginSuccess alone, it is triggering the the UserRegistrationTest also. This is expected because I have dependsonMethods configured. </p>

<p>I am trying to find a way to nullify the dependsonMethods, when i do unit testing/debugging. I followed the trails given in the below links, but i couldnt able to finalize the solution. </p>

<p><a href=""https://groups.google.com/forum/#!topic/testng-users/K9lwhXuSLZM"" rel=""nofollow noreferrer"">https://groups.google.com/forum/#!topic/testng-users/K9lwhXuSLZM</a>
<a href=""https://youtrack.jetbrains.com/issue/IDEA-141621"" rel=""nofollow noreferrer"">https://youtrack.jetbrains.com/issue/IDEA-141621</a></p>

<p>Please provide your thoughts.</p>

<p>Btw, I am able to nullify the dependsonMethods and dependsonGroups when i run as TestNg suite by giving the listner(IAnnotationTransformer). Also i am able to nullify by giving it in the pom.xml when running as maven test. But, when i run as TestNG Test, i am not able to set the dependsOnMethods to null programatically..</p>

<pre><code>public class UserRegistrationTest {

        @Test(groups = { ""userRegistration"" })
    public void registerUserSuccess(ITestContext context) {
    ...
        context.setAttribute(""user"", user);
    }

     @Test(dependsOnMethods = { ""userRegistration"" })
    public void userLoginSuccess(ITestContext context) {
        User user = (User) context.getAttribute(""user"");
    ...
    }
}
</code></pre>
",https://stackoverflow.com/questions/52501710/how-to-run-dependent-test-alone-when-debugging-or-unit-testing,['testng'],59,FALSE,1,1
Angular 6 unit testing detectChange throws error for component with @input,"<p>I have a simple component that is passed a config object as <code>@input</code> and uses it to set some values in <code>ngOnInit</code></p>

<pre><code>export class MyComponent implements OnInit {
    @input() config: ConfigObject;
    min: number;
    max: number;

    ngOnInit() {
        this.min = this.config.range.min;
        this.max = this.config.range.max;
    }
}
</code></pre>

<p>And I test it as follows:</p>

<pre><code>describe('MyComponent', () =&gt; {
    beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({...})
        .compileComponents();
    }));
    beforeEach(() =&gt; {
        fixture = TestBed.createComponent(MyComponent);
        component = fixture.componentInstance;
        component.config = &lt;ConfigObject&gt;mockConfig;
        fixture.detectChanges();
    })
})
</code></pre>

<p><code>detectChanges</code> here will throw an error <code>[object ErrorEvent] thrown</code>. 
If I call <code>ngOnInit</code> explicitly, I will receive <code>TypeError: Cannot read property 'min' of undefined</code>.
From <a href=""https://angular.io/guide/testing#component-with-inputs-and-outputs"" rel=""nofollow noreferrer"">Angular's testing guide</a> it seems like it should be possibly to set input explicitly on tested component, and then call <code>detectChanges</code> so I'm not sure why this isn't working.</p>

<p>In case you were wondering - the <code>mockConfig</code> object is a copy of the object passed to the component when code is run, and the component does not error in this case.</p>
",https://stackoverflow.com/questions/51520758/angular-6-unit-testing-detectchange-throws-error-for-component-with-input,"['angular', 'unit-testing']",1909,FALSE,1,1
Angular 5 unit testing object in template causes [object ErrorEvent] thrown,"<p>I'm getting an error running Jasmine tests in Angular 5. It seems to be linked to the object bindings in the template file. If I have a binding 3 levels deep I get the following error</p>

<pre><code>[object ErrorEvent] thrown
</code></pre>

<p>The error goes away when I change the template from</p>

<pre><code>&lt;p class=""item__auth-name""&gt;{{shot.user.name}}&lt;/p&gt;
</code></pre>

<p>to</p>

<pre><code>&lt;p class=""item__auth-name""&gt;{{shot.user}}&lt;/p&gt;
</code></pre>

<p>Here is my component</p>

<pre><code>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { IShot } from '../../shared/models';

@Component({
  selector: 'app-details',
  templateUrl: './details.component.html',
  styleUrls: ['./details.component.scss']
})
export class DetailsComponent implements OnInit {

  public shot: IShot;

  constructor(
    private route: ActivatedRoute
  ) { }

  ngOnInit() {
    this.shot = this.route.snapshot.data['shot'];
  }

}
</code></pre>

<p>And here is my spec file</p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { SafePipe } from '../../core/pipes/safe.pipe';
import { DetailsComponent } from './details.component';
import { ActivatedRoute } from '@angular/router';

describe('DetailsComponent', () =&gt; {
  let component: DetailsComponent;
  let fixture: ComponentFixture&lt;DetailsComponent&gt;;
  let dataFromActivatedRoute = {
    id: 1
  };

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ DetailsComponent, SafePipe ]
    })
    .overrideComponent(DetailsComponent, {
      set: {
        providers: [
          {provide: ActivatedRoute, useValue: {
             snapshot: {
              data: {
                shot: dataFromActivatedRoute
              }
            }
          }}
        ]
      }})
    .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(DetailsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
      });

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });

});
</code></pre>

<p>Removing the fixture.detectChanges() in the spec file also removes the error but that's not fixing the problem. Does anyone have experience with this kind of behavior?</p>
",https://stackoverflow.com/questions/48371171/angular-5-unit-testing-object-in-template-causes-object-errorevent-thrown,"['angular', 'jasmine', 'angular5']",1824,FALSE,1,0
Less than 100% branch coverage unit testing. How to fix that?,"<p>I have a memoized recursive function to calculate fibonacci numbers. I have test cases for this function. Basically it sends in a position and if there already is a number at that position, just return it and if there is not, calculate it. I ran my code through the debugger and realised that:</p>

<pre><code>if (dictionary[position] != null){
    result = dictionary[position];
  }
</code></pre>

<p>is never hit. The full code below. For example, if you have calculatefib(4), that will ask for <code>fib(3)</code> which will ask for <code>fib(2)</code> which will ask for <code>fib(1)</code> which will ask for <code>fib(0)</code> and when the stack starts to close up, the values are never saved. so for example <code>fib(2)</code> or rather <code>dictionary(2)</code> is always null. Its confusing cause in the debugger it shows the values are calculated but when the stack starts to close up, they are null again. How do i refactor the code so the lines are always hit. </p>

<pre><code>public BigInteger calculateFib(int position) {

final BigInteger[] dictionary = new BigInteger[100000];

BigInteger result = BigInteger.ONE;

if (position &lt; 2) {
  return result;
}
else {
  if (dictionary[position] != null){
    result = dictionary[position];
  }
  else {
    result = calculateFib(position - 1).add(calculateFib(position - 2));
    dictionary[position] = result;
  }
  return result
</code></pre>
",https://stackoverflow.com/questions/52999068/less-than-100-branch-coverage-unit-testing-how-to-fix-that,"['java', 'fibonacci']",1388,FALSE,1,4
How to do unit testing for Http delete in angular 6?,"<p>I want to write unit test for deleting record from grid.</p>

<p>Below is delete.component.ts file where deleteRecord method is shown</p>

<pre><code>deleteRecord(id: string): void {
const result = confirm(""Are you sure you want to delete record?"");
if (result) {
  this.deleteService.deleteRecord(id).subscribe(() =&gt; {
    const index = this.gridDetails.findIndex
      ((i) =&gt; i.id === id);
    this.gridDetails.splice(index, 1);
    alert(""Deleted successfully"");
  }, (error: ErrorResponse) =&gt; {
    alert(""Delete failed"");
  });
}}
</code></pre>

<p>Below is delete.service.ts file</p>

<pre><code>deleteRecord(id: string): Observable&lt;void&gt; {
return this.http.delete&lt;void&gt;('http:/xyz/server/api/blogs/' + id);}
</code></pre>

<p>Below is delete.component.spec.ts file</p>

<pre><code>it('should delete record from grid on click of ok', () =&gt; {
spyOn(component, 'deleteRecord').and.callThrough();
spyOn(window, 'confirm').and.returnValue(true);
component.deleteRecord(mockDeleteService.id);
expect(component.deleteRecord).toHaveBeenCalled();
});

it('should not delete Record from grid on click of cancel', () =&gt; {
spyOn(component, 'deleteRecord').and.callThrough();
spyOn(window, 'confirm').and.returnValue(false);
expect(component.deleteRecord).not.toHaveBeenCalled();
});
</code></pre>

<p>Please help me in writing/improving unit tests for the above code</p>
",https://stackoverflow.com/questions/52727459/how-to-do-unit-testing-for-http-delete-in-angular-6,"['angular', 'karma-jasmine']",2652,FALSE,1,0
Kotlin Coroutine Unit Testing Error: Exception in thread &quot;main @coroutine#1 @coroutine#2&quot; java.lang.NullPointerException,"<p>I'm trying to unit test a presenter that I made with Kotlin coroutines, and this is also my first time using Mockito</p>

<p>Whenever I try to run the unit test I'm getting the following error the first time it tries to do anything with my view while in the coroutine</p>

<pre><code>Exception in thread ""main @coroutine#1 @coroutine#2"" java.lang.NullPointerException
    at .signin.SignInPresenter$subscribe$1.doResume(SignInPresenter.kt:45)
    at kotlin.coroutines.experimental.jvm.internal.CoroutineImpl.resume(CoroutineImpl.kt:54)
    at kotlinx.coroutines.experimental.DispatchedKt.resumeCancellable(Dispatched.kt:208)
    at kotlinx.coroutines.experimental.intrinsics.CancellableKt.startCoroutineCancellable(Cancellable.kt:35)
    at kotlinx.coroutines.experimental.CoroutineStart.invoke(CoroutineStart.kt:111)
    at kotlinx.coroutines.experimental.AbstractCoroutine.start(AbstractCoroutine.kt:161)
    at kotlinx.coroutines.experimental.BuildersKt.launch(Builders.kt:68)
    at kotlinx.coroutines.experimental.BuildersKt.launch$default(Builders.kt:61)
    at .signin.SignInPresenter.subscribe(SignInPresenter.kt:42)
</code></pre>

<p>This is the relevant part of my presenter, the line referenced in the error is <code>view.showSigninPanel</code></p>

<pre><code>class SignInPresenter(
    private val view: SignInContract.View,
    private val userRepo: ParseAuthController,
    private val contextPool: CoroutineContextProvider
) : SignInContract.Presenter {

    private val coroutineJobs: MutableList&lt;Job&gt; = mutableListOf()

    override fun subscribe() {
        view.loadBackgroundImage()
        view.setUpSignInPanel()
        view.setUpKeyboardListener()

        coroutineJobs.add(launch(contextPool.Main) {
            if (!userRepo.isAuthenticated()) {
                view.showSignInPanel()
                subscribeToLoginValidation()
                subscribeToPaswordEmailValidation()
            } else {
                view.launchMainActivity()
            }
        })
    }
</code></pre>

<p>The call to <code>userRepo.isAuthenticated()</code> is a suspended call</p>

<p>I'm passing in a test coroutine context into my presenter as per this article </p>

<p><a href=""https://android.jlelse.eu/mastering-coroutines-android-unit-tests-8bc0d082bf15"" rel=""noreferrer"">https://android.jlelse.eu/mastering-coroutines-android-unit-tests-8bc0d082bf15</a></p>

<pre><code>class TestContextProvider : CoroutineContextProvider() {
    override val Main: CoroutineContext = Unconfined
    override val IO: CoroutineContext = Unconfined
}
</code></pre>

<p>This is my unit test currently</p>

<pre><code>class SignInPresenterTest {

    private lateinit var view: SignInContract.View
    private lateinit var presenter: SignInPresenter
    private lateinit var parseAuthController: ParseAuthController

    @Before
    fun setUp() {
        view = mock(SignInContract.View::class.java)

        parseAuthController = mock(ParseAuthController::class.java)

        presenter = SignInPresenter(
            view,
            parseAuthController,
            TestContextProvider()
        )
    }

    @After
    fun tearDown() {
        presenter.dispose()
    }

    @Test
    fun subscribeNotAuthenticatedShowSignInPanel() {
        runBlocking {
            val expectedResult = false
            `when`(parseAuthController.isAuthenticated()).thenReturn(expectedResult)

            presenter.subscribe()
        }

        verify(view).showSignInPanel()
    }
}
</code></pre>

<p>UPDATE: I've been doing some additional tests, and it looks like if I remove the suspend call within my presenter <code>if (!userRepo.isAuthenticated())</code> it won't crash and I can verify if something has run with Mockito, but this isn't an actual solution... but something with that suspending call is causing problems?</p>
",https://stackoverflow.com/questions/50184175/kotlin-coroutine-unit-testing-error-exception-in-thread-main-coroutine1-cor,"['android', 'unit-testing', 'kotlin', 'mockito', 'kotlinx.coroutines']",8874,TRUE,18,1
Unit Testing - Inner class receives null when accessing outer class fields,"<p>I'm writing unit tests for a class with an inner class. When I try to access variables belonging to the outer class from inside the inner class, they resolve to be null. However, this is only when running the unit tests.</p>

<pre><code>class Outer {
    private final SomeClass foo;

    Outer(SomeClass foo) {
        this.foo = foo;
    }

    // + some static methods used by other tests

    class Inner {
        void doSomething() {
            assertNotNull(foo);
        }
    }
}
</code></pre>

<p>It doesn't matter whether <code>Someclass</code> is a mock or not (could be a basic <code>String</code>), the problem still occurs.</p>

<pre><code>@RunWith(RobolectricTestRunner.class)
@PowerMockIgnore({ ""org.mockito.*"", ""org.robolectric.*"", ""android.*"" })
@PrepareForTest(Outer.class)
public class OuterTest {

    Outer outer;
    SomeClass someClassMock;

    @Rule
    public PowerMockRule rule = new PowerMockRule();

    @Before
    public void setUp() {
        PowerMockito.mockStatic(Outer.class);
        someClassMock = Mockito.mock(SomeClass.class);
        // + setup someClassMock
        outer = new Outer(someClassMock);
    }


    @Test
    public void testInner() throws Exception {
        outer.new Inner().doSomething();
    }
}
</code></pre>

<p><strong>EDIT</strong> I've narrowed it down to the use of <code>PowerMock.mockStatic(..)</code>. Even though the <code>Inner</code> class is non-static, PowerMock/Mockito seem to treat it as such and handle requests to the <code>Outer</code> class as static.</p>
",https://stackoverflow.com/questions/48507231/unit-testing-inner-class-receives-null-when-accessing-outer-class-fields,"['java', 'unit-testing', 'mockito', 'robolectric', 'powermockito']",385,FALSE,1,0
Some of your tests did a full page reload - Unit Testing,"<p>I'm relatively new to unit tests so forgive me. But I'm getting the following error and have been looking around for a solution but can't really understand the examples I've seen. 
Error: </p>

<blockquote>
  <p>Some of your tests did a full page reload!</p>
</blockquote>

<p>This is my test causing the issue.</p>

<pre><code>it('should download test results', () =&gt; {
    expect(scope.downloading).toBeFalsy();
    httpBackend
      .expectGET('http://1.2.3.4/dowloads')
      .respond(mockedProductTest);
    controller.DownloadResults();
    expect(scope.downloading).toBeTruthy();
    httpBackend.flush();
    expect(scope.downloading).toBeFalsy();
});
</code></pre>

<p>This is my function.</p>

<pre><code>this.$scope.downloading = true;
    this.$http.get(
        `${this.$config.serverAddress}downloads}`
    )
    .then(response =&gt; {
        this.$scope.downloading = false;
        //Next Line is the one causing issues.
        this.$window.location.href = `${this.$config.serverAddress}download/TestResultszipFullPath=${response.data}`;
    },
</code></pre>
",https://stackoverflow.com/questions/50257528/some-of-your-tests-did-a-full-page-reload-unit-testing,"['javascript', 'angularjs', 'unit-testing']",3992,FALSE,1,0
Mockito Kotlin Unit Testing Method called verification throws Null Pointer Exception,"<p>I am getting <code>Null Pointer Exception</code> whenever I try to verify method is called or not. </p>

<pre><code>class NotesDialogPagePresenterTest {

@Mock
private lateinit var repository: OrderSummaryRepository
@Mock
private lateinit var view: NotesDialogPageContract.View
@Mock
private lateinit var context: Context

private lateinit var presenter: NotesDialogPagePresenter
private val notes = ""abcd""
private val remarks = ""xyz""


@Before
fun setup() {
    MockitoAnnotations.initMocks(this)
    whenever(view.getContext()).thenReturn(context)
    this.presenter = NotesDialogPagePresenter(view, repository)
}

@Test
fun onCompleteCallClicked_successTest() {

    whenever(repository.updateOrderAfterCompleteCall(notes, remarks)).thenReturn(Completable.complete())

    val spyPresenter = Mockito.spy(presenter)
    spyPresenter.onCompleteCallClicked(notes, remarks)

    verify(view, times(1)).showOnCompleteCallSuccess()
    verify(spyPresenter, times(1)).updateUser()//Null Pointer Exception Here
}
</code></pre>

<p>}</p>

<p>Presenter Class</p>

<pre><code> class NotesDialogPagePresenter @Inject constructor(var view: NotesDialogPageContract.View,
                                               var repository: OrderSummaryRepository)
: NotesDialogPageContract.Presenter {

private var disposable: Disposable? = null

override fun start() {
}

override fun onCompleteCallClicked(notes: String, remarks: String) {

    disposable = repository.updateOrderAfterCompleteCall(notes, remarks)
            .subscribe({
                view.showOnCompleteCallSuccess()
                updateUser() 
            }, {
                view.showError(it)
            })
}

@VisibleForTesting
internal fun updateUser() {
    disposable = repository.updateUser(-1)
            .subscribe({
                //NO-OP
            }, {
                //NO-OP
            })
}

override fun stop() {
    disposable?.dispose()
}
</code></pre>

<p>}</p>

<p>These two methods need to be verified and updateUser() throws Null 
   Pointer Exception</p>

<p><code>view.showOnCompleteCallSuccess()
 updateUser()
</code></p>

<p>Logcat:</p>

<pre><code>java.lang.NullPointerException
    at com.rosia.bcp.ordersummary.notes.NotesDialogPagePresenter.updateUser$app_pgDebug(NotesDialogPagePresenter.kt:30)
    at com.rosia.bcp.ordersummary.notes.NotesDialogPagePresenter$onCompleteCallClicked$1.run(NotesDialogPagePresenter.kt:22)
    at io.reactivex.internal.observers.CallbackCompletableObserver.onComplete(CallbackCompletableObserver.java:54)
    at io.reactivex.internal.disposables.EmptyDisposable.complete(EmptyDisposable.java:68)
    at io.reactivex.internal.operators.completable.CompletableEmpty.subscribeActual(CompletableEmpty.java:27)
    at io.reactivex.Completable.subscribe(Completable.java:1794)
    at io.reactivex.Completable.subscribe(Completable.java:1860)
    at com.rosia.bcp.ordersummary.notes.NotesDialogPagePresenter.onCompleteCallClicked(NotesDialogPagePresenter.kt:20)
    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.rosia.bcp.ordersummary.notes.NotesDialogPagePresenter.onCompleteCallClicked(NotesDialogPagePresenter.kt:19)
    at com.rosia.bcp.ordersummary.notes.NotesDialogPagePresenterTest.onCompleteCallClicked_successTest(NotesDialogPagePresenterTest.kt:42)
    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.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 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)
    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.AppMainV2.main(AppMainV2.java:131)
Exception in thread ""main"" java.lang.NullPointerException
    at com.rosia.bcp.ordersummary.notes.NotesDialogPagePresenter.updateUser$app_pgDebug(NotesDialogPagePresenter.kt:30)
    at com.rosia.bcp.ordersummary.notes.NotesDialogPagePresenter$onCompleteCallClicked$1.run(NotesDialogPagePresenter.kt:22)
    at io.reactivex.internal.observers.CallbackCompletableObserver.onComplete(CallbackCompletableObserver.java:54)
    at io.reactivex.internal.disposables.EmptyDisposable.complete(EmptyDisposable.java:68)
    at io.reactivex.internal.operators.completable.CompletableEmpty.subscribeActual(CompletableEmpty.java:27)
    at io.reactivex.Completable.subscribe(Completable.java:1794)
    at io.reactivex.Completable.subscribe(Completable.java:1860)
    at com.rosia.bcp.ordersummary.notes.NotesDialogPagePresenter.onCompleteCallClicked(NotesDialogPagePresenter.kt:20)
    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.rosia.bcp.ordersummary.notes.NotesDialogPagePresenter.onCompleteCallClicked(NotesDialogPagePresenter.kt:19)
    at com.rosia.bcp.ordersummary.notes.NotesDialogPagePresenterTest.onCompleteCallClicked_successTest(NotesDialogPagePresenterTest.kt:42)
    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.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 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)
    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.AppMainV2.main(AppMainV2.java:131)
</code></pre>

<p>FYI: I am using following Dependencies:</p>

<pre><code>testImplementation 'org.mockito:mockito-core:2.19.0'
testImplementation 'com.squareup.retrofit2:retrofit-mock:2.3.0'
testImplementation 'org.mockito:mockito-inline:2.8.9'
testImplementation 'com.nhaarman:mockito-kotlin-kt1.1:1.6.0'
testImplementation 'junit:junit:4.12'
</code></pre>
",https://stackoverflow.com/questions/52273867/mockito-kotlin-unit-testing-method-called-verification-throws-null-pointer-excep,"['android', 'unit-testing', 'kotlin', 'nullpointerexception', 'mockito']",5068,TRUE,1,4
How to Pass @Value to a @Component for Spring Unit Testing,"<p>Im writing unit tests for services, controllers, etc however theres is a @Component that has the following values</p>

<pre><code>@Component
Public class myclass
   @Autowired
   Private MyTemplate myTemplate

   @Value(""$someString"")
   Private String someString

   @PostConstruct
   Public void loadString()
      ...
</code></pre>

<p>How would I manually load values into the @Values? I have tried with Mocks, TestPropertySource, ReflectionTestUtils, among other ways found around</p>
",https://stackoverflow.com/questions/52838228/how-to-pass-value-to-a-component-for-spring-unit-testing,"['spring', 'eclipse', 'testing']",5395,TRUE,1,2
Unit testing for Angular service method with imported third party dependancy,"<p>I have an Angular service which imports a third party dependancy.  I call the dependancy to give me the browser fingerprint which is then stored in the service.</p>

<p>I am not sure how to mock this dependency in the test so I can assert it has been called and mock a return value.</p>

<p>This is the service:</p>

<pre><code>import { Inject, Injectable } from '@angular/core';
import * as Fingerprint2 from 'fingerprintjs2';

@Injectable()
export class ClientInfoService {
    public fingerprint: string | null = null;

    constructor() {
    }

    createFingerprint(): any {
        return new Fingerprint2();
    }

    setFingerprint(): void {
        let fprint = this.createFingerprint();
        setTimeout(() =&gt; fprint.get(hash =&gt; this.fingerprint = hash), 500);
    }

    getFingerprint(): string | null {
        return this.fingerprint;
    }

}
</code></pre>

<p>This is the current test code:</p>

<pre><code>import { TestBed } from '@angular/core/testing';
import { ClientInfoService } from './client-info.service';

describe('Client Info Service', () =&gt; {
    const hash = 'a6e5b498951af7c3033d0c7580ec5fc6';
    let service: ClientInfoService;

    beforeEach(() =&gt; {
        TestBed.configureTestingModule({
            providers: [ClientInfoService],
        });
        service = TestBed.get(ClientInfoService);
    });

    test('should be defined', () =&gt; {
        expect(service).toBeDefined();
    });


    describe('get the fingerprint', () =&gt; {

        test('it should be null', () =&gt; {
            let fprint = service.getFingerprint();
            expect(fprint).toBeNull();
        });

        test('it should be the hash value', () =&gt; {
            service.fingerprint = hash;
            let fprint = service.getFingerprint();
            expect(fprint).toEqual(hash);
        });

    test('it should get the hash value after setting', () =&gt; {
        jest.useFakeTimers();
        service.createFingerprint = jest.fn().mockReturnValue(() =&gt; {
            return {
                get: function (cb) {
                    return cb(hash);
                }
            };
        });
        spyOn(service, 'createFingerprint');
        service.setFingerprint();
        jest.runAllTimers();
        expect(service.createFingerprint).toHaveBeenCalled();
        expect(service.fingerprint).toEqual(hash);
    });

    });

});
</code></pre>
",https://stackoverflow.com/questions/52836002/unit-testing-for-angular-service-method-with-imported-third-party-dependancy,"['angular', 'unit-testing', 'jestjs', 'angular-services']",522,TRUE,1,2
iOS on device Unit Testing fails to start - HealthKit entitlements error,"<p>Whenever I try to run the unit tests on device. Everything seems to build and install onto the device but I get the following error in a dialog when it is about to run:</p>

<blockquote>
  <p>The executable was signed with invalid entitlements. The entitlements specified in your application’s Code Signing Entitlements file are invalid, not permitted, or do not match those specified in your provisioning profile. (0xE8008016).</p>
</blockquote>

<p>Unit testing on simulator works fine. However I would like to get unit tests to work on the device, because it will work a bit faster.</p>

<p>My project has the following warning:</p>

<blockquote>
  <p>Provisioning profile ""match Development com.example.app"" for ""Example"" contains entitlements that aren't in the entitlements file: com.apple.developer.healthkit.access. To use these entitlements, add them to your entitlements file. Otherwise, remove unused entitlements from your provisioning profile.</p>
</blockquote>

<p>But everything else works, I can run the target and publish it to appstore. Only unit testing on device fails to start. I looked inside the development provisioning profile and found it contains the <code>com.apple.developer.healthkit.access</code> key which is not in the appstore provisioning profile. But when I add this key to the entitlements file, it still does not run the unit tests.</p>

<p>I have tried deleting the entitlements file and letting Xcode regenerate it, but that does not work. My project has 5 different app targets each with their own unit testing bundle.</p>

<p>I have also tried regenerating the development provisioning profile, but it always has a <code>com.apple.developer.healthkit.access</code> key in it.</p>

<p>I looked in the project file as suggested <a href=""https://stackoverflow.com/questions/33071726/missing-healthkit-entitlement"" title=""Answer"">here</a>. All I found was that all the app targets were using the same entitlements file. So I changed it so that all the apps use their own entitlements, but unit testing still fails to start. And the <code>com.apple.developer.healthkit.access</code> warning stays there</p>

<p>Is there a way I can get unit testing on device to work with healthkit turned on? Unit testing on device without HealthKit will also be an improvement, but then everything else should also work (distribution etc...)</p>
",https://stackoverflow.com/questions/52253833/ios-on-device-unit-testing-fails-to-start-healthkit-entitlements-error,"['ios', 'xcode', 'unit-testing', 'healthkit']",822,TRUE,1,2
ReferenceError : AngularJS is not defined on Karma with Jasmine unit testing,"<p>I'm actually stuck since few hours, my boss wants me to proceed to unit testing on the functionalities i coded last week, when I do my karma start <code>karma.conf.js</code> it gives me the following issue :</p>

<p><code>""message"": ""An error was thrown in afterAll\nUncaught ReferenceError: angular is not defined"",</code></p>

<p>my files structure :</p>

<pre><code>webapp
    -www
        -services
            api.service.js
    -test
        test.test.js
    karma.conf.js
</code></pre>

<p>essential of karma.conf.js :</p>

<pre><code>module.exports = function(config) {
  config.set({
  files: [
    'www/js/services/api.service.js',
    'test/**/*.test.js'
  ],
})
}
</code></pre>

<p>I think Karma doesn't find my api.service.js but i don't know why, the angularjs code actually work in the webapp.</p>

<p>content of my test.test.js : </p>

<pre><code>(function() {
'use strict';

   describe('apiService', function() {

     it('should return an array of object', function() {
     var artist = typeof getArtist(118680); // MGMT Artist
     console.log(artist);
     expect(artist).toEqual('array');
     });
   });
})();
</code></pre>

<p>getArtist is the function I need to test situated in api.service.js.</p>

<p>Thank you, </p>

<p>Paul.</p>
",https://stackoverflow.com/questions/49728167/referenceerror-angularjs-is-not-defined-on-karma-with-jasmine-unit-testing,"['angularjs', 'unit-testing', 'karma-jasmine']",1317,TRUE,1,1
How to run a unit testing particular component in angular 4,"<p>Is there any way to run a unit test only for a particular component in the angular 4 project?</p>
",https://stackoverflow.com/questions/50677691/how-to-run-a-unit-testing-particular-component-in-angular-4,"['angular', 'unit-testing']",1537,TRUE,1,3
How can i created unit testing to Graphql application with Laravel?,"<p>I created an application with Laravel using Graphql. But I dont how to create my unit tests. Only do it simple request with PHPUnit or have other better way to do it?</p>

<p>Example Query Graphql in Laravel:</p>

<pre><code>class ClientQuery extends Query
{
    protected $attributes = [
        'name' =&gt; 'ClientQuery',
        'description' =&gt; 'A query'
    ];

    public function type()
    {
       return GraphQL::type(""Client"");
    }

    public function args()
    {
       return [
            'id' =&gt; [
                 'type' =&gt; Type::nonNull(Type::int()),
            ],
       ];
    }

    public function resolve($root, $args, $context, ResolveInfo $info)
    {
      return Client::find($args['id']);
    }
}
</code></pre>
",https://stackoverflow.com/questions/50540932/how-can-i-created-unit-testing-to-graphql-application-with-laravel,"['php', 'laravel', 'unit-testing', 'phpunit', 'graphql']",742,FALSE,1,1
"Unit Testing in Angular 5 with Component, Data Source and Service","<p>I am like a born baby for writing Angular Test cases but trying to learn and I am using Sonar Scanner for checking code coverage. </p>

<p>Am sharing my code, please go have a look:</p>

<pre><code>`// test.component.ts 

dataSource: TestDataSource;
..
// method I am trying to test 

loadDataPage() {
      if (this.code === undefined || this.code === 'Test') {
        this.pageNo = this.paginator.pageIndex + 1;
        this.dataSource.loadDatas(
          this.paginator.pageIndex,
          this.paginator.pageSize,
          this.sort.active,
          this.sort.direction,
          this.input.nativeElement.value,
          this.locationSelectedValue,
          this.testticketSelectedValue,
          this.teststatusSelectedValue,
          this.styleOptionSelectedValue
        );
    } else {
      this.getUserByName(this.Name);
    }
  }

...
</code></pre>

<p>Below is Datasource file: </p>

<pre><code>// testDatasource.ts

export class TestDataSource implements DataSource&lt;any&gt; {

..
 loadDatas(pageIndex: number, pageSize: number, sortLabel: string,
        sortDirection: string, search: any, location: string[],
        testticketCount: string[], teststatus: string[], styleOption: string[]) {
        this.loadingSubject.next(true);
        this.testService.getData(pageIndex, pageSize, sortLabel,
            sortDirection, search, location,
             ticketCount, status, styleOption).pipe(catchError(() =&gt; of([])), finalize(() =&gt; this.loadingSubject.next(false)))
            .subscribe(responses =&gt; {
                this.countValue = responses['count'];
                this.dataSubject.next(responses['response']);
            });
    }

..
</code></pre>

<p>Below is service file: </p>

<pre><code>//test.service.ts
export class TestService {
getData(
        pageNumber, pageSize, sortLabel, sortDirection, search,
        location, ticketCount, status, styleOption): Observable&lt;any[]&gt; {
        const object = {
            pageNumber: pageNumber,
            pageSize: pageSize,
            sortLabel: sortLabel,
            sortDirection: sortDirection,
            search: search,
            location: location,
            ticketCount: ticketCount,
            status: status,
            styleOption: styleOption
        };

        return this.apiService.post(this.config.api_url +
            '/testOrder/getall', object).pipe(
                map(res =&gt; res)
            );
    }
</code></pre>

<p>The above there file is my code which I need to test using Karma and Jasmine</p>

<p>The way I tried to test the method am sharing: </p>

<pre><code>// test.component.spec.ts

it('should call and run #loaddata()', () =&gt; {
    spyOn(comp, 'loadDataPage');
    comp.testcode = 'TEST';
    comp.paginator.pageIndex = 0;
    comp.paginator.pageSize = 25;
    comp.sort.active = null;
    comp.sort.direction = 'desc';
    comp.input.nativeElement.value = null;
    comp.locationSelectedValue = [];
    comp.testticketSelectedValue = [];
    comp.teststatusSelectedValue = [];
    comp.styleOptionSelectedValue = [];

      if (!expect(comp.companycode).toEqual('TEST')) {
        expect(comp.paginator.pageIndex + 1).toBe(1);
        expect(comp.dataSource.loadDatas).toHaveBeenCalledWith(
          comp.paginator.pageIndex,
          comp.paginator.pageSize,
          comp.sort.active,
          comp.sort.direction,
          comp.input.nativeElement.value,
          comp.locationSelectedValue,
          comp.testticketSelectedValue,
          comp.teststatusSelectedValue,
          comp.styleOptionSelectedValue);
    } else {
      expect(comp.paginator.pageIndex + 1).toBe(1);
    }
  });
</code></pre>
",https://stackoverflow.com/questions/53381688/unit-testing-in-angular-5-with-component-data-source-and-service,"['angular', 'jasmine', 'angular5', 'karma-jasmine', 'karma-coverage']",2042,FALSE,0,0
Spring Boot MockMVC Unit Testing | application/xml;charset=ISO-8859-1,"<p>I'm testing an endpoint and the response content-type is ""application/xml;charset=ISO-8859-1"", when I expect it to be ""application/xml"".  Can you see where I may have misconfigured the produces aspect?  I added it to the @RequestMapping for the function and received the same, unexpected, result.</p>

<h2>Feature Under Test</h2>

<pre><code>@Controller
@RequestMapping(value = ""/sitemaps"",
    consumes = MediaType.ALL_VALUE,
    produces = MediaType.APPLICATION_XML_VALUE)
public class SitemapQueryControllerImpl implements SitemapQueryController {

    @RequestMapping(value = ""/index.xml"", method = RequestMethod.GET)
    public ResponseEntity&lt;String&gt; GetSitemapIndex() {
        return new ResponseEntity&lt;&gt;(""&lt;Hello&gt;"", HttpStatus.OK);
    }

}
</code></pre>

<h2>Test</h2>

<pre><code>@RunWith(SpringRunner.class)
@WebMvcTest(controllers = SitemapQueryControllerImpl.class, secure = false)
@ContextConfiguration(classes = {ApplicationTestContext.class})
public class SitemapQueryController_Spec {

    @Autowired
    private MockMvc mockMvc;


    @Before
    public void setup() { }


    @Test
    public void GetSitemapIndex_Successul() throws Exception {

        String expect = ""&lt;Hello&gt;"";
        mockMvc.perform(get(""/sitemaps/index.xml"")
                .contentType(MediaType.APPLICATION_XML_VALUE))
                    .andExpect(status().isOk())
                    .andExpect(content().contentType(MediaType.APPLICATION_XML_VALUE))
                    .andExpect(content().xml(expect));
}
</code></pre>
",https://stackoverflow.com/questions/53819150/spring-boot-mockmvc-unit-testing-application-xmlcharset-iso-8859-1,"['unit-testing', 'spring-mvc', 'spring-boot']",1958,TRUE,0,2
C++ Ensuring We Call a Mocked System Call for Unit Testing,"<p>When trying to wrap a system call in C++, such as lseek, the compiled code would call the actual system call instead of my mock.</p>

<p>Here's an example:</p>

<pre><code>/* Mock the file operation lseek. */
off_t lseek(int fd, off_t offset, int whence)
{
    printf(""%s \n"", __PRETTY_FUNCTION__);
}
</code></pre>

<p>How to get the compiler to call my mocked system call rather than the one in unistd.h?</p>

<p>I tried using the -Wl,--wrap=lseek flag, but this failed as the linker could not find the __wrap_lseek symbol.</p>

<p><a href=""https://stackoverflow.com/questions/13961774/gnu-gcc-ld-wrapping-a-call-to-symbol-with-caller-and-callee-defined-in-the-sam"">GNU gcc/ld - wrapping a call to symbol with caller and callee defined in the same object file</a></p>
",https://stackoverflow.com/questions/49440235/c-ensuring-we-call-a-mocked-system-call-for-unit-testing,"['linux', 'unit-testing', 'mocking', 'g++', 'system-calls']",197,FALSE,0,1
unit testing using enzyme: Pass react props as event to wrapper,"<p>My test fail because I don't know what to declare in the <code>onChange</code> value,</p>

<pre><code>describe(""App"", function() {
  const wrapper = shallow(&lt;App /&gt;);

  it(""should have an input"", function() {
    expect(
      wrapper.contains(&lt;input type=""text"" onChange={null} /&gt;)
    ).toBeTruthy();
  });
});
</code></pre>

<p>I just have this in my component</p>

<pre><code>&lt;input type=""text"" onChange={this.changeInput} /&gt;
</code></pre>
",https://stackoverflow.com/questions/53744175/unit-testing-using-enzyme-pass-react-props-as-event-to-wrapper,"['reactjs', 'jestjs', 'enzyme']",210,TRUE,0,3
How is measure() testing normally use for in performance unit testing?,"<p>I found boilerplate of Unit Test file has performance test. I tried to put a function inside but it doesn't seems like it works in that way. My question is:</p>

<ol>
<li><p>Why we need this performance test and when its useful to use?</p></li>
<li><p>How is the best practice of doing performance test?</p>

<p>func testPerformanceExample() {
    self.measure {
    }
}</p></li>
</ol>
",https://stackoverflow.com/questions/48298451/how-is-measure-testing-normally-use-for-in-performance-unit-testing,"['swift', 'xcode', 'unit-testing', 'cocoa', 'performance-testing']",676,TRUE,0,1
Get fixture and component values on describe call - Angular unit testing,"<p>I am writing unit tests for web application which contains too many forms. So, for code optimization I am creating <strong>one common function which will return function</strong>. That function tests all the supplied form fields(ReactiveFroms approach) whether they are required or not.</p>

<p>Function that tests whether fields are required or not.</p>

<p><strong>common-function.spec.ts:</strong> </p>

<pre><code>export const componentTestFn = (formGroup: any, fields: Fields[], configurationOptions?) =&gt; () =&gt; {

describe('On required fields', () =&gt; {

    beforeEach(() =&gt; {

        if (configurationOptions) {
            TestBed.configureTestingModule(configurationOptions)
                .compileComponents();
        }

    });


    fields.forEach(element =&gt; {

        describe(element.name, () =&gt; {
            it('should be a required field', () =&gt; {

                let control = formGroup.get(element.formControlName);
                if (element.nestedControl) {
                    control = control.get(element.nestedControl);
                }
                control.patchValue('');
                expect(control.hasError('required')).toBeTruthy();
                control.patchValue('Test');
                expect(control.hasError('required')).toBeFalsy();
            });
        });

    });

});

}
</code></pre>

<p>And I am calling this function from main spec file with describe clause.</p>

<p><strong>main.component.spec.ts:</strong></p>

<pre><code>describe('Given a Physical Property Setup Component', () =&gt; {

     let component: PhysicalPropertySetupComponent;
     let fixture: ComponentFixture&lt;PhysicalPropertySetupComponent&gt;;
     let fields: Fields[] = [
           new Fields('','field1','',''),
           new Fields('','field2','',''),
           new Fields('','field3','',''),
           new Fields('','field4','','')
     ];

     beforeEach(() =&gt; {
           TestBed.configureTestingModule({
                 ....
           });
           fixture = TestBed.createComponent(PhysicalPropertySetupComponent);
           component = fixture.componentInstance;
     });
     describe('Testing',common.componentTestFn(component.formGroup,fields));
});
</code></pre>

<p><strong>But it is giving me error ""TypeError: Cannot read property 'formGroup' of undefined"".</strong> </p>

<p>I think it is because we can only use component and fixture value inside <code>it</code> clause. But i'm not using it because my <code>componentTestFn</code> will replace it. Similarly when i call this function inside <code>it</code> it works fine.</p>

<p>Can anybody tell me how can i get that <code>formGroup</code> value on describe? Any Help will be appreciated.</p>

<p><strong>Thanks in advance!!</strong> </p>
",https://stackoverflow.com/questions/50406196/get-fixture-and-component-values-on-describe-call-angular-unit-testing,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",350,FALSE,0,1
Is possible to finish unit testing when a method is called?,"<p>Here is my test method where It should be success if <em>showLoading()</em> and <em>loadDataSuccess(response)</em> was called:</p>

<pre><code> @RunWith(PowerMockRunner.class)
     public class PresenterTest {
            @Mock  
            private ProfileContract.View view;
            @Mock
            private ProfileContract.Handler handler;

            @Test
            public void onLoadDataClicked() {
              presenter.loadData();
              verify(mView, times(1)).showLoading();
              verify(mHandler, times(1)).loadDataSuccess();
            }
     }
</code></pre>

<p><strong>UPDATE 1</strong>
Here is my presenter:</p>

<pre><code>class ProfilePresenter(private val mView: ProfileContract.View) : ProfileContract.Handler {

     override fun loadData() {
            mView.showLoading()
            mUserService.user()
                    .compose(RxUtil.mapper())
                    .subscribe({ response -&gt;
                        loadDataSuccess()
                    }, { error -&gt;
                        //stuff
                    })
        }
}
</code></pre>

<p>Thanks!</p>
",https://stackoverflow.com/questions/50582926/is-possible-to-finish-unit-testing-when-a-method-is-called,"['unit-testing', 'kotlin', 'mvp']",184,FALSE,0,2
Unit Testing protected methods using Mocks and sub classes in C#,"<p>I am trying to unit test a few protected methods which are in a public class.
I am inheriting from this class and testing the inherited class by returning the super class' methods from it.
My sample code is as follows:</p>

<p>Base Class:</p>

<pre><code>public class A
{
    // Private variables here
    public A(){ }

    protected virtual bool MethodOfA()
    {
        bool returnValue = false;
        //some operation here to set returnValue
        return returnValue;
    }

    protected bool AnotherMethodOfA()
    {
        bool anotherReturnValue = false;
        bool operationCheck = MethodOfA();

        if(operationCheck)
        {
            //do something to set the value of anotherReturnValue
        }

        return anotherReturnValue;
    }
}
</code></pre>

<p>Inherited Class:</p>

<pre><code>public class B : A
{
    // Private variables here
    public B():base() { }

    public new bool MethodOfA()
    {
        return base.MethodOfA();
    }

    public new bool AnotherMethodOfA()
    {
        var testMock = new Mock&lt;A&gt;();

        //This is the part where I'm not sure how to get it to work.
        testMock.CallBase = true; // I have tried it with and without this statement. couldn't get it to work
        testMock.Protected()
                .Setup&lt;bool&gt;(""MethodOfA"")
                .Returns(true);

        return base.AnotherMethodOfA();
    }
}
</code></pre>

<p>Tests:</p>

<pre><code>public class TestB
{
    private readonly B _sut

    //some Mocks here for setup

    public TestB()
    {
        _sut = new B();
    }


    [Fact]
    public void AnotherMethodOfA_Test()
    {
        var result = _sut.AnotherMethodOfA();
        Assert.True(result);
    }
}
</code></pre>

<p>What i need is basically, when I run my test from the TestB class, and it hits '_sut.AnotherMethodOfA()', within that method where it needs to call 'MethodOfA()', it should just use the value that I provide in the Mock and move on with the execution instead of calling the actual method (which it is doing now).</p>

<p>Now, if my Method-Under-Test were simpler and not call another method within it, this whole thing would have been simple (Which is the case in many of my other methods and I am testing those successfully already), but since this method calls another method during it's execution, i need to mock this intermediate method and pass that to my Method-under-test.</p>
",https://stackoverflow.com/questions/53641725/unit-testing-protected-methods-using-mocks-and-sub-classes-in-c,"['c#', 'unit-testing', 'mocking', 'moq', 'access-modifiers']",1318,FALSE,0,1
Unable to inject dependency ngComboDatePicker while doing AngularJS app unit testing,"<p><strong>Angular module defined as follow:</strong></p>

<pre><code>angular.module('app', ['ngComboDatePicker']);
</code></pre>

<p><strong>Controller file:</strong></p>

<pre><code>angular.module('app')

.controller('pricebreakdown', [""$scope"", ""$rootScope"", ""$stateParams"", ""$log"", ""$q"",

    function($scope, $rootScope, $stateParams, $log, $q) {
        $scope.coolVariable = ""pricebreakdown-view"";
        $scope.coolMethod = function(){
            $log.log(""This is a sample method"");
        };
    }
]);
</code></pre>

<p><strong>Spec file:</strong></p>

<pre><code>describe('Unit: pricebreakdown', function() {

    beforeEach(module('app'));

    var ctrl, scope, rootScope, stateParams, log, q;

    beforeEach(inject(function($controller, $rootScope) {
        scope = $rootScope.$new();
        ctrl = $controller('pricebreakdown', {
            $scope: scope,
            $rootScope: rootScope,
            $stateParams: stateParams,
            $log: log,
            $q: q
        });

    }));

    it('this is the sample test', function() {
        expect($scope.coolVariable).toBe('pricebreakdown-view');
    });
})
</code></pre>

<p><strong>Config file looks like this:</strong></p>

<pre><code>files: [  'bower_components/angular/angular.js',

          'bower_components/angular-mocks/angular-mocks.js',
          'bower_components/angular-ui-router/release/angular-ui-router.min.js',
          'bower_components/jquery/dist/jquery.min.js',
          'bower_components/angular-bootstrap/ui-bootstrap.min.js',
          //'src/**/*.js',
          //'src/**/*.html',
          //'test/**/*.js',
          'src/app/app.js',
          'src/app/booking/payment-confirm/price-breakdown/pricebreakdown.controller.js',
          'test/app/booking/paymentconfirm/pricebreakdown/pricebreakdown.spec.js'
        ],
</code></pre>

<p><strong>Error from CMD is:</strong></p>

<pre><code>Error: [$injector:modulerr] Failed to instantiate module budget.app due to:
        Error: [$injector:modulerr] Failed to instantiate module ngComboDatePicker due to:
        Error: [$injector:nomod] Module 'ngComboDatePicker' 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.

Chrome 63.0.3239 (Windows 10 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.044 secs / 0.017 secs).
</code></pre>

<p>Help me with this? How to inject these dependency??</p>
",https://stackoverflow.com/questions/48298721/unable-to-inject-dependency-ngcombodatepicker-while-doing-angularjs-app-unit-tes,"['angularjs', 'jasmine', 'karma-jasmine']",32,FALSE,0,0
Unit testing Retrofit calls when service is injected with Dagger 2,"<p>I use Dagger 2 to provide all my classes in Android app. I want to unit test my repository class which has Retrofit service in the constructor.</p>

<pre><code>class MainRepository(private val service: ImageService) {

fun download(username: String, liveData: MutableLiveData&lt;ImageDownloadResult&gt;) {
    service.downloadImage(username).enqueue(object : Callback&lt;ImageResponse&gt; {
        override fun onFailure(call: Call&lt;ImageResponse&gt;, t: Throwable) {
            liveData.value = DownloadFailed(t)
        }

        override fun onResponse(call: Call&lt;ImageResponse&gt;, response: Response&lt;ImageResponse&gt;) {
            if (response.isSuccessful) {
                response.body()?.let {
                    liveData.value = DownloadSuccessful(it.image)
                }
            } else {
                liveData.value = DownloadFailed(
                    when (response.code()) {
                        401 -&gt; Unauthorized()
                        403 -&gt; Forbidden()
                        404 -&gt; NotFound()
                        in 500..599 -&gt; InternalServerError()
                        else -&gt; General()
                    }
                )
            }
        }
    })
}
</code></pre>

<p>}</p>

<p>Network module class provides the service in this way:</p>

<pre><code>@Provides
@Singleton
fun provideImageService(gson: Gson, okHttpClient: OkHttpClient): ImageService {
    return Retrofit.Builder()
        .addConverterFactory(GsonConverterFactory.create(gson))
        .baseUrl(mBaseUrl)
        .client(okHttpClient)
        .build()
        .create(ImageService::class.java)
}
</code></pre>

<p>I am trying to use Mockito to mock the classes, but I get NullPointerException in the <code>download</code> method.</p>

<pre><code>public class MainRepositoryTest {

@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
@InjectMocks
ImageService service;

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
}

@Test
public void testImageDownload() {
    MutableLiveData&lt;ImageDownloadResult&gt; liveData = new MutableLiveData&lt;&gt;();
    Response&lt;ImageResponse&gt; response = null;
    try {
        response = service.downloadImage(""test"").execute();
        assertEquals(response.code(), 200);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
</code></pre>

<p>}</p>

<p>Please educate me how to inject service into the test so that I can call Http calls there. Thank you!</p>
",https://stackoverflow.com/questions/52805825/unit-testing-retrofit-calls-when-service-is-injected-with-dagger-2,"['android', 'unit-testing', 'mockito', 'retrofit2']",1666,TRUE,0,1
How to mock function for unit testing in serverless-mocha-plugin,"<p>I am using aws lambda function and nodejs I am trying to test following function.</p>

<pre><code>module.exports.handler = (event, context, callback) =&gt; {

var host = environment.set_environment(env);

if (event.body[0].value) {
var cid= event.body[1].customerID;
var loginResponse = loginMethods.login(host,cid);

loginResponse.then(function (loginResult) {
  if (loginResult.hash) {
    console.log(""login success"");
    var Response = requestMethod.callAPI(event.body, loginResult.hash);
    Response .then(function (Result) {
      console.log('successfulll');



    }, function (error) {
      console.log('failure response');

    })
  } else {
    console.log(""login response with no token"");

  }
}, function (error) {
  console.log('login failure response');

})

} else {
  callback(null, responseMethods.error('Invalid request'));
}

};
</code></pre>

<p>When i am calling this function for unit testing, I want to mock the other function which is being called inside this function</p>

<p>For example in this line</p>

<pre><code>var loginResponse = loginMethods.login(host,cid);
</code></pre>

<p>In unit test i don't want to call real function i just want to call a mocked function for unit testing 
I am from UI background to achieve same thing i.e to mock a function in unit testing in angular we can easily do while importing.</p>

<p>I there a way to mock function in nodejs</p>
",https://stackoverflow.com/questions/50565402/how-to-mock-function-for-unit-testing-in-serverless-mocha-plugin,"['node.js', 'unit-testing', 'aws-lambda', 'mocha.js', 'aws-serverless']",949,TRUE,1,1
Unit Testing a Django Form with a ImageField without external file,"<p>django version: 1.11, python version: 3.6.3</p>

<p>I found this stackoverflow question:</p>

<p><a href=""https://stackoverflow.com/questions/2473392/unit-testing-a-django-form-with-a-filefield"">Unit Testing a Django Form with a FileField</a></p>

<p>and I like how there isn't an actual image/external file used for the unittest; however I tried these approaches:</p>

<pre><code>from django.test import TestCase
from io import BytesIO
from PIL import Image
from my_app.forms import MyForm
from django.core.files.uploadedfile import InMemoryUploadedFile

class MyModelTest(TestCase):                    
    def test_valid_form_data(self):                    
        im_io = BytesIO() # BytesIO has to be used, StrinIO isn't working         
        im = Image.new(mode='RGB', size=(200, 200))         
        im.save(im_io, 'JPEG')                                  
        form_data = {
                'some_field': 'some_data'
            }                                               
        image_data = {   
                InMemoryUploadedFile(im_io, None, 'random.jpg', 'image/jpeg', len(im_io.getvalue()), None) 
            }    
        form = MyForm(data=form_data, files=image_data)             
        self.assertTrue(form.is_valid()) 
</code></pre>

<p>however, this always results in the following error message:</p>

<pre><code>Traceback (most recent call last):
  File ""/home/my_user/projects/my_app/products/tests/test_forms.py"", line 44, in test_valid_form_data
    self.assertTrue(form.is_valid())
  File ""/home/my_user/.virtualenvs/forum/lib/python3.6/site-packages/django/forms/forms.py"", line 183, in is_valid
    return self.is_bound and not self.errors
  File ""/home/my_user/.virtualenvs/forum/lib/python3.6/site-packages/django/forms/forms.py"", line 175, in errors
    self.full_clean()
  File ""/home/my_user/.virtualenvs/forum/lib/python3.6/site-packages/django/forms/forms.py"", line 384, in full_clean
    self._clean_fields()
  File ""/home/my_user/.virtualenvs/forum/lib/python3.6/site-packages/django/forms/forms.py"", line 396, in _clean_fields
    value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
  File ""/home/my_user/.virtualenvs/forum/lib/python3.6/site-packages/django/forms/widgets.py"", line 423, in value_from_datadict
    upload = super(ClearableFileInput, self).value_from_datadict(data, files, name)
  File ""/home/my_user/.virtualenvs/forum/lib/python3.6/site-packages/django/forms/widgets.py"", line 367, in value_from_datadict
    return files.get(name)
AttributeError: 'set' object has no attribute 'get'
</code></pre>

<p>Why? I understand that <code>.get()</code> is a dictionary method, but I fail to see where it created a set. </p>
",https://stackoverflow.com/questions/48075739/unit-testing-a-django-form-with-a-imagefield-without-external-file,"['python', 'django', 'unit-testing']",1427,TRUE,1,2
Scala Pattern match the result of a method during unit testing,"<p>I am unit testing a scala method which returns a string of the following form </p>

<blockquote>
  <p>SELECT col1 FROM tableName WHERE ts &lt;= 1533499389</p>
</blockquote>

<p>The integer value is epoch and would change on every execution. I was wondering if there is a way in Scala to just match the pattern to assert the value returned</p>

<p>Pattern can be something like :</p>

<blockquote>
  <p>SELECT col1 FROM tableName WHERE ts &lt;= {}</p>
</blockquote>
",https://stackoverflow.com/questions/51697926/scala-pattern-match-the-result-of-a-method-during-unit-testing,"['scala', 'unit-testing']",282,TRUE,0,1
Visual Studio 2010 Unit Testing: Referenced Project Class Not Being Recognized,"<p>I am trying to make a basic unit test for a very basic C++ class in Visual Studio 2010. I have already tested the class and everything works. However, when I make a Test Project, I can't get the class to be recognized.</p>

<p>My class header file:</p>

<pre><code>#include &lt;string&gt;
#include &lt;iostream&gt;
using namespace std;
#ifndef FIRST_H
#define FIRST_H
class First
{
private:
string name;
int age;
public:
// Constructors
First(); // default constructor
First(string n, int a); // constructor with parameters

void ChangeAge(int newAge);
void ChangeName(string newName);

void getName();
void getAge();
};
#endif
</code></pre>

<p>My Class cpp file:</p>

<pre><code>#include ""First.h""

// Constructors
First :: First()// default constructor
{
    name = ""No Name"";
    age = 0;
}
First :: First(string n, int a) // constructor with parameters
{
    name = n;
    age = a;
}
//Manipulators
void First :: ChangeAge(int newAge)
{
    age = newAge;
}
void First :: ChangeName(string newName)
{
    name = newName;
}
// Observers
void First :: getName()
{
    cout &lt;&lt; ""The name of this student is "" &lt;&lt; name &lt;&lt; endl;
    //cin &gt;&gt; name;
}
void First :: getAge()
{
    cout &lt;&lt; ""The age of this student is "" &lt;&lt; age &lt;&lt; endl;
}
</code></pre>

<p>Here is my Basic Unit Test:   // Note: All of this is autogenerated, except for the body of void TestMethod1()</p>

<pre><code>#include ""stdafx.h""

using namespace System;
using namespace System::Text;
using namespace System::Collections::Generic;
using namespace Microsoft::VisualStudio::TestTools::UnitTesting;

    namespace TestProject5
    {
        [TestClass]
        public ref class UnitTest1
        {
        public: 
        [TestMethod]
        void TestMethod1()
        {
            First person;    // Sets Age to 0
            person.getAge(); // Should Display 0
        }
    };
}
</code></pre>

<p>When building the unit Test project, I am getting an error saying:
 ""First is an undeclared identifier"".</p>

<p>If I change the ""public ref class"" value from ""UnitTest1"" to my class name ""First"", I get the following error:
""'getAge' is not a member of 'TestProject5::First'""</p>
",https://stackoverflow.com/questions/51026939/visual-studio-2010-unit-testing-referenced-project-class-not-being-recognized,"['c++', 'unit-testing', 'visual-studio-2010']",45,FALSE,-2,2
"Unit testing http methods (get, post) in react / javascript using intern","<p>This is my first time writing unit tests - please be nice. </p>

<p>I am trying to write unit tests for two functions. one function is to <code>GET</code> a number from the api, and the other is to <code>POST</code> data. </p>

<p>I am not sure how to do this. I know, I want to use the intern ""expect"" call and fetch-mock but the rest I want to do in <code>react / javascript</code>. I made a mock response with some data. </p>

<p>My questions are: </p>

<ol>
<li>How can I use fetch-mock to compare my expected output with what my function is outputting</li>
<li>How does my mock response data relate to fetch-mock? </li>
</ol>

<p>Again, I have not done this before and i am having a hard time understanding the resources available online (have been researching this for 8+ hours) so i am looking for another opinion</p>
",https://stackoverflow.com/questions/49578065/unit-testing-http-methods-get-post-in-react-javascript-using-intern,"['javascript', 'reactjs', 'unit-testing', 'http', 'intern']",738,TRUE,0,1
Cookies are not available in Class library while doing unit testing,"<p>I am doing unit testing for my mvc application. It includes many class library. I have mocked the http context in unit testing project using NSubstitute and created the cookie. But it is not available in class library while debug the source. How can we get cookies in class library?  </p>

<p><strong>Unit Test</strong> </p>

<pre><code>        [Test]
        [TestModule(ModuleAttribute.ModuleName)]
        public void MethodName()
        {
            var httpContext = MockHttphelpers.MockHttpContextBaseWithUrlReferrer(""~/pagename"", ""https://test.abc.com"");

            var checkSecureConn = httpContext.Request.IsSecureConnection;
            var userCookie = new HttpCookie(""TrackReferrer"");
            userCookie.Value = ""http://www.google.com,http://test.abc.com"";
            userCookie.Secure = true;
            userCookie.HttpOnly = true;
            httpContext.Request.Cookies.Add(userCookie);
            this.TrackingInfo.GetCustomerOriginReferral();

            Assert.AreEqual(httpContext.Session[""sessionname""].ToString(), ""www.google.com""); 
        }
</code></pre>

<p><strong>Class Library</strong></p>

<pre><code>public void GetReferral()
        {
            string urlReferrer = HttpContext.Current.Request.UrlReferrer == null ? string.Empty : HttpContext.Current.Request.UrlReferrer.ToString().ToLower();
            if (!string.IsNullOrEmpty(urlReferrer) &amp;&amp; new Uri(urlReferrer).Host != HttpContext.Current.Request.Url.Host &amp;&amp; HttpContext.Current.Request.Cookies[""TrackReferrer""] != null &amp;&amp; !string.IsNullOrEmpty(HttpContext.Current.Request.Cookies[""TrackReferrer""].Value))
            {
                //Code
            }
        }
</code></pre>

<p><strong>HttpContext Mock</strong></p>

<pre><code>public static HttpContextBase MockHttpContextBase()
        {
            var httpContextBase = Substitute.For&lt;HttpContextBase&gt;();

            var httpRequestBase = Substitute.For&lt;HttpRequestBase&gt;();
            var httpResponseBase = Substitute.For&lt;HttpResponseBase&gt;();
            var httpSessionStateBase = Substitute.For&lt;HttpSessionStateBase&gt;();
            var httpServerUtilityBase = Substitute.For&lt;HttpServerUtilityBase&gt;();

            httpRequestBase.Cookies.Returns(new HttpCookieCollection());
            httpResponseBase.Cookies.Returns(new HttpCookieCollection());
            httpRequestBase.ServerVariables.Returns(MockRequestObjects.ServerVariables);
            httpContextBase.Request.Returns(httpRequestBase);
            httpContextBase.Response.Returns(httpResponseBase);
            httpContextBase.Session.Returns(httpSessionStateBase);
            httpContextBase.Server.Returns(httpServerUtilityBase);

            // Initializing HttpContext.Current
            HttpContext.Current = MockHttpContext(); 
            HttpContext.Current.Request.Browser = new HttpBrowserCapabilities() { Capabilities = new Dictionary&lt;string, string&gt; { { ""supportsEmptyStringInCookieValue"", ""false"" } } };

            // Initializing Session in HttpContextBase in ControllerContext
            httpContextBase.Session.Returns(MockHttpContextControllerContextSession());

            // Initializing ApplicationInstance in HttpContextBase in ControllerContext
            httpContextBase.ApplicationInstance = new HttpApplication();

            // Initializing ApplicationInstance in HttpContext.Current
            HttpContext.Current.ApplicationInstance = new HttpApplication();
            httpContextBase.Request.ServerVariables.Returns(MockRequestObjects.ServerVariables);

            // Initializing FormCollection in HttpContextBase in ControllerContext
            httpContextBase.Request.Form.Returns(new FormCollection());

            return httpContextBase;
        }
</code></pre>
",https://stackoverflow.com/questions/51718922/cookies-are-not-available-in-class-library-while-doing-unit-testing,"['asp.net-mvc', 'unit-testing', 'nsubstitute']",290,FALSE,0,0
Unit testing a method which Posts and Deletes by selection C#,"<p>I have this method which selects one row of a table and copies it to the another table and then it just deletes it from the first one. The problem is that how can I unit test it because it executes two methods (Post and Delete) at the same time.</p>

<p><strong>Here is the method:</strong> </p>

<pre><code>public ActionResult Pay(int id, Car car)
    {
        try
        {
            using (BookCarDBEntities db = new BookCarDBEntities())
            {

                var carToDelete = db.Cars.FirstOrDefault(c =&gt; c.Id == id);
                var book = CreateNewBooking(carToDelete);
                db.Bookings.Add(book);



                db.Cars.Remove(carToDelete);

                db.SaveChanges();


                return RedirectToAction(""ListBookings"", ""Home"");
            }

        }
        catch (Exception ex)
        {
            return View(ex + ""error"");
        }
    }

    private Booking CreateNewBooking(Car car)
    {
        var bookingCreated = new Booking
        {
            id = car.Id,
            model = car.model,
            make = car.make,
            price = car.price,
            location = car.location
        };

        return bookingCreated;
    }
</code></pre>
",https://stackoverflow.com/questions/53804706/unit-testing-a-method-which-posts-and-deletes-by-selection-c,"['c#', 'unit-testing', 'post', 'select', 'model-view-controller']",52,FALSE,0,1
"Unit testing vue component, using vue-cli, can&#39;t test parent methods?","<p>I'm running into this problem that I can't figure out and looking around can't seem to find anyone asking the same questions...</p>

<p>So, here's my working code:</p>

<p><strong><em>main.js:</em></strong></p>

<pre><code>import Vue from 'vue'
import App from './App'
import router from './router'

Vue.config.productionTip = false

window.Vue = Vue

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  methods: {
    greetings: function () {
      return 'good morning'
    }
  },
  render: h =&gt; h(App)
})
</code></pre>

<p><strong><em>router/index.js:</em></strong></p>

<pre><code>import Vue from 'vue'
import Router from 'vue-router'
import Configurations from '@/components/Configurations'

Vue.use(Router)
export default new Router({
  routes: [
    {
      path: '/configs',
      name: 'Configurations',
      component: Configurations
    }
  ]
})
</code></pre>

<p><strong><em>App.vue:</em></strong></p>

<pre><code>&lt;template&gt;
    &lt;router-view&gt;&lt;/router-view&gt;
&lt;/template&gt;
&lt;script&gt;
export default {
  name: ""App""
};
&lt;/script&gt;
</code></pre>

<p><strong><em>Configurations.vue:</em></strong></p>

<pre><code>&lt;template&gt;
&lt;span&gt;{{greetings}}&lt;/span&gt;
&lt;/template&gt;

&lt;script&gt;
export default {
  name: ""configurations"",
  data() {
    return {
      greetings: """"
    };
  },
  created: function() {
    this.greetings = this.$root.greetings();
  }
};
&lt;/script&gt;
</code></pre>

<p>When I run this, it displays a page with the words ""good morning"" on it. Nothing else. As you can see, the greetings message is defined on the main.js file, because in this scenario I'd like a message to be displayed on all components, ie: a copyright note. So I set the message on the common ancestor to all my components.</p>

<p>From my understanding, to call a method from a ""parent"" component, you use this.$root.yourMethod() to call it.</p>

<p>Now, the problem is, that if I wish to run a unit-test for the Configurations component, I get an error which leads me to believe that the way I have things set up, I cannot test the this.$root.greetings() because something tells me the testing environment is unaware of the parent-child relationship between the components.</p>

<p>So, when I run:</p>

<pre><code>cross-env BABEL_ENV=test karma start test/unit/karma.conf.js --single-run
</code></pre>

<p>Having the following test file set up:</p>

<p><strong><em>Configurations.spec.js</em></strong>:</p>

<pre><code>import Configurations from '@/components/Configurations'
import Vue from 'vue'

describe('Configurations.vue', () =&gt; {
  it('should display a greetings message', () =&gt; {
    const Constructor = Vue.extend(Configurations)
    const ConfigurationsComponent = new Constructor().$mount()
    expect(ConfigurationsComponent.greetings).to.not.be.undefined;
  })
})
</code></pre>

<p>I get:</p>

<pre><code>&gt; 16 10 2018 09:28:35.184:INFO [karma]: Karma v1.7.1 server started at
&gt; http://0.0.0.0:3000/ 16 10 2018 09:28:35.191:INFO [launcher]:
&gt; Launching browser PhantomJS with unlimited concurrency 16 10 2018
&gt; 09:28:35.204:INFO [launcher]: Starting browser PhantomJS 16 10 2018
&gt; 09:28:40.977:INFO [PhantomJS 2.1.1 (Windows 8.0.0)]: Connected on
&gt; socket WnDl-mQqmNZQOfyzAAAA with id 10303480 ERROR LOG: '[Vue warn]:
&gt; Error in created hook: ""TypeError:  is not a constructor (evaluating
&gt; 'this.$root.greetings()')""
</code></pre>

<p>(followed by more lines that stack-overflow won't let me post because they contain too many links)</p>

<p>Now, if I were to change</p>

<pre><code>this.greetings = this.$root.greetings()
</code></pre>

<p>To:</p>

<pre><code>this.greetings = ""good morning"";
</code></pre>

<p>In the <strong><em>Configurations.vue</em></strong> file, and then run the test command again, I'd get:</p>

<pre><code>&gt; 16 10 2018 09:48:43.174:INFO [karma]: Karma v1.7.1 server started at
&gt; http://0.0.0.0:3000/ 16 10 2018 09:48:43.180:INFO [launcher]:
&gt; Launching browser PhantomJS with unlimited concurrency 16 10 2018
&gt; 09:48:43.555:INFO [launcher]: Starting browser PhantomJS 16 10 2018
&gt; 09:48:49.228:INFO [PhantomJS 2.1.1 (Windows 8.0.0)]: Connected on
&gt; socket o8BQ24wv1QX26SAZAAAA with id 53463701
&gt; 
&gt;   Configurations.vue
&gt;     √ should display a greetings message
&gt;
&gt; PhantomJS 2.1.1 (Windows 8.0.0): Executed 1 of 1 SUCCESS (0.024 secs / 0.017 secs)
&gt;
&gt; TOTAL: 1 SUCCESS
</code></pre>

<p>(followed by some other information that's irrelevant)</p>

<p>So, how can I run a unit-test for a component that contains calls to this.$root methods?</p>

<p>Any help is appreciated.</p>

<ul>
<li>Lucas</li>
</ul>
",https://stackoverflow.com/questions/52831622/unit-testing-vue-component-using-vue-cli-cant-test-parent-methods,"['javascript', 'unit-testing', 'vue.js', 'vuejs2', 'vue-cli']",471,TRUE,0,1
Live Unit Testing doesn&#39;t copy over data file used by test,"<p>I have a test that loads and processes a .json file. The file is part of the project and marked as ""copy always"" so that it's present in the build directory of the test, and I have veryfied that this does work on manual test run.</p>

<p>Live Unit Testing instead disregards this setting and fails the test as the file is not found. Is there any option other then disabling the test for live testing?</p>
",https://stackoverflow.com/questions/50198795/live-unit-testing-doesnt-copy-over-data-file-used-by-test,"['visual-studio-2017', 'live-unit-tests']",155,FALSE,0,1
How to trigger if(this.props!==nextProps) in componentwillreceiveprops in Unit Testing?,"<p>I am new in Unit Testing for React. I have a question regarding the if statement. I need test the function of componentwillreceiveprops, I know I can use spy = sinon.stub(component.props,""componentwillreceiveprops"") method to let spy be called.</p>

<p>But in my component, there is an if statement, such as</p>

<pre><code>componentwillreceiveprops(nextProps){
    if(this.props.name!==nextProps.name) {
        this.setState({
            oldstate: newstate
        })
    }
}
</code></pre>

<p>I can make the <code>componentWillReceiveProps</code> function called. If I remove the if statement, the setState function can be called either. But what I have in my component contains a if statement, it is not called when I run the unit testing. Is there any way to make this if statement called? Thank you in advance.</p>
",https://stackoverflow.com/questions/53330092/how-to-trigger-ifthis-props-nextprops-in-componentwillreceiveprops-in-unit-t,"['reactjs', 'unit-testing', 'if-statement', 'triggers', 'react-lifecycle']",88,TRUE,0,1
MVC unit testing a RedirectToAction that returns with a status code,"<p>I am trying to write a unit test for a controller that returns a <code>RedirectToAction</code> with the view, the controller, and also a status code. The return is below</p>

<pre><code>return RedirectToAction(""Index"", ""Errors"", new {statusCode = StatusCodes.Status505HttpVersionNotsupported});
</code></pre>

<p>I have found several stack overflow articles but none of them helped me figure out what the problem is my unit tests look like.</p>

<pre><code>[TestMethod]
public void Index_OnError_ThrowsException()
{
    //Arrange
    Service.Setup(m =&gt; m.GetAllViewModels()).Throws(new NullReferenceException());

    //Act
    var result = (RedirectToRouteResult) controller.Index();


    //Assert
    Assert.AreEqual(""Index"", result.RouteValues[""action""]);
    Assert.AreEqual(""Error"", result.RouteValues[""controller""]);
}
</code></pre>

<p>I keep get an exception thrown that says it can't cast </p>

<blockquote>
  <p>RedirectToRouteResult to type RedirectToRouteResult</p>
</blockquote>

<p>And I can't figure out another way to run this unit test so I can test my controller.</p>
",https://stackoverflow.com/questions/49321438/mvc-unit-testing-a-redirecttoaction-that-returns-with-a-status-code,"['c#', 'unit-testing', 'asp.net-core-2.0']",1514,TRUE,-1,1
Cannot read property &#39;0&#39; of undefined Angular 2/4 Unit testing,"<p>I created a unit testing for a service file like this</p>

<pre><code>import { TestBed, inject } from '@angular/core/testing';
import { OrderGroupingService } from './order-grouping.service';
import { MockBackend } from '@angular/http/testing';
import { BaseRequestOptions, Jsonp, Http, HttpModule, JsonpModule, 
ResponseOptions } from '@angular/http';
import { CommonError } from 'app/services/helper/commonerror';
import { tick } from '@angular/core/testing';
import { fakeAsync } from '@angular/core/testing';
import { orderGrouping } from 'app/entity/orderGrouping';

fdescribe('OrderGroupingService', () =&gt; {
let service: OrderGroupingService;
let backend: MockBackend;
let orderGrouping: orderGrouping

beforeEach(() =&gt; {
TestBed.configureTestingModule({
  providers: [OrderGroupingService, MockBackend, BaseRequestOptions, CommonError,
    {
      provide: Jsonp,
      useFactory: (backend, options) =&gt; new Jsonp(backend, options),
      deps: [MockBackend, BaseRequestOptions]
    },
    {
      provide: Http,
      useFactory: (backend, options) =&gt; new Http(backend, options),
      deps: [MockBackend, BaseRequestOptions]
    }],
  imports: [HttpModule, JsonpModule]
});
// Get the MockBackend
backend = TestBed.get(MockBackend);
// Returns a service with the MockBackend so we can test with dummy responses
service = TestBed.get(OrderGroupingService);
});

it('Should Be Created Order Grouping Service', 
inject([OrderGroupingService], (service: OrderGroupingService) =&gt; {
expect(service).toBeTruthy();
}));

it('Add Order Groups And Returns Success Message', fakeAsync(() =&gt; {

let response = {
  ""results"": [
    {
      ""message"": ""Saved successfully.""
    }]
};

this.orderGrouping = {
  partyRoleId: 313,
  description: ""sampleName""
}

// 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)
  }));
});

tick();

// Perform a request and make sure we get the response we expect
service.addOrderGroup(this.orderGrouping).subscribe(res =&gt; {
  debugger;
  expect(res.results[0].message).toBe(""Saved successfully."");
}, );

}));

 });
</code></pre>

<p>Here my first test case is passed. But the second one always fails and it says 'Cannot read property '0' of undefined'. My second test case is 'Add Order Groups And Returns Success Message'. Is there any idea what is wrong? database working correctly.</p>
",https://stackoverflow.com/questions/48220617/cannot-read-property-0-of-undefined-angular-2-4-unit-testing,"['angular', 'unit-testing', 'typescript']",1107,FALSE,0,0
How to test shared component&#39;s method in Angular 2 unit testing?,"<p>How can I test a shared components method with Angular 2 unit testing? I need to test whether a shared components method has been called or not.</p>
",https://stackoverflow.com/questions/51471470/how-to-test-shared-components-method-in-angular-2-unit-testing,['angular'],203,TRUE,0,1
unit testing in Typo3. What is the procedure to do it?,"<p>I have one question. In any custom extension folder, there is another folder called Tests.
My question is, how can I utilise it inorder to do unit test of each public function of controller and Repository?</p>

<p>What is the procedure to do it?
Can anyone help me?</p>
",https://stackoverflow.com/questions/52518921/unit-testing-in-typo3-what-is-the-procedure-to-do-it,['typo3-8.x'],61,FALSE,0,1
Can I get performance testing in node.js like a unit testing,"<p>I need performance testing/tuning in nodejs.<br>
In CI/CLI, like a unit test.(target to function call. not networking.)<br>
I use mocha <code>timeout()</code> now.  </p>

<pre><code>var dictionary_handle;
it (""Dictionary.init_dictionary timeout"", function(done) {
    dictionary_handle = Dictionary.init_dictionary(dictionary_data);
    done();
}).timeout(1000);

it (""Linad.initialize timeout"", function(done) {
    Linad.initialize(function(err){
    done();
    });
}).timeout(6000);
</code></pre>

<p>But it is not enough.</p>

<p>I need that function.</p>

<ul>
<li>able using in CI.  </li>
<li>execute multiple time  </li>
<li>output performance metric information  </li>
</ul>
",https://stackoverflow.com/questions/53127950/can-i-get-performance-testing-in-node-js-like-a-unit-testing,"['javascript', 'node.js', 'performance', 'unit-testing', 'performance-testing']",2306,TRUE,0,2
Importing view in jest for unit testing gives invariant violation error,"<p>We were trying to migrate our unit tests to Jest (from Mocha Chai Expect) for an existing application, when our team ran into this issue where as soon as we try to import a View (say DummyView.js), we get an </p>

<blockquote>
  <p>Invariant Violation error: You must pass a component to the function
  returned by connect. Instead received undefined.</p>
</blockquote>

<p>We get this error even if we have commented out all test code. It fails on the import itself.</p>

<p>This DummyView.js is itself used inside a container in our code.</p>

<pre><code>// DummyContainer.js
import { connect } from 'react-redux'
import DummyView from './DummyView.js'

const mapStateToProps = (state) =&gt; { 
  tabType: state.tabType,
  miscProps: state.miscProps
}
const mapDispatchProps = (dispatch) =&gt; {...}

export default connect(mapStateToProps, mapDispatchToProps)(DummyView)

// DummyView.js
import React from 'react'
import Tab1Section from './Tab1Section'
import Tab2Section from './Tab2Section'
import Tab3Section from './Tab3Section'

const DummyView = ({tabType, miscProps}) =&gt; {
  const TabRender = null
  switch(tabType) {
    case 1:
      TabRender = &lt;Tab1Section { ...miscProps } /&gt;
    case 2:
      TabRender = &lt;Tab1Section { ...miscProps } /&gt;
    case 3:
      TabRender = &lt;Tab1Section { ...miscProps } /&gt;
    default:
      TabRender = (
        &lt;div&gt;&lt;span&gt;Error&lt;/span&gt;&lt;div&gt;
      )
  }

  return (TabRender)
}

export default DummyView
</code></pre>

<p>Does Jest not allow to test the DummyView alone? Why/ how does it know its used inside a container?</p>

<p>Does it make sense to test only a container then? Assuming the View will be tested along with it?</p>

<p>PS: I'm aware invariant violation means the HTML is probably formatted incorrectly. But how do I get to the tests if it fails on import?</p>
",https://stackoverflow.com/questions/50529008/importing-view-in-jest-for-unit-testing-gives-invariant-violation-error,"['reactjs', 'unit-testing', 'redux', 'jestjs']",1050,TRUE,0,1
Setting up Mock IMember Object in Umbraco 7.5.10 for Unit Testing,"<p>So I'm trying to Unit Test an Umbraco 7.5.10 controller. Context has been mocked and passed through with no issue. I then go on to create a mock IMember object but whenever I try to set any of the properties (LastLoginDate, Name, Email etc) they're not being set and when you go to inspect the inactiveMemberEmailed.Object during debugging all the properties are null. I've checked what IMember is inheriting and there is no reason why they shouldn't be set.</p>

<pre><code>using NUnit.Framework;
using Umbraco.Core.Models;
using Site.Logic.Controllers.SurfaceControllers;
using System;
using Moq;
using Umbraco.UnitTesting.Adapter.Support;
using System.Collections.Generic;

namespace Site.Tests
{
    [TestFixture]
    public class InactiveMemberCheckTest
    {
        private UmbracoSupport support = new UmbracoSupport();
        private Mock&lt;IMember&gt; inactiveMemberEmailed;

        [SetUp]
        public void Setup()
        {
            support.SetupUmbraco();

            this.inactiveMemberEmailed = new Mock&lt;IMember&gt;();


            inactiveMemberEmailed.Object.LastLoginDate = DateTime.Today.AddMonths(-12);
            inactiveMemberEmailed.Object.Name = ""inactiveMemberNotEmailed"";
            inactiveMemberEmailed.Object.Email = ""email@example.co.uk"";
            inactiveMemberEmailed.Object.SetValue(""contactId"", 1);
            inactiveMemberEmailed.Object.SetValue(""inactiveCheckEmailed"", true);
        }

        [Test]
        public void MembersCanBeChecked()
        {
            var controller = new InactiveMemberCheckController(support.UmbracoContext);

            var resultInactiveEmailed = controller.InactiveCheck(inactiveMemberEmailed.Object);

            Assert.AreEqual(resultInactiveEmailed, true);
        }
    }
}   
</code></pre>
",https://stackoverflow.com/questions/50640758/setting-up-mock-imember-object-in-umbraco-7-5-10-for-unit-testing,"['c#', 'unit-testing', 'nunit', 'umbraco', 'umbraco7']",87,TRUE,0,1
Angular6/Karma Unit Testing - How to include external JS library (AOS)?,"<p>I'm using <a href=""https://www.npmjs.com/package/aos"" rel=""nofollow noreferrer"">AOS</a>  (Animate on scroll library - an external JS library) in angular 6 project and it is loaded to the project in following way.</p>

<pre><code>import AOS from 'aos';

ngAfterViewInit() {
    AOS.init();
  }
</code></pre>

<p>I need to load this external JS library to the Angular Unit Test Component in order to run the angular unit test. How to do that? I tried following way but it doesn't work. (I believe it's because AOS is not a component per se)</p>

<pre><code>import AOS from 'aos';

describe(""SampleComponent"", () =&gt; {
  let component: SampleComponent;
  let fixture: ComponentFixture&lt;SampleComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [SampleComponent],
      imports: [
        FormsModule,
        RouterTestingModule,
        AOS
      ],
      providers:[]
    }).compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(SampleComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it(""should create"", () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>
",https://stackoverflow.com/questions/52219913/angular6-karma-unit-testing-how-to-include-external-js-library-aos,"['angular', 'unit-testing', 'jasmine', 'karma-runner']",491,FALSE,0,1
"Package convention when working with java, unit testing and cucumber bdd","<p>I want to modify my actual project so I can put the integration test on the same repo.
Right now i have something like </p>

<p>*src</p>

<p>**main</p>

<p>***java</p>

<p>****com.example</p>

<p>** test</p>

<p>***groovy</p>

<p>****com.example</p>

<p>I have all the unit test on src/test/groovy/com/example and the code on src/main/java/com/example now I want to add the specs related to cucumber somewhere on the project 
I can not find if there is any convention to this so I'm asking here to see if i can find some answer.</p>
",https://stackoverflow.com/questions/51690582/package-convention-when-working-with-java-unit-testing-and-cucumber-bdd,"['spring', 'unit-testing', 'cucumber', 'bdd', 'cucumber-jvm']",137,TRUE,0,2
How to mock a OPC UA Session for unit testing in C#,"<p>I have a C# application, which includes a service that works with multiple OPC UA Sessions (<a href=""http://documentation.unified-automation.com/uasdkdotnet/2.0.0/L2ClientSdkSession.html"" rel=""noreferrer"">UnifiedAutomation.UaClient.Session</a>). These sessions are created by connecting to addresses like opc.tcp://localhost:48030 etc.</p>

<pre><code>foreach (ConnectionStringSettings connectionSettings in ConfigurationManager.ConnectionStrings)
{
    var connectionString = connectionSettings.ConnectionString;

    // Ignore non-OPC-connections 
    if (!connectionString.StartsWith(""opc.tcp"")) continue;

    // Create new session for connection
    var session = new Session
    {
        AutomaticReconnect = true,
        ReconnectDelay = 0
    };

    // Connect to OPC UA Server
    try
    {
        session.Connect(connectionString, SecuritySelection.None);
        Log(""OPC UA Session establish."", EventLogEntryType.Information);
    }
    catch (StatusException)
    {
        Log($""No OPC UA Server found at {connectionString}."",
            EventLogEntryType.Warning);
    }
}
</code></pre>

<p>I want to <strong>unit test</strong> the methods of my service but I cannot figure out how to <strong>mock the OPC UA sessions</strong>.</p>

<p>Any idea if this is possible at all?</p>
",https://stackoverflow.com/questions/52943870/how-to-mock-a-opc-ua-session-for-unit-testing-in-c,"['c#', 'unit-testing', 'nunit', 'opc-ua', 'unified-automation-sdk']",1172,FALSE,5,0
How to provide routes with guards for unit testing Angular 6 Component?,"<p>I have an <strong>Angular 6</strong> component that has input fields.  If any of the input fields fail validation if the user tries to navigate away, a guard will trigger on the <code>canDeactivate</code> function.  The guard is generic because this logic needs to happen on more than one component in the app.  It works beautifully running it, but when I attempt to unit test this behavior, the <code>canDeactivate</code> function in the guard is never reached.  The guard itself is reached, but never the function.  Am I providing the guard in an incorrect way? </p>

<p><strong>Guard Component Interface</strong></p>

<pre><code>export interface GuardComponent {
    canDeactivate: () =&gt; Observable&lt;boolean&gt; | Promise&lt;boolean&gt; | boolean;
}
</code></pre>

<p><strong>CanDeactivateGuard</strong></p>

<pre><code>export class CanDeactivateGuard implements CanDeactivate&lt;GuardComponent&gt; {
    constructor() { }

    canDeactivate(component: GuardComponent): Observable&lt;boolean&gt; | Promise&lt;boolean&gt; | boolean {
        return component.canDeactivate();
    }
}
</code></pre>

<p><strong>Component</strong></p>

<pre><code>export class MyComponent implements OnInit, GuardComponent {

...

    canDeactivate() {
        if (!this.form.invalid) {
            return true;
        }
        this.isError = true;
        return false;
    }
}
</code></pre>

<p><strong>spec</strong></p>

<pre><code>const routes = [
    {
        path: 'my-component',
        component: MyComponent,
        canDeactivate: [CanDeactivateGuard],
    },
    {
        path: 'my-component-2',
        component: MyComponent2
    }
];

beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
        imports: [ RouterTestingModule.withRoutes(routes) ],
        declarations: [ MyComponent, MyComponent2 ],
        providers: [ CanDeactivateGuard ],
    }).compileComponents();
}));

beforeEach(() =&gt; {
    fixture = TestBed.createComponent(MyComponent);
    component = fixutre.componentInstance;
    fixture.detectChanges();
});    

it('should restrict route change if validation fails', fakeAsync(inject([Router, Location, CanDeactivateGuard], (router: Router, location: Location, guard: CanDeactivateGuard) =&gt; {
    const textbox = fixture.debugElement.query(By.css('#inputField')).nativeElement;
    const canDeactivateSpy = spyOn(guard, 'canDeactivate');
    const componentDeactivateSpy = spyOn(component, 'canDeactivate');

    // anything lower than 0 will fail the form
    textbox.value = '-10';
    fixture.detectChanges();

    router.navigate(['/my-page-2']).then(() =&gt; {
        expect(location.path()).toBe('/my-component');  // path doesn't change because guard blocks it due to form being invalid
        expect(canDeactivateSpy).toHaveBeenCalled();
        expect(componentDeactivateSpy).toHaveBeenCalled();
    });
})));
</code></pre>

<p>The test fails because the <code>canDeactivate</code> functions are never reached.</p>
",https://stackoverflow.com/questions/52505812/how-to-provide-routes-with-guards-for-unit-testing-angular-6-component,"['javascript', 'unit-testing', 'jasmine', 'angular6', 'angular-router-guards']",883,FALSE,5,0
Angular 4 Unit testing: Cannot call Promise.then from within a sync test,"<p>I just started to write unit test for my angular service and I am running in to a promise error.</p>

<p>Basically I have two services 
1.  Configuration service
2.  CountryDetails service 
The country details service uses the configuration service to return a observable.
Below is the code for the services</p>

<p><strong>Configuration service</strong></p>

<pre><code>import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

@Injectable()
export class ConfigurationService {
private config: any;
constructor(private http: Http) {
}
public loadConfig(): Promise&lt;any&gt; {
     return this.http.get('assets/env-config.json')
       .map(res =&gt; res.json())
       .toPromise()
       .then(settings =&gt; this.config = settings);
}
public get configuration(): any {
     return this.config;
   }
}
</code></pre>

<p><strong>CountryDetails Service</strong> </p>

<pre><code>import { Injectable } from '@angular/core';
import { Country } from '../models/country';
import {ConfigurationService  } from '../../services/configuration.service';
import { Observable } from 'rxjs/Observable';
import { HttpClient} from '@angular/common/http';
@Injectable()
export class CountryDetailsService {
public countryData: Country;
  constructor(
    private http: HttpClient,
    private configSvc: ConfigurationService
  ) { }
getData(isoCode: string): Observable&lt;Country&gt; {
  const endpointUrl = `${this.configSvc.configuration.CountryAPIUrl}Details/${isoCode}`;
  const country$ = this.http.get&lt;Country&gt;(endpointUrl);
  country$.subscribe(rslt =&gt; this.countryData = rslt);
  return country$;
}
}
</code></pre>

<p><strong>Test for CountryDetails</strong></p>

<pre><code>import { TestBed, getTestBed, inject, async } from '@angular/core/testing';
import { CountryDetailsService } from './countrydetails.service';
import {ConfigurationService  } from '../../services/configuration.service';
import { Country } from '../models/country';

import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { HttpClient, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Http } from '@angular/http';

fdescribe('CountryDetailsService', () =&gt; {

  let httpClient: HttpClient;
  let httpTestingController: HttpTestingController;

  let countrySvc: CountryDetailsService;
  let configSvc:  ConfigurationService;

  let  http = TestBed.get(Http);

  let  expectedcountryData: Country ;
  const inputIsoCode = 'IN';

  beforeEach( async (() =&gt; {

    TestBed.configureTestingModule({
      imports: [ HttpClientTestingModule ],
      providers: [CountryDetailsService, ConfigurationService  ]
    });

    httpClient = TestBed.get(HttpClient);
    httpTestingController = TestBed.get(HttpTestingController);

    countrySvc = TestBed.get(CountryDetailsService);
    configSvc = new ConfigurationService(http);
    configSvc.loadConfig();

    countrySvc = TestBed.get(CountryDetailsService);
      expectedcountryData = {
        CountryId: 13415,
        IsoCode2: 'IN',
        IsoCode3: 'IND',
        LongName: 'India, Republic of',
        Name: 'India',
        Capital: 'New Delhi',
        NationalDay: '26 January',
        NumberOfAccession: 18,
        Ambassador: null,
        CurrentBoardMember: 'Y',
        MembershipStartDate: '1957-07-16T00:00:00'
      };
    }));


  afterEach(async(() =&gt; {
    httpTestingController.verify();
  }));

  it('should return expected country (called once)', async( () =&gt; {
    countrySvc.getData(inputIsoCode).subscribe(
     countryData =&gt; {
       expect(countryData).toEqual(expectedcountryData, 'should return expected country i.e IN');
     }
 );

const req = httpTestingController.expectOne(`${this.configSvc.configuration.CountryAPIUrl}Details/${inputIsoCode}`);
 expect(req.request.method).toEqual('GET');

req.flush(expectedcountryData);
}));

});
</code></pre>

<p><strong>Error</strong></p>

<pre><code>Error: Cannot call Promise.then from within a sync test.
Error: Cannot call Promise.then from within a sync test.
    at SyncTestZoneSpec.webpackJsonp.../../../../zone.js/dist/sync-test.js.SyncTestZoneSpec.onScheduleTask ( ://localhost:9876/_karma_webpack_/webpack:/C:/VSO/CountryProfiles AngularApp/Iaea.CountryProfiles.Web/node_modules/zone.js/dist/sync-test.js:30:1)
    at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.scheduleTask ( ://localhost:9876/_karma_webpack_/webpack:/C:/VSO/CountryProfiles AngularApp/Iaea.CountryProfiles.Web/node_modules/zone.js/dist/zone.js:405:1)
    at Zone.webpackJsonp.../../../../zone.js/dist/zone.js.Zone.scheduleTask ( ://localhost:9876/_karma_webpack_/webpack:/C:/VSO/CountryProfiles AngularApp/Iaea.CountryProfiles.Web/node_modules/zone.js/dist/zone.js:236:1)
    at Zone.webpackJsonp.../../../../zone.js/dist/zone.js.Zone.scheduleMicroTask ( ://localhost:9876/_karma_webpack_/webpack:/C:/VSO/CountryProfiles AngularApp/Iaea.CountryProfiles.Web/node_modules/zone.js/dist/zone.js:256:1)
    at scheduleResolveOrReject ( ://localhost:9876/_karma_webpack_/webpack:/C:/VSO/CountryProfiles AngularApp/Iaea.CountryProfiles.Web/node_modules/zone.js/dist/zone.js:871:1)
    at ZoneAwarePromise.then ( ://localhost:9876/_karma_webpack_/webpack:/C:/VSO/CountryProfiles AngularApp/Iaea.CountryProfiles.Web/node_modules/zone.js/dist/zone.js:981:1)
    at ApplicationInitStatus.webpackJsonp.../../../core/esm5/core.js.ApplicationInitStatus.runInitializers ( ://localhost:9876/_karma_webpack_/webpack:/C:/VSO/CountryProfiles AngularApp/Iaea.CountryProfiles.Web/node_modules/@angular/core/esm5/core.js:3457:1)
    at TestBed.webpackJsonp.../../../core/esm5/testing.js.TestBed._initIfNeeded ( ://localhost:9876/_karma_webpack_/webpack:/C:/VSO/CountryProfiles AngularApp/Iaea.CountryProfiles.Web/node_modules/@angular/core/esm5/testing.js:964:1)
    at TestBed.webpackJsonp.../../../core/esm5/testing.js.TestBed.get ( ://localhost:9876/_karma_webpack_/webpack:/C:/VSO/CountryProfiles AngularApp/Iaea.CountryProfiles.Web/node_modules/@angular/core/esm5/testing.js:1000:1)
    at Function.webpackJsonp.../../../core/esm5/testing.js.TestBed.get ( ://localhost:9876/_karma_webpack_/webpack:/C:/VSO/CountryProfiles AngularApp/Iaea.CountryProfiles.Web/node_modules/@angular/core/esm5/testing.js:805:1)

I would be grateful if someone can point out the exact problem in this
</code></pre>
",https://stackoverflow.com/questions/49282588/angular-4-unit-testing-cannot-call-promise-then-from-within-a-sync-test,"['angular', 'unit-testing']",1923,FALSE,4,0
Swift: Timeout when unit testing orientation changes after upgrading to Xcode 10,"<p>We recently upgraded from Xcode 8 to 10. After -finally- getting everything to compile again, I'm having an issue in our unit tests that involve orientation changes.
What I had been doing to simulate device orientation changes was</p>

<pre><code>    XCUIDevice.shared().orientation = .landscapeLeft
    ...
    XCUIDevice.shared().orientation = .faceUp
    ...
    etc.
</code></pre>

<p>Now when this line is executed, the ""device"" (simulator of iPhone 8+) is making the appropriate orientation change, but the call ultimately fails due to a timeout on the confirmation:</p>

<pre><code>    [iMomTests.DataScreenTests testLandscape] : Failed to set orientation: Error Domain=XCTDaemonErrorDomain Code=15 ""Timed out waiting for confirmation of orientation change."" UserInfo={NSLocalizedDescription=Timed out waiting for confirmation of orientation change.}
</code></pre>
",https://stackoverflow.com/questions/52426297/swift-timeout-when-unit-testing-orientation-changes-after-upgrading-to-xcode-10,"['swift', 'unit-testing', 'timeout', 'orientation', 'xcode10']",719,TRUE,4,2
Best Practice for Unit Testing a Controller that depends on UserManager&lt;TUser&gt;?,"<p>I have a controller with the following signature:</p>

<pre><code>[Route(""api/[controller]"")]
[ApiController]
public class UsersController : ControllerBase
{
    private ILogger&lt;UsersController&gt; _logger;

    private readonly UserManager&lt;IdentityUser&gt; _usermanager;

    public UsersController(ILogger&lt;UsersController&gt; logger, UserManager&lt;IdentityUser&gt; usermanager)
    {
        _usermanager = usermanager;
        _logger = logger;
    }

    [HttpGet(""{_uniqueid}"")]
    public async Task&lt;ObjectResult&gt; GetUser(string _uniqueid)
    {
        //Retrieve the object
        try
        {
            var user = await _usermanager.FindByIdAsync(uniqueid);

            var model = JsonConvert.DeserializeObject&lt;GetUserModel&gt;(user.ToString());

            return new ObjectResult(JsonConvert.SerializeObject(model));
        }

        catch(CustomIdentityNotFoundException e)
        {
            return new BadRequestObjectResult((""User not found: {0}"", e.Message));
        }
    }
}
</code></pre>

<p>Right now my unit test looks like this:</p>

<pre><code>public class UsersUnitTests
{
    public UsersController _usersController;

    private UserManager&lt;IdentityUser&gt; _userManager;


    public UsersUnitTests()
    {
        _userManager = new MoqUserManager&lt;IdentityUser&gt;();

        _usersController = new UsersController((new Mock&lt;ILogger&lt;UsersController&gt;&gt;()).Object, _userManager);
    }

    [Fact]
    public async Task GetUser_ReturnsOkObjectResult_WhenModelStateIsValid()
    {
        //Setup

        //Test
        ObjectResult response = await _usersController.GetUser(""realuser"");

        //Assert
        //Should receive 200 and user data content body
        response.StatusCode.Should().Be((int)System.Net.HttpStatusCode.OK);
        response.Value.Should().NotBeNull();
    }
}
</code></pre>

<p>and the Moq'd classes:</p>

<pre><code>public class MoqUserManager&lt;T&gt; : UserManager&lt;IdentityUser&gt;
{
    public MoqUserManager(IUserStore&lt;IdentityUser&gt; store, IOptions&lt;IdentityOptions&gt; optionsAccessor, 
        IPasswordHasher&lt;IdentityUser&gt; passwordHasher, IEnumerable&lt;IUserValidator&lt;IdentityUser&gt;&gt; userValidators, 
        IEnumerable&lt;IPasswordValidator&lt;IdentityUser&gt;&gt; passwordValidators, ILookupNormalizer keyNormalizer, 
        IdentityErrorDescriber errors, IServiceProvider services, ILogger&lt;UserManager&lt;IdentityUser&gt;&gt; logger) 
        : base(store, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors, services, logger)
    {
    }

    public MoqUserManager()
        : base((new MoqUserStore().Store), new Mock&lt;IOptions&lt;IdentityOptions&gt;&gt;().Object, 
            new Mock&lt;IPasswordHasher&lt;IdentityUser&gt;&gt;().Object, new Mock&lt;IEnumerable&lt;IUserValidator&lt;IdentityUser&gt;&gt;&gt;().Object, 
            new Mock&lt;IEnumerable&lt;IPasswordValidator&lt;IdentityUser&gt;&gt;&gt;().Object, 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;IdentityUser&gt;&gt;&gt;().Object)
    {

    }
}

public class MoqUserStore : IdentityUserStore
{
    private Mock&lt;IdentityUserStore&gt; _store;

    public MoqUserStore()
        :base(new Mock&lt;IdentityDbContext&gt;().Object, new Mock&lt;ILogger&lt;IdentityUserStore&gt;&gt;().Object, null)
    {

        _store = new Mock&lt;IdentityUserStore&gt;(new Mock&lt;IdentityDbContext&gt;().Object, new Mock&lt;ILogger&lt;IdentityUserStore&gt;&gt;().Object, null);

        _store.Setup(x =&gt; x.FindByIdAsync(""realuser"", default(CancellationToken))).Returns(Task.Run(() =&gt; new IdentityUser(""realuser"")));
        _store.Setup(x =&gt; x.FindByIdAsync(""notrealuser"", default(CancellationToken))).Throws(new CustomIdentityNotFoundException());
        _store.Setup(x =&gt; x.CreateAsync(new IdentityUser(""realuser""), default(CancellationToken))).Returns(Task.Run(() =&gt; IdentityResult.Success));
    }

    public IdentityUserStore Store { get =&gt; _store.Object; }

}
</code></pre>

<p>I get <code>reference not set to an instance of an object</code> errors when the <code>MoqUserManager</code> constructor is called.</p>

<p>My question is: What is the best practice (I will settle for <em>works but stinks to high heaven</em>) for unit testing these types of controllers that depend on <code>UserManager</code> and/or <code>SignInManager</code>, and what is a easily repeatable way to mock the <code>UserStore</code> dependency?</p>
",https://stackoverflow.com/questions/53453232/best-practice-for-unit-testing-a-controller-that-depends-on-usermanagertuser,"['c#', 'unit-testing', 'moq', 'xunit', 'asp.net-core-2.1']",988,TRUE,4,1
JUnit What is the best way to fail java.io.File.delete() for unit testing,"<p>I am unit testing a method that is using <a href=""https://docs.oracle.com/javase/7/docs/api/java/io/File.html#delete()"" rel=""nofollow noreferrer"">java.io.File.delete()</a> and I am wondering what the best way to make <a href=""https://docs.oracle.com/javase/7/docs/api/java/io/File.html#delete()"" rel=""nofollow noreferrer"">java.io.File.delete()</a> fail is.</p>

<pre><code>final File newFile = new File(filePath); // filePath is a valid path

if (newFile.exists())
{
    if (!newFile.delete())
    {
        final String msg = ""Error deleting file "" + newFile.getAbsolutePath();
        LOG.error(msg);
    }
}
</code></pre>

<p>So the file must exist, and I want the <a href=""https://docs.oracle.com/javase/7/docs/api/java/io/File.html#delete()"" rel=""nofollow noreferrer"">newFile.delete()</a> to fail.</p>

<p>I understand this could be done by:</p>

<ul>
<li>Mocking the <a href=""https://docs.oracle.com/javase/7/docs/api/java/io/File.html"" rel=""nofollow noreferrer"">File</a> class delete method to return false or throw <a href=""https://docs.oracle.com/javase/7/docs/api/java/lang/SecurityException.html"" rel=""nofollow noreferrer"">java.lang.SecurityException</a></li>
<li>Somehow use a security manager and its <a href=""https://docs.oracle.com/javase/7/docs/api/java/lang/SecurityManager.html#checkDelete(java.lang.String)"" rel=""nofollow noreferrer"">SecurityManager.checkDelete(java.lang.String)</a> method denies delete access to the file</li>
<li>Maybe simply changing read/write access alone could do this, but it hasn't seem to be working for me in <a href=""https://junit.org/junit4/"" rel=""nofollow noreferrer"">JUnit 4</a>.</li>
</ul>
",https://stackoverflow.com/questions/48792823/junit-what-is-the-best-way-to-fail-java-io-file-delete-for-unit-testing,"['java', 'file', 'unit-testing', 'junit', 'io']",6058,TRUE,3,3
Angular 5: Karma Unit testing fails to start HeadlessChrome on CI environment,"<p>We're facing issues on our CI environment (Jenkins within a Docker build pod on Openshift).</p>

<p><strong>Error: Failed to adjust OOM score of renderer with pid 261: Permission denied (13)</strong></p>

<p>Here some additionalinfos: </p>

<ul>
<li>Docker based build pod is running based on CentOS</li>
<li>CustomLauncher created with --no-sandbox flag (see below)</li>
<li>We are not able to run the pod as a root </li>
<li>The error occurs intermittent. But most of the time it fails. Like in one of 10 jobs it works. </li>
<li>If we execute the tests locally, everything works fine. </li>
</ul>

<p>Versions:</p>

<ul>
<li>Angular version 5.1.0</li>
<li>Karma-chrome-launcher 2.1.1 </li>
<li>Karma 1.70</li>
</ul>

<p><code>
    [31m22 01 2018 13:05:37.019:ERROR [launcher]: [39mChrome stdout: 
    [31m22 01 2018 13:05:37.019:ERROR [launcher]: [39mChrome stderr: 
    DevTools listening on ws://127.0.0.1:9222/devtools/browser/c45b2629-938e-490e-a8af-706302677ea4
    [0122/130522.747519:ERROR:zygote_host_impl_linux.cc(268)] Failed to adjust OOM score of renderer with pid 261: Permission denied (13)
    [0122/130533.563149:INFO:CONSOLE(8743)] ""Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/."", source: http://localhost:9876/_karma_webpack_/polyfills.bundle.js (8743)
    [0122/130533.563271:ERROR:service_manager.cc(157)] Connection InterfaceProviderSpec prevented service: content_renderer from binding interface: blink::mojom::ReportingServiceProxy exposed by: content_browser</code></p>

<p>Karma.conf
<code>customLaunchers: {
         ChromeHeadlessNoSandbox: {
           base: 'ChromeHeadless',
           flags: [
             '--no-sandbox',
             '--disable-setuid-sandbox',
             '--remote-debugging-port=9222',
             '--disable-gpu'
           ]
         }
       }</code></p>
",https://stackoverflow.com/questions/48388007/angular-5-karma-unit-testing-fails-to-start-headlesschrome-on-ci-environment,"['angular', 'jenkins', 'openshift', 'karma-runner', 'karma-chrome-launcher']",1608,TRUE,3,1
"unit testing issue: wrong number of arguments (given 0, expected 1..2)","<p>I have an issue with my controller test, when running it in the terminal it return: </p>

<pre><code>Error:
 StoriesControllerTest#test_show_story:
 ArgumentError: wrong number of arguments (given 0, expected 1..2)
test/controllers/stories_controller_test.rb:45:in `block in 
&lt;class:StoriesControllerTest&gt;'
</code></pre>

<p>my test in stories_controller_test is:</p>

<pre><code>test ""show story"" do
  get story_path(stories(:one))
  assert_response :success
  assert_response.body.include?(stories(:one).name) #line 45
end
</code></pre>

<p>and in my stories.yml file I have:</p>

<pre><code>one:
  name: Bitcoin Reddit
  link: https://www.reddit.com/r/Bitcoin/
</code></pre>

<p>If more is necessary please ask and the whole project is <a href=""https://github.com/twentyfivemtl/ninjabook"" rel=""nofollow noreferrer"">here</a>. </p>

<p>Still beginning with unit testing and could not find a solution to this issue. </p>
",https://stackoverflow.com/questions/48938694/unit-testing-issue-wrong-number-of-arguments-given-0-expected-1-2,"['ruby-on-rails', 'minitest']",827,TRUE,3,1
Espresso unable to resolve activity for intent - Unit testing abstract base activity,"<p>I'm brand new to Espresso and I'm trying to test a behavior in an abstract activity class in android.</p>

<p>Based on what I've read, the best way to do this is to create a class in the test file that extends the base class and implement whatever methods are needed to exercise the superclass behavior.</p>

<p>I have done this, but when I try to run it, I get the following error:</p>

<p>(Only the relevant stack trace line is shown with some private info <code>redacted</code>)</p>

<p><code>Caused by: java.lang.RuntimeException: Unable to resolve activity for: Intent { act=android.intent.action.MAIN flg=0x14000000 cmp=com.redacted.redacted/.viewcontrollers.onboarding.BaseOnboardingActivityTest$SinglePageTestOnboarder }</code></p>

<p>Some questions seemed to indicate this was because of a missing manifest entry for the Activity, but it appears as if that was an old way of doing things and is no longer needed, though I may be misinterpreting things.</p>

<p>How can I fix this? I don't want the activity to be a part of the actual application, since it is only usable for testing.</p>

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

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

    @Rule @JvmField
    var onboarderActivityTestRule = ActivityTestRule&lt;SinglePageTestOnboarder&gt;(SinglePageTestOnboarder::class.java)

    @Test
    fun testPageNumberDotsDoNotAppearWhenOnlyOnePage() {
        val testActivity = onboarderActivityTestRule.activity

        testActivity.pagesForOnboarding = getOnboardingTestPages(1)
        testActivity.displayPages()
        onView(withId(R.id.indicator_circle)).check(doesNotExist())

        testActivity.pagesForOnboarding = getOnboardingTestPages(2)
        testActivity.displayPages()
        onView(withId(R.id.indicator_circle)).check(matches(isDisplayed()))
    }

    class SinglePageTestOnboarder : BaseOnboardingActivity() {

        lateinit var pagesForOnboarding: List&lt;OnboarderPageData&gt;

        fun displayPages() {
            super.showOnboardingPages(pagesForOnboarding, ""test"")
        }

    }

    private fun getOnboardingTestPages(numPages: Int): List&lt;OnboarderPageData&gt; {
        val pages = arrayListOf&lt;OnboarderPageData&gt;()
        for (i in 0..numPages) {
            pages.add(OnboarderPageData())
        }
        return pages
    }

}
</code></pre>

<p>(I've browsed similar questions and done a lot of searching, but I believe my problem is somewhat different than these questions)</p>

<p>EDIT: Per request, full stack trace is below:</p>

<pre><code>java.lang.RuntimeException: Could not launch activity
at android.support.test.runner.MonitoringInstrumentation.startActivitySync(MonitoringInstrumentation.java:460)
at android.support.test.rule.ActivityTestRule.launchActivity(ActivityTestRule.java:354)
at android.support.test.rule.ActivityTestRule$ActivityStatement.evaluate(ActivityTestRule.java:525)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
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 android.support.test.runner.AndroidJUnit4.run(AndroidJUnit4.java:101)
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:56)
at android.support.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:384)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:2136)
Caused by: java.lang.RuntimeException: Unable to resolve activity for: Intent { act=android.intent.action.MAIN flg=0x14000000 cmp=com.redacted.redacted/.viewcontrollers.onboarding.BaseOnboardingActivityTest$SinglePageTestOnboarder }
at android.app.Instrumentation.startActivitySync(Instrumentation.java:472)
at android.app.Instrumentation.startActivitySync(Instrumentation.java:435)
at android.support.test.runner.MonitoringInstrumentation.access$101(MonitoringInstrumentation.java:96)
at android.support.test.runner.MonitoringInstrumentation$4.call(MonitoringInstrumentation.java:436)
at android.support.test.runner.MonitoringInstrumentation$4.call(MonitoringInstrumentation.java:433)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
</code></pre>
",https://stackoverflow.com/questions/51584752/espresso-unable-to-resolve-activity-for-intent-unit-testing-abstract-base-acti,"['android', 'unit-testing', 'android-activity', 'kotlin', 'android-espresso']",3983,TRUE,3,2
VueJS - Unit testing with vue-test-utils gives error - TypeError: _vm.$t is not a function,"<p>Relatively new to Vuejs and testing its components. Using vue-test-utils and jest for testing. Getting following error 
<a href=""https://i.stack.imgur.com/rQejp.jpg"" rel=""noreferrer"">test log</a></p>

<p>The .vue file consists of template, component and styling. Below is the part of the SignupLayout.vue that gets 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>&lt;style lang=""sass""&gt;
@import '../stylesheets/colors'
html[path=""/signup""], html[path=""/login""]
  height: 100%
  background-image: url(""../assets/background.jpg"")
  background-size: cover
  background-position: center
  background-repeat: no-repeat
  overflow: hidden

  #signup-layout
    #change-language-button
      .lang-menu
        color: $alto

&lt;/style&gt;</code></pre>
</div>
</div>
</p>

<p>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>import Vue from 'vue';
import Vuex from 'vuex'
import SignupLayout from '../src/components/SignupLayout.vue';
import { mount, shallow, createLocalVue } from '@vue/test-utils';

const localVue = createLocalVue()

localVue.use(Vuex)

jest.resetModules()

describe('Signup.test.js', () =&gt; {
    let cmp
    let actions
    let store
    let getters
    let state

    beforeEach(() =&gt; {


        state = {
            email: 'abc@gmail.com'
        }
 
        getters = {
            CURRENT_USER_EMAIL: state =&gt; state.email
        }

        store = new Vuex.Store({
            getters
        })


    })

    it('has received [""Login""] as the title property', () =&gt; {
        cmp = shallow(SignupLayout, {
            store,
            localVue,
            propsData: {
                title: ['Login']
            },
            data: {
                email: 'abc@dsf.com'
            }
        })
        cmp.update()
        expect(cmp.vm.title).toEqual(['Login'])
    })


})</code></pre>
</div>
</div>
</p>

<p>Confused as to what has $t got to do with sass. Any help would be appreciated. Stuck here for a while now.
Let me know if more details needed. Thanks in advance</p>
",https://stackoverflow.com/questions/48790032/vuejs-unit-testing-with-vue-test-utils-gives-error-typeerror-vm-t-is-not,"['vue.js', 'sass', 'jestjs', 'babel-jest', 'vue-test-utils']",23976,TRUE,25,5
Python unit testing a self-written API module - better in separate project?,"<p>I have 2 projects which use the same API modules, which i have written myself. These API modules encapsulate existing imported functions from pypi libraries.</p>

<p>If I have to write unit tests for my API - should the unit tests modules be present in every project which uses my API or should there be a separate project for API testing?</p>

<p>The API is one for all so logically I would open a separate project for API testing, but what if the projects get passed around between people who don't own the API testing project? Then if the implementation of the inner imported functions in the API changes unit testing will be needed.</p>

<p>I suppose the question regards API of any language but my projects are specifically in Python.</p>
",https://stackoverflow.com/questions/51915622/python-unit-testing-a-self-written-api-module-better-in-separate-project,"['python', 'unit-testing', 'python-unittest']",66,FALSE,2,1
How to provide Injected constant to service in nestjs when unit testing,"<p>I try to create unit tests for my small application. I want to test a service that uses injected configurations and other services.</p>

<pre class=""lang-ts prettyprint-override""><code>@Injectable()
export class AuthService {
        private readonly localUri: string;

        constructor(
            @Inject(CORE_CONFIG_TOKEN) private readonly coreConfig: ICoreConfig,
            @Inject(PROVIDER_CONFIG_TOKEN) private readonly providerConfig: IProviderConfig,
            private readonly _httpService: HttpService,
            private readonly _usersService: UsersService,
        ) {
            this.localUri = `http://${this.coreConfig.domain}:${this.coreConfig.port}`;
        }

        ...


        /**
         * Checks if a given email is already taken
         * @param email
         */
        async isEmailTaken(email: string): Promise&lt;boolean&gt; {
            return (await this._usersService.findUserByEmail(email)) !== undefined;
        }

        ...
</code></pre>



<p>I do not understand how to test this service. I don't know how to provide a correct TestModule provider for the injected configuration <code>@Inject(CORE_CONFIG_TOKEN) private readonly coreConfig: ICoreConfig</code></p>

<pre class=""lang-ts prettyprint-override""><code>    const testCoreConfig = '{...}'
    const module = await Test.createTestingModule({
      providers: [AuthService, {
           provide: 'CORE_CONFIG_TOKEN',
           useClass: testCoreConfig ,
      }],
    }).compile();
</code></pre>

<p>
Also I am not sure if I would need also create the other imported services. I just would like to check if they are called. And if so return mock data. This I can do but I am stuck with the module setup. </p>

<p>All samples I found so far where just services with one repository. And more or less checks if the service exists. But no checks against the logic of the implementation and the connections between the classes. </p>

<p>I hope my question is clear
Thank you</p>
",https://stackoverflow.com/questions/52497931/how-to-provide-injected-constant-to-service-in-nestjs-when-unit-testing,"['unit-testing', 'dependency-injection', 'nestjs']",5986,TRUE,2,1
Integration test on a library using UI Tests or unit testing framework?,"<p>There is an iOS library (SDK) that I have to write integration tests for. This library is being used in iOS client apps as a library, never as a standalone app. </p>

<p>I have found 2 equally good opinions on how I shall approach to writing integration tests. </p>

<ol>
<li><p>Use XCode UI test and test end-to-end integration of a library withing a sample client app. The client app will be using all features of the library. This way UI test can show me how the library integrates with a client app. </p></li>
<li><p>Use unit testing framework. The tests would be written inside the library itself. There is no need for a client app at all. The tests will be run against multiple classes to see how they integrate between themselves. </p></li>
</ol>

<p>What do you propose as the right approach? </p>
",https://stackoverflow.com/questions/50759063/integration-test-on-a-library-using-ui-tests-or-unit-testing-framework,"['ios', 'unit-testing', 'integration-testing', 'xcode-ui-testing']",392,TRUE,2,1
Inject Entity Framework Core Context into repository with ServiceStack when unit testing,"<p>I have a repository class</p>

<pre><code>public class PersonRepository : IPersonRepository
{
    private DataContext _context;

    public PersonRepository(DataContext context)
    {
        _context = context;
    }

    public List&lt;PersonDto&gt; Fetch() ......
}
</code></pre>

<p>I then have a ServiceStack PersonsService</p>

<pre><code>public class PersonsServices : Service
{
    private IPersonsRepository _personRepo;

    public PersonsServices(IPersonsRepository personRepository)
    {
        _personRepo = personRepository;
    }

    public object Any(GetPersons request)
    {
        return new GetPersonssResponse
        {
            Results = _personsRepo.Fetch()
        };
    }
}
</code></pre>

<p>My code works fine in the ServiceStack app as the DataContext is injected in by .Net Core as configured in the AddDbContext method in Startup.cs</p>

<pre><code>services.AddDbContext&lt;DataContext&gt;(x =&gt; x
    .UseSqlServer(Configuration.GetConnectionString(""DefaultConnection"")));
</code></pre>

<p>How do I do this in a unit test in conjunction with ServiceStack and using .Net Core Entity Framework?</p>

<p>I need something equivalent to the AddDbContext here.  Ultimately my goal is to create unit tests that use an in-memory or SQLite context but keep the same repository code.</p>

<p>EDIT: Here is what my unit test looks like so far.</p>

<pre><code>[TestFixture]
    public class PersonTest
    {
        private ServiceStackHost appHost;

        [SetUp]
        public void TestFixtureSetUp()
        {
            appHost = new BasicAppHost().Init();
            var container = appHost.Container;

            IConfigurationRoot configuration = new ConfigurationBuilder()
                   .SetBasePath(Directory.GetCurrentDirectory())
                   .AddJsonFile(""appsettings.json"")
                   .Build();

            var optionsBuilder = new DbContextOptionsBuilder&lt;DataContext&gt;();
            optionsBuilder
                .UseSqlite(configuration.GetConnectionString(""DefaultConnection""));
</code></pre>

<p>//HOW TO GET SERVICESTACK / FUNQ TO RESOLVE THE DataContext IN REPOSITORY???</p>

<pre><code>            **container.Register&lt;IDataContext&gt;(i =&gt; new DataContext(optionsBuilder.Options)).ReusedWithin(ReuseScope.Request);**
            container.RegisterAutoWiredAs&lt;PersonRepository, IPersonRepository&gt;();

        }

        [Test]
        public async Task GetPersons()
        {
            var service = appHost.Container.Resolve&lt;PersonsServices&gt;();

            var response = await service.Any(new GetPersons { });
            var results = (GetPersonsResponse)response;

            Assert.That(1 == 1);
        }

        [TearDown]
        public void TestFixtureTearDown()
        {
            appHost.Dispose();
        }
    }
</code></pre>
",https://stackoverflow.com/questions/53706004/inject-entity-framework-core-context-into-repository-with-servicestack-when-unit,"['unit-testing', 'entity-framework-core', 'servicestack']",697,TRUE,2,1
How to assert with anonymous type result in unit testing web API?,"<p>Hi I am writing unit test cases for the following method in my controller.</p>

<pre><code>    [HttpGet]
    [Route(""GetList"")]
    public IHttpActionResult GetAllMasterList()
    {
        var MasterList = _masterListRepo.GetAll().Select(t =&gt; new { t.MASTER_ID, t.MASTER_NAME }).OrderBy(t=&gt;t.MASTER_NAME).ToList();
        return Ok(MasterList);
    }
</code></pre>

<p>For the above method the unit test case method is as follows.</p>

<pre><code>    [TestMethod]
    public void AllMastersList()
    {
        //Arrange
        var controller = new MastersController();
        var actualResults = _masterListRepo.GetAll().ToList();

        //Act
        var actionResult = controller.GetAllMasterList();

        //Assert
        Assert.IsTrue(actionResult.GetType().GetGenericTypeDefinition() == typeof(OkNegotiatedContentResult&lt;&gt;));
        var contentExpected = actionResult as OkNegotiatedContentResult&lt;IEnumerable&lt;dynamic&gt;&gt;;
        Assert.IsNotNull(contentExpected.Content.ToList());
        Assert.AreEqual(contentExpected.Content.Count(), actualResults.Count);

    }
</code></pre>

<p>I am getting <code>contentExpected</code> as <code>null</code>. How do I cast this <code>Ok()</code> result to get the value. How to do it? </p>
",https://stackoverflow.com/questions/48163847/how-to-assert-with-anonymous-type-result-in-unit-testing-web-api,"['c#', 'unit-testing', 'asp.net-web-api2', 'mstest']",1737,TRUE,2,1
Angular 5 Unit testing throwing error for &quot;components should create &quot; test case,"<p>I am trying Angular 5 unit testing for the first time. While I already created the app then decided to run testing in it. But I am getting these errors: </p>

<pre><code>AppComponent should create the app
AppComponent should have as title 'app'
AppComponent should render title in a h1 tag
GalleryComponent should create
UploadComponent should create
</code></pre>

<p>and error details like : </p>

<pre><code>Failed: Template parse errors:
'app-upload' is not a known element:
1. If 'app-upload' is an Angular component, then verify that it is part of this module.
2. If 'app-upload' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("" class=""row""&gt;
        &lt;div class=""col-md-3"" style=""padding:5%; box-sizing: border-box""&gt;
            [ERROR -&gt;]&lt;app-upload&gt;&lt;/app-upload&gt;
        &lt;/div&gt;
        &lt;div class=""col-md-9""&gt;
""): ng:///DynamicTestModule/AppComponent.html@3:12
</code></pre>

<p>My package.json dev dependencies :</p>

<pre><code>devDependencies"": {
    ""@angular/compiler-cli"": ""^6.0.2"",
    ""@angular-devkit/build-angular"": ""~0.6.3"",
    ""typescript"": ""~2.7.2"",
    ""@angular/cli"": ""~6.0.3"",
    ""@angular/language-service"": ""^6.0.2"",
    ""@types/jasmine"": ""2.8.6"",
    ""@types/jasminewd2"": ""~2.0.3"",
    ""@types/node"": ""~8.9.4"",
    ""codelyzer"": ""~4.2.1"",
    ""jasmine-core"": ""~2.99.1"",
    ""jasmine-spec-reporter"": ""~4.2.1"",
    ""karma"": ""~1.7.1"",
    ""karma-chrome-launcher"": ""~2.2.0"",
    ""karma-coverage-istanbul-reporter"": ""~1.4.2"",
    ""karma-jasmine"": ""~1.1.1"",
    ""karma-jasmine-html-reporter"": ""^0.2.2"",
    ""protractor"": ""~5.3.0"",
    ""ts-node"": ""~5.0.1"",
    ""tslint"": ""~5.9.1""
  } 
</code></pre>

<p>Test file app.component.spec.ts</p>

<pre><code>import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () =&gt; {
  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));
  it('should create the app', async(() =&gt; {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  }));
  it(`should have as title 'app'`, async(() =&gt; {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app.title).toEqual('app');
  }));
  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('Welcome to Typito-photo-app!');
  }));
});
</code></pre>

<p>I couldn't figure out how to solve these. I haven't made any changes in spec files nor did I wrote any test cases. Shouldn't all these be running as expected according to what is described in angular documentation?</p>
",https://stackoverflow.com/questions/53618822/angular-5-unit-testing-throwing-error-for-components-should-create-test-case,"['angular', 'typescript', 'unit-testing', 'jasmine']",12265,TRUE,2,2
Implement unit testing with jasmine/karma by mocking Http Post - Angular 5,"<p>I am completely new to unit testing and I am implementing unit testing using jasmine/karma for the first time. I am facing few issues in understanding how I should implement testing by mocking for Http Post. I have gone through few solutions such as : 
<a href=""https://stackoverflow.com/questions/46420640/angular-4-unit-testing-with-jasmine-karma-with-http-post-mocking-how-to-fix"">solution1</a> and <a href=""https://stackoverflow.com/questions/44076086/how-do-i-mock-out-http-post-in-angular-without-using-testbed"">solution2</a></p>

<p>But still I have faced few issues in understanding them and have also faced few errors. </p>

<p>By following solution2 I have tried to implement as follows:</p>

<p><strong>http.service.ts</strong></p>

<pre><code> update(id,password,url){

    let content = {
        ""username"": id,
        ""password"":password,

     }

     const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type':  'application/json'
      })
    };

     return this.http.post(url,content,httpOptions).subscribe((data:any) =&gt; {

        if(data.length){
          return true;
        }
        else{
          return false;
        }
      })
</code></pre>

<p><strong>http.service.spec.ts</strong></p>

<pre><code>import { TestBed, inject } from '@angular/core/testing';
import { HttpClientModule } from '@angular/common/http'; 
import { HttpService } from './http.service';
import {HttpModule, XHRBackend,Response,ResponseOptions, Connection} from 
'@angular/http';
import {  of } from 'rxjs';
import { MockBackend } from '@angular/http/testing';

 describe('HttpService', () =&gt; {
 let mockbackend, service;
 beforeEach(() =&gt; {TestBed.configureTestingModule({
 imports:[HttpClientModule, HttpModule],
 providers:[{
 provide: XHRBackend, useclass: MockBackend
 }]

 })
 });

  beforeEach(inject([ XHRBackend], (_service, 
  _mockbackend) =&gt; {
  service = _service;
  mockbackend = _mockbackend;
  }));

  it('post method is successfull',() =&gt;{
  const status = 'success';
  const username = '5555555';
  const password = 'test';
  const currentUserExpected = JSON.stringify({status:status});
  const response = { status : status};
  const responseOptions = new ResponseOptions();
  responseOptions.body = JSON.stringify(response);
  mockbackend.connections.subscribe(connection =&gt;{
  connection.mockRespond(new Response(responseOptions));
  });
  service.update(username,password).subscribe(respond =&gt;{
  expect(respond).toEqual(true)
  })
   })
</code></pre>

<p>The error I am receiving is this:</p>

<p><strong>Error</strong></p>

<blockquote>
  <p>Cannot read property 'connections' of undefined</p>
</blockquote>

<p>Can someone please help me out in understanding where I am going wrong. </p>

<p>Also I would like to receive reference to any documentation which can help me better understand this. </p>
",https://stackoverflow.com/questions/53494266/implement-unit-testing-with-jasmine-karma-by-mocking-http-post-angular-5,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",1988,TRUE,2,1
vue.js unit testing with Jest : Should I mock the HTLL5 audio element?,"<p>Testing an AudioPlayer vue component, which contains the HTML5  element , I wonder how to write my specs with Jest .</p>

<p>template</p>

<pre><code>    &lt;audio id=""player"" ref=""player"" @ended=""ended"" @canplay=""canPlay"" :src=""file""&gt;&lt;/audio&gt;
</code></pre>

<p>If I use the following wrapper </p>

<pre><code>const wrapper = mount(AudioPlayer, {
      propsData: {
        autoPlay: false,
        file,
        ended,
        canPlay
      }
    });
</code></pre>

<p>How should I set the file property ? ( I want to pass an audio file from src/assets/audio/mysong.mp3 )</p>

<p>If I use shallowMount instead, should I mock the audio element ? which way ... as the audio element handles play(), pause(), mute() ... I am a little bit lost and I cannot find any post related to testing such component...</p>
",https://stackoverflow.com/questions/52139300/vue-js-unit-testing-with-jest-should-i-mock-the-htll5-audio-element,"['unit-testing', 'vue.js', 'jestjs', 'vue-test-utils']",1135,FALSE,2,2
Canvas Issues when Unit Testing Phaser and TypeScript with Mocha on Node,"<p>I'm currently developing a TypeScript/Phaser (2.6.2) project and attempting to run unit tests, set up to use Mocha and Chai (with <code>ts-node/register</code> and <code>jsdom-global/register</code>) on a Node environment with <code>node-canvas</code> installed using the <a href=""https://www.npmjs.com/package/canvas"" rel=""nofollow noreferrer"">installation instructions</a> for Windows.</p>

<p>The project builds using webpack and runs in the browser correctly, as does Compodoc, and tests that do not require Phaser are also able to execute and pass. Example class/test:</p>

<p><strong>phaser.game.class.ts</strong>:</p>

<pre><code>import { Phaser } from 'phaser'

export class Game extends Phaser.Game {
    constructor() { super(1280, 720, Phaser.AUTO, 'game') }
}
</code></pre>

<p><strong>phaser.game.class.spec.ts</strong>:</p>

<pre><code>import 'mocha'
import { expect } from 'chai'
import { Game } from './phaser.game.class'

describe('Game', () =&gt; {
    it('should be defined', () =&gt; {
        expect(Game).to.exist
    })
})
</code></pre>

<p>However when running tests that do import Phaser I receive an error:</p>

<pre><code> context.drawImage(magenta, 0, 0);
            ^
 TypeError: Expected object, number and number
</code></pre>

<p>Looking at <a href=""https://github.com/Automattic/node-canvas/issues/487"" rel=""nofollow noreferrer"">this issue</a> I believe it may be related to Phaser using a different canvas build to that which is installed with <code>node-canvas</code>, but I cannot force the use of a certain <code>node-canvas</code> version (as is described there) as ultimately this will be run in a browser - <strong>is this the case, and is there any method to ensure the canvas version just for the tests?</strong></p>

<p>Alternatively I've looked into using <a href=""https://github.com/byondreal/phaser-mock"" rel=""nofollow noreferrer"">phaser-mock</a> and <a href=""https://github.com/thlorenz/proxyquire"" rel=""nofollow noreferrer"">proxyquire</a> (which I would prefer for simply testing isolated class logic), but am experiencing other issues and am unable to find an example implementation combining the two.</p>

<p>Any information would be much appreciated!</p>
",https://stackoverflow.com/questions/48790987/canvas-issues-when-unit-testing-phaser-and-typescript-with-mocha-on-node,"['node.js', 'typescript', 'html5-canvas', 'mocha.js', 'phaser-framework']",469,FALSE,2,0
angular 5 unit testing- getting error &#39;Cannot read property offsetHeight of null&#39;,"<p>when I doing unit test on my app it shows following error</p>

<pre><code>TypeError: Cannot read property 'offsetHeight' of null
</code></pre>

<p>In my application I am using  below code to get the height of my div element</p>

<pre><code>totalHeight= (document.getElementById(""rcyc-page-header"") as HTMLElement).offsetHeight +
                            (document.querySelector(""nav.menu-wrapper.brand-nav-wrapper"") as HTMLElement).offsetHeight;
</code></pre>

<p>when I print the value of variable 'totalheight' it displays correctly,then why it shows this error? </p>
",https://stackoverflow.com/questions/50368109/angular-5-unit-testing-getting-error-cannot-read-property-offsetheight-of-null,"['angular5', 'karma-jasmine']",406,FALSE,1,0
How do I force call a SQLException when Unit Testing in Java?,"<p>I am running Java tests on JUnit 4.xx. I'm trying to force run a SQLException from the try block. I've ran Mockito in many different ways but I don't get the result that I want. </p>

<p><strong>Here is my main file:</strong></p>

<pre><code>public boolean close()   {

    if (connection == null) {
        throw new IllegalStateException(""Connection never initialized!"");
    }

    try {
        connection.close();
        return true;
    }

    catch (SQLException e)
    {
        LOGGER.logp(Level.INFO, CLASS_NAME, ""close"", e.getMessage());
        return false;
    }

}
</code></pre>

<p><strong>Here is my test file:</strong></p>

<pre><code>@Test
public void testFail2() throws SQLException {

    JDBCConnection spyConnect = mock(JDBCConnection.class);

    given(spyConnect.getConnection()).willAnswer(invocationOnMock -&gt; new SQLException());

    assertFalse(spyConnect.close());
}
</code></pre>

<p>In summary, how do I get the catch block to get executed so that I get 100% line coverage for my overall program?
Thanks for the help in advance.</p>
",https://stackoverflow.com/questions/50806673/how-do-i-force-call-a-sqlexception-when-unit-testing-in-java,"['java', 'unit-testing', 'junit', 'mockito', 'sqlexception']",2278,FALSE,1,1
laravel unit testing with factories Unable to locate factory with name [default],"<p>I try to create a factory for one of my models in laravel unit test</p>

<pre><code>use Illuminate\Support\Collection;
use phpDocumentor\Reflection\Types\Parent_;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\User;
use Illuminate\Auth;
use App\Role;
use App\AppName\HolidaysEmployees;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class TestApiCalls extends TestCase
{


    public function setUp()
    {
        parent::setUp();

        $this-&gt;user = factory(User::class)-&gt;create([
            'firstname' =&gt; 'RA',
            'lastname' =&gt; 'Tester',
            'password' =&gt; bcrypt('tester'),
            'email' =&gt; 'ra@tester.com'
        ]);

        $this-&gt;holidays = factory(HolidaysEmployees::class)-&gt;make();
    }

}
</code></pre>

<p>but when I run the test I keep getting</p>

<pre><code>InvalidArgumentException: Unable to locate factory with name [default] [App\MyName\HolidaysEmployees].
</code></pre>

<p>What I do wrong in this case?</p>
",https://stackoverflow.com/questions/52662931/laravel-unit-testing-with-factories-unable-to-locate-factory-with-name-default,"['laravel', 'model', 'phpunit', 'factory']",436,FALSE,1,1
unit testing extension function and mocking the other methods of the class,"<p>I am writing an extension function adding some retry capabilities to <code>AmazonKinesis.putRecords</code>. In my extension method i do some logic and some calls to the original <code>putRecords</code> method:</p>

<pre><code>fun AmazonKinesis.putRecordsWithRetry(records: List&lt;PutRecordsRequestEntry&gt;, streamName: String) {
    //...
    val putRecordResult = this.putRecords(PutRecordsRequest().withStreamName(streamName).withRecords(records))
   //...
}
</code></pre>

<p>From a unit test point of view I am finding it hard to see how I should mock the call to <code>this.putRecords</code></p>

<p>I am using <code>com.nhaarman.mockitokotlin2.*</code></p>

<pre><code>val successfulRequest = PutRecordsResultEntry().withErrorCode(null);

class KinesisExtensionTest : StringSpec({
    val testRecords = ArrayList&lt;PutRecordsRequestEntry&gt;()
    testRecords.add(PutRecordsRequestEntry().withPartitionKey(""iAmABunny"").withData(ByteBuffer.wrap(""aaa"".toByteArray()))
    )

    val kinesis = mock&lt;AmazonKinesis&gt;{
        on { putRecordsWithRetry(testRecords, ""/dev/null"") }.thenCallRealMethod()
        on { putRecords(any()) }.thenReturn(PutRecordsResult().withRecords(listOf(successfulRequest, successfulRequest)))
    }


    ""can write a record"" {
        kinesis.putRecordsWithRetry(testRecords, ""/dev/null"")
        verify(kinesis).putRecord(any())
    }
})
</code></pre>

<p>The <code>putRecordResult</code> is always null</p>
",https://stackoverflow.com/questions/52207237/unit-testing-extension-function-and-mocking-the-other-methods-of-the-class,"['kotlin', 'kotlin-extension']",1651,TRUE,1,1
unit testing in spring boot giving error when exception thrown in service,"<p>So, I have this unit test that I need to run. </p>

<pre><code>@MockBean
private AppServiceImpl appService;


@Test
public void shouldThrowExceptionWhenAppIdIsNull() throws Exception {
    File inputFile = this.getJsonFile();
    RequestDto requestDto = objectMapper.readValue(inputFile.getAbsoluteFile(),
            RequestDto.class);
    AppData appData = requestDto.getAppData();
    appData.setAppId(null);
    requestDto.setAppData(appData);
    when(appService.getUrl(requestDto, ""header"")).thenThrow(new RequestNotValidException());
    String payload = objectMapper.writeValueAsString(requestDto);
    this.mockMvc.perform(post(Base_URL + ""app/requesturl"")
            .contentType(contentType).content(payload).header(this.Header, ""header""))
            .andExpect(status().is4xxClientError());
}
</code></pre>

<p>Interface for service:</p>

<p>SO when I run this test, it throws an exception and doesn't actually assert the test here. </p>

<p>I have added <code>@ResponseStatus(HttpStatus.BAD_REQUEST)</code> on top of <code>RequestNotValidException</code> and it extends <code>RunTimeException</code></p>

<p>And in the second test case, I get empty response. I tried this API vis Postman and I get the response. Everything works fine there. </p>

<pre><code>@Test
public void getCardRegistration() throws Exception {
    File inputFile = this.getJsonFile();
    RequestDto requestDto = objectMapper.readValue(inputFile.getAbsoluteFile(), RequestDto.class);
    ResponseDto responseDto = new ResponseDto();
    responseDto.setURL(AuthUtils.randomStringToken(35));
    given(appService.getRegistrationUrl(requestDto, ""header"")).willReturn(responseDto);
    String payload = objectMapper.writeValueAsString(requestDto);
    MvcResult mvcResult = this.mockMvc.perform(post(Base_URL + ""app/requesturl"")
            .contentType(contentType).content(payload).header(this.Header, ""header""))
            .andReturn();
    String contentAsString = mvcResult.getResponse().getContentAsString();
}
</code></pre>

<p>Controller content:</p>

<pre><code>    @Autowired
    IAppService appService;

    @RequestMapping(value = ""/app/requesturl"", method = RequestMethod.POST)
public ResponseDto getCardsRegistration(@RequestBody @Valid RequestDto requestDto, @RequestHeader(value=""X-App-Name"", required = true) String header) throws RequestNotValidException, JsonProcessingException {
    log.info(""Request received in controller: ""+ mapper.writeValueAsString(cardRegistrationRequestDto));
    log.info(""Header value: ""+ header);

    return this.appService.getRegistrationUrl(requestDto, header);
}
</code></pre>

<p>Test Class:  </p>

<pre><code>@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class AppRestControllerTest {

    protected String Base_URL = ""/app"";

    protected String Header = ""X-App-Name"";

    protected MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(),
            MediaType.APPLICATION_JSON.getSubtype(),
            Charset.forName(""utf8""));

    @Autowired
    protected MockMvc mockMvc;

    protected ObjectMapper objectMapper = new ObjectMapper();

    @MockBean
    private AppServiceImpl appService;

    @Mock
    private AppRegistrationRepository appRegistrationRepository;


        @Before
    public void setUp() throws Exception {
        MapperFacade mapperFacade = new DefaultMapperFactory.Builder().build().getMapperFacade();
        appService = new AppServiceImpl(appRegistrationRepository, mapperFacade);
    }
</code></pre>

<p>What did I miss here?</p>
",https://stackoverflow.com/questions/51060493/unit-testing-in-spring-boot-giving-error-when-exception-thrown-in-service,"['java', 'spring', 'unit-testing', 'spring-boot']",1019,TRUE,1,1
TypeError: Cannot read property &#39;query&#39; of undefined while unit testing Angular 6,"<p>I am learning unit testing for Angular 6 using karma and Jasmine. I have tried a simple unit test of a text present inside <code>&lt;p&gt;</code> tag. Here's my HTML code:</p>

<pre><code>&lt;p&gt;
  dash works!
&lt;/p&gt;
</code></pre>

<p>And also in my dash.component.spec.ts, I am giving a test code like this:</p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { DashComponent } from './dash.component';
import { DebugElement } from '@angular/core';
import { By } from '@angular/platform-browser';

describe('DashComponent', () =&gt; {
  let component: DashComponent;
  let fixture: ComponentFixture&lt;DashComponent&gt;;
  let de: DebugElement;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ DashComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(DashComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
    it('should have a p tag of `dash works!`', () =&gt; {
        expect(de.query(By.css('p')).nativeElement.innerText).toBe('dash works!');
    });
});
</code></pre>

<p>After doing ng test, I am getting this error. please suggest me how to proceed.</p>

<pre><code>TypeError: Cannot read property 'query' of undefined
    at UserContext.eval (./src/app/dash/dash.component.spec.ts?:32:19)
    at ZoneDelegate.invoke (./node_modules/zone.js/dist/zone.js?:387:26)
    at ProxyZoneSpec.onInvoke (./node_modules/zone.js/dist/zone-testing.js?:287:39)
    at ZoneDelegate.invoke (./node_modules/zone.js/dist/zone.js?:386:32)
    at Zone.run (./node_modules/zone.js/dist/zone.js?:137:43)
    at runInTestZone (./node_modules/zone.js/dist/zone-testing.js?:508:34)
    at UserContext.eval (./node_modules/zone.js/dist/zone-testing.js?:523:20)
    at attempt (http://localhost:9876/absoluteD:/thbs/coe/iot/2.POC/Unit%20Testing/angular-unit-testing/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?0b1eaf7a13cae32191eadea482cfc96ae41fc22b:4478:46)
    at ZoneQueueRunner.QueueRunner.run (http://localhost:9876/absoluteD:/thbs/coe/iot/2.POC/Unit%20Testing/angular-unit-testing/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?0b1eaf7a13cae32191eadea482cfc96ae41fc22b:4402:20)
    at runNext (http://localhost:9876/absoluteD:/thbs/coe/iot/2.POC/Unit%20Testing/angular-unit-testing/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?0b1eaf7a13cae32191eadea482cfc96ae41fc22b:4446:20)
</code></pre>
",https://stackoverflow.com/questions/52660391/typeerror-cannot-read-property-query-of-undefined-while-unit-testing-angular,"['angular', 'unit-testing', 'karma-jasmine', 'angular6']",4119,TRUE,1,2
Angular 6 Unit testing : how to use test.ts for running karma tests,"<p>Under my <strong>Angular 6</strong> app , i ve this config</p>

<p><strong>karma.conf.js:</strong></p>

<pre><code>// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma')
    ],
    client:{
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    mime: {
      'text/x-typescript': ['ts','tsx']
    },
    coverageIstanbulReporter: {
      dir: require('path').join(__dirname, 'coverage'),
      reports: [ 'html', 'lcovonly' ],
      fixWebpackSourcePaths: true
    },

    reporters: config.angularCli &amp;&amp; config.angularCli.codeCoverage
      ? ['progress', 'coverage-istanbul']
      : ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    browserDisconnectTimeout: 10000,
    browserDisconnectTolerance: 3,
    browserNoActivityTimeout: 60000,
    flags: [
      '--disable-web-security',
      '--disable-gpu',
      '--no-sandbox'
    ],
    singleRun: true,
    concurrency: Infinity
  });
};
</code></pre>

<p>An i ve a file , test.ts ; which is supposed to configurate the test running :</p>

<pre><code>// This file is required by karma.conf.js and loads recursively all the .spec and framework files

import 'zone.js/dist/long-stack-trace-zone';
import 'zone.js/dist/proxy.js';
import 'zone.js/dist/sync-test';
import 'zone.js/dist/jasmine-patch';
import 'zone.js/dist/async-test';
import 'zone.js/dist/fake-async-test';
import { getTestBed } from '@angular/core/testing';
import {
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';

// Unfortunately there's no typing for the `__karma__` variable. Just declare it as any.
declare var __karma__: any;
declare var require: any;

// Prevent Karma from running prematurely.
__karma__.loaded = function () {};

// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting()
);
// Then we find all the tests.
const context = require.context('./', true, /my-component.component.spec.ts/);
// And load the modules.
context.keys().map(context);
// Finally, start Karma to run the tests.
__karma__.start();
</code></pre>

<p>i may let me filter file to be tested </p>

<p>for example i want to run this one : <code>my-component.component.spec.ts</code></p>

<p>But that it not running , and it seems that it lacks some config in the <strong>karma.conf</strong> to run the <strong>test.ts</strong></p>

<p><strong>Sugesstions ?</strong></p>
",https://stackoverflow.com/questions/52778108/angular-6-unit-testing-how-to-use-test-ts-for-running-karma-tests,"['javascript', 'angular', 'typescript', 'karma-jasmine', 'karma-runner']",6121,TRUE,1,1
ConnectionString Property Not initialized error occurded while unit testing business logic function,"<p>I am trying to perform unit test on a business logic function of a 3-tier Windows form C# application. But I'm getting this error:</p>

<blockquote>
  <p>Message: Test method Cognizant.Dotnet.EMS.UnitTest.BusinessAddEmpDtlsTest.TestBusinessAddEmpDtls15 threw exception: 
      System.InvalidOperationException: The ConnectionString property has not been initialized.</p>
</blockquote>

<p>Now I'm new to unit testing. I have created a visual studio unit test project in my solution. Here is my business layer or tier class:</p>

<pre><code>public class BusinessAddEmployee {
    DataAddEmployee objDataAddEmp;
    public BusinessAddEmployee()
    {            
        objDataAddEmp = new DataAddEmployee();
    }
    public int BusinessAddEmpDetails(EntityAddEmployee objEntityAddEmployee) {          
        SqlParameter[] objDataParams = new SqlParameter[5];
        objDataParams[0] = new SqlParameter(""@EmpId"", SqlDbType.Int) {Value = objEntityAddEmployee.EmpID};
        objDataParams[1] =
            new SqlParameter(""@EmpName"", SqlDbType.VarChar, 25) {Value = objEntityAddEmployee.EmpName};
        objDataParams[2] =
            new SqlParameter(""@DeptName"", SqlDbType.VarChar, 25) {Value = objEntityAddEmployee.DepartmentName};
        objDataParams[3] =
            new SqlParameter(""@Location"", SqlDbType.VarChar, 25) {Value = objEntityAddEmployee.Location};
        objDataParams[4] = 
            new SqlParameter(""@ContactNumber"", SqlDbType.BigInt) {Value = objEntityAddEmployee.ContactNo};
        var result = objDataAddEmp.DataAddEmployeeDetails(objDataParams);
        return result;
    }
}
</code></pre>

<p>And here is the Entity layer/tier class for <code>AddEmployee</code></p>

<pre><code>public class EntityAddEmployee {
    public Int32? EmpID { get; set; }
    public string EmpName { get; set; }
    public string DepartmentName { get; set; }
    public string Location { get; set; }
    public long? ContactNo { get; set; }        
}
</code></pre>

<p>The data layer class is this:</p>

<pre><code>public class DataAddEmployee
{
    private static string conStr;
    private SqlConnection objConnnection;
    SqlCommand objCommand;        
    public DataAddEmployee()
    {
        conStr = ConfigurationManager.AppSettings[""Connection""];
        objConnnection = new SqlConnection(conStr);            
    }
    public int DataAddEmployeeDetails(SqlParameter[] objParams) {
        objCommand = new SqlCommand(""USPEmpDtls"", objConnnection);
        objCommand.CommandType = CommandType.StoredProcedure;
        objCommand.Parameters.AddRange(objParams);
        objConnnection.Open();**//This line throws the exception**    
        int result;
        try
        {
            result = objCommand.ExecuteNonQuery();
        }
        catch (Exception e)
        {
            throw new InvalidOperationException();
        }           
        objConnnection.Close();
        return result;
    }       
}
</code></pre>

<p>The unit test class is given below:</p>

<pre><code>[TestClass]
public class BusinessAddEmpDtlsTest
{
    private BusinessAddEmployee objBusinessAddEmp;
    private EntityAddEmployee objEntityAddEmp;

    [TestInitialize]
    public void Init()
    {
        objBusinessAddEmp = new BusinessAddEmployee();
        objEntityAddEmp = new EntityAddEmployee();

    }
    [TestMethod]        
    public void TestBusinessAddEmpDtls15()
    {
        objEntityAddEmp.EmpID = 11112;
        objEntityAddEmp.EmpName = ""John Die"";
        objEntityAddEmp.DepartmentName = ""Audit"";
        objEntityAddEmp.Location = ""Dhaka"";
        objEntityAddEmp.ContactNo = Convert.ToInt64(01999999999);           
        Assert.AreEqual(1, objBusinessAddEmp.BusinessAddEmpDetails(objEntityAddEmp));//**I have compared with 1 since it is a valid operation**//           
    }
}
</code></pre>

<p>The connection string works fine since I have successfully inserted data into database from the <code>WindowsForm</code> I created. Everything works fine except the unit test function.</p>

<p>Can anyone tell me what is the problem here why is the exception is occurring? I have initialized the connection string in the data layer class constructor.</p>
",https://stackoverflow.com/questions/49569735/connectionstring-property-not-initialized-error-occurded-while-unit-testing-busi,"['c#', 'unit-testing', 'ado.net', 'connection-string', 'n-tier-architecture']",1445,TRUE,1,1
Integrated Unit Testing is not running in ASP.NET core MVC/Web API,"<p>I am developing a web API using ASP.Net core. I am doing integrated testing to my project. I am following this link, <a href=""https://koukia.ca/integration-testing-in-asp-net-core-2-0-51d14ede3968"" rel=""nofollow noreferrer"">https://koukia.ca/integration-testing-in-asp-net-core-2-0-51d14ede3968</a>. This is my code.</p>
<p>I have the controller to be tested in the thegoodyard.api project.</p>
<pre><code>namespace thegoodyard.api.Controllers
{
   [Produces(&quot;application/json&quot;)]
   [Route(&quot;api/category&quot;)]
   public class CategoryController: Controller
   {
      [HttpGet(&quot;details/{id}&quot;)]
      public string GetCategory(int id = 0)
      {
         return &quot;This is the message: &quot; + id.ToString();
      }
   }
}
</code></pre>
<p>I added a new unit test project called thegoodyard.tests to the solution. I added a TestServerFixture class with the following definition</p>
<pre><code>namespace thegoodyard.tests
{
    public class TestServerFixture : IDisposable
    {
      private readonly TestServer _testServer;
      public HttpClient Client { get; }

      public TestServerFixture()
      {
         var builder = new WebHostBuilder()
                .UseContentRoot(GetContentRootPath())
                .UseEnvironment(&quot;Development&quot;)
                .UseStartup&lt;Startup&gt;();  // Uses Start up class from your API Host project to configure the test server

         _testServer = new TestServer(builder);
         Client = _testServer.CreateClient();
      }

      private string GetContentRootPath()
      {
         var testProjectPath = PlatformServices.Default.Application.ApplicationBasePath;
         var relativePathToHostProject = @&quot;..\..\..\..\..\..\thegoodyard.api&quot;;
         return Path.Combine(testProjectPath, relativePathToHostProject);
      }

      public void Dispose()
      {
         Client.Dispose();
         _testServer.Dispose();
      }
   }
}
</code></pre>
<p>Then again in the test project, I created a new class called, CategoryControllerTests with the following definition.</p>
<pre><code>namespace thegoodyard.tests
{
    public class CategoryControllerTests: IClassFixture&lt;TestServerFixture&gt;
   {
      private readonly TestServerFixture _fixture;

      public CategoryControllerTests(TestServerFixture fixture)
      {
         _fixture = fixture;
      }

      [Fact]
      public async Task GetCategoryDetai()
      {
         var response = await _fixture.Client.GetAsync(&quot;api/category/details/3&quot;);

         response.EnsureSuccessStatusCode();

         var responseString = await response.Content.ReadAsStringAsync();

         bool containMessage = false; //responseString.Contains(&quot;This is the message: 3&quot;); - I commented on purpose to make the test fails.
         Assert.True(containMessage);
      }
   }
}
</code></pre>
<p>Then I right on the test method and clicked run tests in the option to run the test. But none of the tests was run. This is the output.
<a href=""https://i.stack.imgur.com/JR150.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/JR150.png"" alt=""enter image description here"" /></a></p>
<p>What is missing in my code? How can I get my integrated test running?</p>
",https://stackoverflow.com/questions/52356948/integrated-unit-testing-is-not-running-in-asp-net-core-mvc-web-api,"['unit-testing', 'asp.net-core', '.net-core']",2324,TRUE,1,3
unable to set property values in camel xml route during unit testing,"<p>I am novice to apache camel dev (3 months). I am using xml based (not java DSL) and trying to develop a unit test. But I am not able to perform two things</p>

<ol>
<li>Unable to set value for the property key in the xml InOut node</li>
<li>I am not able use weavbyToString to mock the InOut uri as it shows no output matches the pattern. So i am forced to use weaveById by providing id for InOut node. But my requirement is to perform weave by using pattern only.</li>
</ol>

<h2>Route XML Code</h2>

<pre><code>&lt;route id=""testID""&gt;
      &lt;from uri=""direct:getCustDetails"" /&gt;
       &lt;to uri=""velocity:META-INF/templates/manage/input.vm"" /&gt;
        &lt;inOut uri=""{{url}}/custinquiry?httpClient.soTimeout={{timeout}}&amp;amp;bridgeEndpoint=true&amp;amp;throwExceptionOnFailure=false"" id=""cardEnquiryService""/&gt;
         &lt;to uri = ""bean:responseProcessor""&gt;

&lt;/route&gt;
</code></pre>

<h2>Java part</h2>

<pre><code>ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(""classpath:META-INF/routes/route.xml"");
        PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
        Properties prop = new Properties();
        prop.setProperty(""url"", ""http://127.0.0.1:xxxx/server2"");
        prop.setProperty(""timeout"", ""50000000"");
        configurer.setProperties(prop);
        appContext.addBeanFactoryPostProcessor(configurer);
        CamelContext camelContext =        SpringCamelContext.springCamelContext(appContext,false);

        try 
                {
                    ProducerTemplate template = camelContext.createProducerTemplate();
                    //camelContext.start();
                    Exchange ex = new DefaultExchange(camelContext);
                    final InputStream in = ResponseTest.class
                            .getResourceAsStream(""/Cust_Inquiry_Res.json"");
                    camelContext.getRouteDefinition(""testID"").adviceWith(camelContext, new AdviceWithRouteBuilder() {
                        @Override
                        public void configure() throws Exception {
                            System.out.println(""Inside configure method"");
                            weaveById(""cardEnquiryService"").replace()

/*   //Not working
    weaveByToString("".*httpClient.*"").replace() */
                            .process(new Processor() {
                                public void process(Exchange exchange) throws Exception {
                                    exchange.getIn().setBody(in);
                                }
                            });
                          }
                    }); 
                    camelContext.start();
</code></pre>

<p>When I start the camel-context code using the above code I get following error</p>

<p>Caused by:</p>

<pre><code> java.lang.IllegalArgumentException: PropertiesComponent with name properties must be defined in CamelContext to support property placeholders. Property with key [url] not found in properties from text: {{url}}/custinquiry?httpClient.soTimeout={{timeout}}&amp;bridgeEndpoint=true&amp;throwExceptionOnFailure=false
    at org.apache.camel.component.properties.DefaultPropertiesParser$ParsingContext.getPropertyValue(DefaultPropertiesParser.java:269)
    at org.apache.camel.component.properties.DefaultPropertiesParser$ParsingContext.readProperty(DefaultPropertiesParser.java:155)
    at org.apache.camel.component.properties.DefaultPropertiesParser$ParsingContext.doParse(DefaultPropertiesParser.java:114)
    at org.apache.camel.component.properties.DefaultPropertiesParser$ParsingContext.parse(DefaultPropertiesParser.java:98)
    at org.apache.camel.component.properties.DefaultPropertiesParser.parseUri(DefaultPropertiesParser.java:63)
    at org.apache.camel.component.properties.PropertiesComponent.parseUri(PropertiesComponent.java:177)
    at org.apache.camel.component.properties.PropertiesComponent.parseUri(PropertiesComponent.java:128)
    at org.apache.camel.impl.DefaultCamelContext.resolvePropertyPlaceholders(DefaultCamelContext.java:1267)
    at org.apache.camel.model.ProcessorDefinitionHelper.resolvePropertyPlaceholders(ProcessorDefinitionHelper.java:633)
    at org.apache.camel.model.ProcessorDefinition.createOutputsProcessor(ProcessorDefinition.java:410)
    at org.apache.camel.model.ProcessorDefinition.createOutputsProcessor(ProcessorDefinition.java:159)
    at org.apache.camel.model.ProcessorDefinition.createChildProcessor(ProcessorDefinition.java:178)
    at org.apache.camel.model.OtherwiseDefinition.createProcessor(OtherwiseDefinition.java:47)
    at org.apache.camel.model.ProcessorDefinition.createProcessor(ProcessorDefinition.java:460)
    at org.apache.camel.model.ChoiceDefinition.createProcessor(ChoiceDefinition.java:139)
    at org.apache.camel.model.ProcessorDefinition.makeProcessor(ProcessorDefinition.java:500)
    at org.apache.camel.model.ProcessorDefinition.addRoutes(ProcessorDefinition.java:213)
    at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:942)
    ... 51 more
</code></pre>
",https://stackoverflow.com/questions/51094441/unable-to-set-property-values-in-camel-xml-route-during-unit-testing,"['java', 'properties', 'apache-camel']",1166,FALSE,1,0
Unit Testing (Angular) Error: Cannot call Promise.then from within a sync test,"<p>i got a problem when im writing test in angular the fact that i wanna test routing of button but it got error like this</p>

<p><strong>this is my homepage.component.spec.ts file</strong> (this is not app.component.spec.ts file)</p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { DebugElement } from '@angular/core';
import { HomepageComponent } from './homepage.component';
import { Router } from '@angular/router';
import { inject } from '@angular/core/src/render3';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from '../app.component';
import { RegisterpageComponent } from'../registerpage/registerpage.component';
import { Location } from '@angular/common';

describe('HomepageComponent', () =&gt; {
  let component: HomepageComponent;
  let fixture: ComponentFixture&lt;HomepageComponent&gt;;

beforeEach(async(() =&gt; {
  TestBed.configureTestingModule({
  imports: [RouterTestingModule],
  declarations: [ HomepageComponent,
                  AppComponent,
                  RegisterpageComponent ]
})
.compileComponents();
}));


beforeEach(() =&gt; {
  fixture = TestBed.createComponent(HomepageComponent);
  component = fixture.componentInstance;
  fixture.detectChanges();
});

it('should create', () =&gt; {
  expect(component).toBeTruthy();
});

// tslint:disable-next-line:prefer-const
let location: Location;
// tslint:disable-next-line:prefer-const
let router: Router;
// tslint:disable-next-line:prefer-const

router = TestBed.get(Router);
location = TestBed.get(Location);

router.initialNavigation();

it('navigate to ""registerpage""', () =&gt; {
  router.navigate(['register']);
  expect(location.path()).toBe('/register');
 });
});
</code></pre>

<p><strong>this is app-routing.module.ts file</strong></p>

<pre><code>import { ApplicationRef, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Routes, RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { HomepageComponent } from './homepage/homepage.component';
import { RegisterpageComponent } from './registerpage/registerpage.component';

const routes: Routes = [
    { path: '',
    //   redirectTo: '/home',
         component: HomepageComponent,
         pathMatch: 'full' },


     { path: 'register',
       component: RegisterpageComponent}
  // { path: '**',
  //   component: PagenotfoundComponent }
];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule],
})
export class AppRoutingModule { }
</code></pre>

<p>i have stuck with this for a week and seem like no hope please help me! Thanks</p>

<p>ps.actually im confusing that i have to write test code in AppComponent.spec.ts file or not</p>
",https://stackoverflow.com/questions/49771751/unit-testing-angular-error-cannot-call-promise-then-from-within-a-sync-test,"['angular', 'unit-testing']",7570,TRUE,1,1
Unit Testing VueJS - Checking for an element with a certain class name,"<p>I'm struggling to get a simple unit test working in a VueJS app.</p>

<p>I'm basically trying to test the template and check if it contains a div element with a class name of ""version"" but the test keeps failing with an <code>undefined is not a constructor (evaluating 'expect(component.$el.querySelector('div')).to.have.className('version')').</code> error.</p>

<p>It's a simple component with this as the template:</p>

<pre><code>&lt;template&gt;
    &lt;div&gt;
        &lt;div class=""version""&gt;
            &lt;label&gt;Version {{ version }}&lt;/label&gt;
        &lt;/div&gt;
        &lt;div class=""activityBanner""&gt;
            &lt;label&gt;{{ user }}&lt;/label&gt;
            &lt;router-link id=""logout"" :to=""{name: 'logout' }""&gt;
                &lt;label&gt;Logout&lt;/label&gt;
            &lt;/router-link&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/template&gt;
</code></pre>

<p>Here is the unit test I'm working with:</p>

<pre><code>import Vue from 'vue';
import router from '@/router';
import VueRouter from 'vue-router';
import Navigation from '@/components/Navigation';

describe('Navigation.vue', () =&gt; {
  // Nice little helper to return our component within a div
  const getComponent = data =&gt; {
    const Constructor = Vue.extend(Navigation);

    return new Constructor({
      router
    }).$mount();
  };

  describe('Component', () =&gt; {
    it('should have a property ""name""', () =&gt; expect(Navigation.name).to.be.a('string'));

    it('should have a property ""name"" set to ""Navigation""', () =&gt; expect(Navigation.name).to.equal('Navigation'));

    it('should have a data hook', () =&gt; expect(Navigation.data).to.be.a('function'));

    it('should have a default ""currentView"" set to ""profileTable""', () =&gt; {
      const defaultData = Navigation.data();

      expect(defaultData.currentView).to.equal('profileTable');
    });

    it('should have a default ""version"" set to ""0.5""', () =&gt; {
      const defaultData = Navigation.data();

      expect(defaultData.version).to.equal(0.5);
    });

    it('should have a default ""user"" set to ""Bob Barker""', () =&gt; {
      const defaultData = Navigation.data();

      expect(defaultData.user).to.equal('Bob Barker');
    });
  });

  describe('Template', () =&gt; {
    Vue.use(VueRouter);

    it('should render correctly', () =&gt; {
      const component = getComponent();

      expect(component.$el);
    });

    it('should have a ""div"" element', () =&gt; {
      const component = getComponent();

      expect(component.$el.querySelectorAll('div').length);
    });

    it('should have a element with a ""className"" set to ""version""', () =&gt; {
      const component = getComponent();

      expect(component.$el.querySelector('div')).to.have.className('version');
    });
  });
});
</code></pre>

<p>What are I doing wrong?</p>
",https://stackoverflow.com/questions/48662851/unit-testing-vuejs-checking-for-an-element-with-a-certain-class-name,"['unit-testing', 'vue.js']",5363,TRUE,1,1
Injected mocked dependency into ViewModel while unit testing not behaving as expected,"<p>I'm trying to do unit testing in view model by using Moq and dependency injection</p>

<p>Basically, I have model: Class <code>PersonModel</code> containing properties <code>FirstName</code>, <code>LastName</code>, <code>Input</code>, <code>Output</code> - no logic or any methods in here.</p>

<p>In my <code>ViewModel</code>, I have:</p>

<pre><code>public class ViewModel
{
    private IGetService getService;
    private Personmodel personModel;
    private string result;

    public ViewModel(IGetService getService)
    {
        personModel= new Personmodel ();
        this.getService = getService;
    }

    public string FullName
    {
        get { return personModel.FirstName + "" "" + personModel.LastName; }
    }
    public string Result
    {
        get { return result; }
        set { result = value; }
    }

    public string FirstName
    {
        get { return personModel.FirstName; }
        set { personModel.FirstName = value; }
    }

    public string LastName
    {
        get { return personModel.LastName; }
        set { personModel.LastName = value; }
    }

    public string Input
    {
        get { return personModel.Input; }
        set { personModel.Input= value; }
    }

    public string Output
    {
        get { return personModel.Output; }
        set { personModel.Output= value; }
    }

    public string Result
    {
        get { return result; }
        set { result = value; }
    }        
    public void ResultFromModelToView()
    {
        getService.GetOutput(personModel);
        Result = string.Join("","", FullName,personModel.Output);            
    }
}
</code></pre>

<p>For <code>IGetService</code>,</p>

<pre><code>public interface IGetService
{
    void GetOutput(PersonModel personModel);
}   
</code></pre>

<p>The implementation of <code>GetService</code> is pretty much getting <code>personModel.Outout</code> value depending on business logic</p>

<p>Here is my <code>ViewModelTests</code></p>

<pre><code>public class ViewModelTests
{

    private Mock&lt;IGetService&gt; GetServiceMock{ get; set; }
    private ViewModel ViewModel { get; set; }

    [TestInitialize()]
    public void Initialize()
    {
        GetServiceMock= new Mock&lt;IGetService&gt;();
        ViewModel = new ViewModel (GetServiceMock.Object);
    }

    [TestMethod()]
    public void GetResultTests()
    {
        // Arrange
        GetServiceMock.Setup(x =&gt;  x.GetOutput(It.Is&lt;PersonModel&gt;(
            p=&gt; p.FirstName == ""FirstName"" &amp;&amp;
                    p.LastName == ""LastName"" &amp;&amp;
                    p.Input == ""Input""
            )));

        // Act
        ViewModel.ResultFromModelToView();

        // Assert
        Assert.AreEqual(ViewModel.Result, ""FirstName,LastName,Output"");

    }
}
</code></pre>

<p>When I run the test I'm getting </p>

<blockquote>
  <p>Assert failed, with expected result of "",,""</p>
</blockquote>

<p>What have I missed? </p>
",https://stackoverflow.com/questions/49567249/injected-mocked-dependency-into-viewmodel-while-unit-testing-not-behaving-as-exp,"['c#', 'unit-testing', 'dependency-injection', 'moq', 'viewmodel']",399,TRUE,1,1
Failure to set APP_ENV to &#39;testing&#39; for unit testing in Laravel 5.5,"<p>I am using Laravel 5.5, phpunit 6.5.5 on Homestead-7 (I think).</p>

<p>I am trying this tutorial: <a href=""https://laravel-news.com/your-first-laravel-application"" rel=""nofollow noreferrer"">https://laravel-news.com/your-first-laravel-application</a> (And this should tell you a lot about my experience with the framework)</p>

<p>Testing fails (due to <code>TokenMismatchException</code>) and I have managed to track down the root cause to the <code>APP_ENV</code> variable being set to <code>local</code>, although I've tried many ways of setting it to <code>testing</code>.</p>

<p>At the end, what allowed me to overcome the problem was to set the variable like this:</p>

<pre><code>APP_ENV=testing vendor/bin/phpunit
</code></pre>

<p>Then, the tests completed successfully.</p>

<p>My question is, what am I doing wrong? The above hack is obviously not the best way to do it. There must be a way to properly do this.</p>

<p><strong>Update</strong></p>

<p>Contents of <code>phpunit.xml</code>:</p>

<pre><code>&lt;?xml version=""1.0"" encoding=""UTF-8""?&gt;
&lt;phpunit backupGlobals=""false""
         backupStaticAttributes=""false""
         bootstrap=""vendor/autoload.php""
         colors=""true""
         convertErrorsToExceptions=""true""
         convertNoticesToExceptions=""true""
         convertWarningsToExceptions=""true""
         processIsolation=""false""
         stopOnFailure=""false""&gt;
    &lt;testsuites&gt;
        &lt;testsuite name=""Feature""&gt;
            &lt;directory suffix=""Test.php""&gt;./tests/Feature&lt;/directory&gt;
        &lt;/testsuite&gt;

        &lt;testsuite name=""Unit""&gt;
            &lt;directory suffix=""Test.php""&gt;./tests/Unit&lt;/directory&gt;
        &lt;/testsuite&gt;
    &lt;/testsuites&gt;
    &lt;filter&gt;
        &lt;whitelist processUncoveredFilesFromWhitelist=""true""&gt;
            &lt;directory suffix="".php""&gt;./app&lt;/directory&gt;
        &lt;/whitelist&gt;
    &lt;/filter&gt;
    &lt;php&gt;
        &lt;env name=""APP_ENV"" value=""testing""/&gt;
        &lt;env name=""CACHE_DRIVER"" value=""array""/&gt;
        &lt;env name=""SESSION_DRIVER"" value=""array""/&gt;
        &lt;env name=""QUEUE_DRIVER"" value=""sync""/&gt;
        &lt;env name=""DB_CONNECTION"" value=""sqlite""/&gt;
        &lt;env name=""DB_DATABASE"" value="":memory:""/&gt;
    &lt;/php&gt;
&lt;/phpunit&gt;
</code></pre>

<p>Thank you in advance for your time.</p>
",https://stackoverflow.com/questions/48227569/failure-to-set-app-env-to-testing-for-unit-testing-in-laravel-5-5,"['laravel', 'phpunit']",4488,TRUE,1,2
Unit testing Angular service that depends on another service that uses InjectionToken,"<p>I am working on unit testing an Angular service that looks like so:</p>

<pre><code>/* data.service.ts */
import { Injectable } from '@angular/core';

import { FooService } from './foo.service';
import { Data } from './data.model';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  constructor(private fooService: FooService) {}

  addData(data: Data) {
    return this.fooService.getActiveFoo().addData(data);
  }
}
</code></pre>

<p><code>FooService</code> is a service in the same module. It injects some values using InjectionTokens. </p>

<pre><code>/* foo.service.ts */
import { Inject, Injectable } from '@angular/core';

import { KEY1, KEY2 } from './tokens';
import { Foo } from './foo.ts';

@Injectable({
  providedIn: 'root'
})
export class FooService{

  activeFoo: Foo; 

  constructor(@Inject(KEY1) private key1: string, @Inject(KEY2) private key2: string) {}

  ...

  getActiveFoo() {
    return this.activeFoo; 
 }
}


/* tokens.ts */
import { InjectionToken } from '@angular/core';

export const KEY1 = new InjectionToken('KEY_1');
export const KEY2 = new InjectionToken('KEY_2');
</code></pre>

<p>All three files are part of the same module, which is set up as so: </p>

<pre><code>/* bar.module.ts */
import { ModuleWithProviders, NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { KEY1, KEY2 } from './tokens';
import { DataService } from './data.service';
import { FooService } from './foo.service';

@NgModule({
  imports: [CommonModule],
})
export class BarModule {
  static forRoot(key1Val: string, key2Val: string): ModuleWithProviders {
    return {
      ngModule: BarModule,
      providers: [
        DataService,
        FooService,
        { provide: KEY1, useValue: key1Val},
        { provide: KEY2, useValue: key2Val}
      ]
    };
  }
}
</code></pre>

<p>This is working fine in the app itself. Now I am working on writing a unit test for <code>data.service.ts</code> and am running into issues with the provided InjectionTokens. </p>

<pre><code>/* data.service.spec.ts */
import { TestBed, inject } from '@angular/core/testing';

import { DataService } from './data.service';
import { FooService } from './foo.service';
import { KEY1, KEY2 } from './tokens';

describe('DataService', () =&gt; {
  const mockFooService = jasmine.createSpyObj(['getActiveFoo']);

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      providers: [
        DataService,
        { provide: FooService, useValue: mockFooService },
        { provide: KEY1, useValue: 'abc' },
        { provide: KEY2, useValue: '123' }
      ]
    });
  });

  it('should be created', inject([DataService], (service: DataService) =&gt; {
    expect(service).toBeTruthy();
  }));
});
</code></pre>

<p>When I run my tests I am receiving an error saying </p>

<pre><code>Error: StaticInjectorError(DynamicTestModule)[FooService -&gt; InjectionToken KEY_1]: 
  StaticInjectorError(Platform: core)[FooService -&gt; InjectionToken KEY_1]: 
    NullInjectorError: No provider for InjectionToken KEY_1!
</code></pre>

<p>I have tried using empty objects instead of strings in the test providers but still get the same error. Is there another way I need to be providing these tokens?</p>
",https://stackoverflow.com/questions/50633133/unit-testing-angular-service-that-depends-on-another-service-that-uses-injection,"['angular', 'karma-jasmine', 'angular6', 'angular-test']",2347,TRUE,1,1
How can an Acceptor flow in Corda be isolated for unit testing?,"<p>I'm trying to unit test an Acceptor flow in Corda, without calling it from the Initiating flow. Specifically I want to send in an invalid SignedTransaction (invalid because it fails the output state contract verification), to ensure that the Acceptor flow handles it as expected and refuses to sign it.</p>

<p>If the Acceptor flow is tested by calling the Initiating Flow, then an invalid txn will get kicked out on the Initiator flow side, before calling the Acceptor flow.</p>
",https://stackoverflow.com/questions/48166626/how-can-an-acceptor-flow-in-corda-be-isolated-for-unit-testing,['corda'],345,TRUE,1,1
"When unit testing without a host application, where do I put files?","<p>When running a unit test without a host application, my code for creating a file is returning something in the CoreSimulator. However that location doesn't necessarily exist.</p>

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

<pre><code>let searchPaths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentFolderPath = searchPaths[0]
let dbFilePath = documentFolderPath + ""/test.db""
</code></pre>

<p>dbFilePath created:</p>

<pre><code>/Users/aaronbratcher/Library/Developer/CoreSimulator/Devices/3E6F7BD3-482B-4A90-B3C7-C0CC8412A5AC/data/Documents/test.db
</code></pre>

<p>How can I get a path outside of CoreSimulator when running unit tests without a host app?</p>
",https://stackoverflow.com/questions/50090626/when-unit-testing-without-a-host-application-where-do-i-put-files,"['ios', 'xcode', 'unit-testing']",141,TRUE,0,1
"In unit testing, does static readonly have any clear advantages over const?","<p>There have been many, many answers to the question about differences between <code>static readonly</code> and <code>const</code>. I am not asking about that. What I want to know is whether one or the other has a clear advantage when creating dummy data for a unit test class.</p>

<p>Here's an example with <code>const</code>:</p>

<pre><code>[TestClass]
public class CustomerModelTest
{
   private const string firstName = ""Bill"";
   private const string lastName = ""The Tester"";

   // Test methods in the class then use the above data in their tests.
}
</code></pre>

<p>Here's the same example with <code>static readonly</code>:</p>

<pre><code>[TestClass]
public class CustomerModelTest
{
   private static readonly string firstName = ""Bill"";
   private static readonly string lastName = ""The Tester"";

   // Test methods in the class then use the above data in their tests.
}
</code></pre>

<p>My team is in a debate over this question and I'd like to create a standard that would allow us to tell new hires, ""Use [const/static readonly] as a default for holding dummy data, unless you have a good reason not to.""</p>

<p>Here's what I understand so far: </p>

<ul>
<li><code>const</code> is <a href=""https://www.stum.de/2009/01/14/const-strings-a-very-convenient-way-to-shoot-yourself-in-the-foot/"" rel=""nofollow noreferrer""><em>theoretically</em> faster</a>.</li>
<li><code>static readonly</code> keeps me from having to <a href=""https://stackoverflow.com/a/3190930/5098460"">recompile any dlls that reference the current assembly</a>.</li>
<li><code>const</code> cannot be used for <a href=""https://stackoverflow.com/a/3190930/5098460"">computed values</a>.</li>
</ul>

<p>So are there any fact-based reasons why one is preferable to the other in this situation? Or should our team just create an arbitrary standard?</p>
",https://stackoverflow.com/questions/48910493/in-unit-testing-does-static-readonly-have-any-clear-advantages-over-const,"['c#', 'unit-testing', 'mstest']",1000,TRUE,0,2
Login before executing a post in unit testing using Chai and Mocha,"<p>I am trying to test my post function where it only allows data from a user which has specific permission. I have made a login function (tested separately it works). I want to make a test which will perform a login then do a post with data so it does it as an authorised user. As now the test code is working but it does not see a user to be logged in and does it as a normal user. </p>

<p>My current not working code :</p>

<pre><code>describe('/POST _json post data as a admin', () =&gt; {
        before((done) =&gt; {
            let loginInfo = {};
            loginInfo.usr = 'testuser';
            loginInfo.psw = 'mochatesting197';
            chai.request.agent(app)
                .post('/login')
                .send(loginInfo)
                .then((res) =&gt; {
                    done();
                });
        });
        it('POST data as a admin', () =&gt; {
            let json = {};
            json.module_name = ""TEST ENTRY"";
            json.module_url = ""/TEST_ENTRY"";
            json.module_privilege = ""testentry;testentry2;testentry3"";
            chai.request(app)
                .post('/_json')
                .send(json)
                .then((res) =&gt; {
                    res.should.have.status(200);
                    res.body.should.be.a('object');
                    res.body['success'].should.have.property('message');
                }).catch((err) =&gt; {
                    throw err;
                });

        });
    });
</code></pre>
",https://stackoverflow.com/questions/50321095/login-before-executing-a-post-in-unit-testing-using-chai-and-mocha,"['node.js', 'unit-testing', 'express', 'mocha.js', 'chai']",793,FALSE,0,1
How to utilize unit-testing without classes and def functions in python?,"<p>I am currently in my intro to Python class this semester. We constantly make small-scale programs. Such as the program I just made that takes a function, a domain and finds the root (We assume the user will input a domain that has exactly one root) using bisection.</p>

<p>We made test cases that we just simply commented on our program:</p>

<ul>
<li><h1>TEST CASES:</h1>

<h1>f(x) = 4x^3-5x^2+2x+6  D: {-50, 70} Root: -3/4</h1></li>
</ul>

<h1>f(x) = x^3+10x^2+ 10x + 10 D: {-50, 50} Root: -9.014</h1>

<h1>f(x) = 7x^3 + 0x^2 + 3x -2 D: {-100, 40} Root: 0.45</h1>

<h1>f(x) = 5x^3 + 2x^2 -3x + 4 D: {-100, 100} Root: -1.317</h1>

<p>That got me to look more in depth with testing and I ran across the unittest import. I searched videos about it but every video I ran across assumes that you have classes and are using the def function. </p>

<p>This program doesn't does not use that. Only reads in a function and domain and we use that to find the root. </p>

<p>So, is there anyway we can use unittest to pass values that could be inputted by the user? Or can is it only possible when we call classes and defs? If it's not, what else can you suggest I use? </p>

<p>P.S this is simply for my understanding... unittest is not required for any assignment.</p>
",https://stackoverflow.com/questions/52693672/how-to-utilize-unit-testing-without-classes-and-def-functions-in-python,"['python', 'unit-testing']",211,FALSE,0,0
TypeError: service.getValue is not a function in Angular2 Unit-Testing a Service,"<blockquote>
  <p>TypeError: service.getValue is not a function</p>
</blockquote>

<pre><code>let data: string;

@Injectable()
export class MyService {
constructor() {
    myOtherObservableReturning.subscribe((data: mydata) =&gt; {
           data.items.forEach((item: Object)  =&gt; {
               .....
           }
        ...
        ...
    });
}
   public getValue() { return 'HelloWorld'; }
}
</code></pre>

<p>unit test:</p>

<pre><code>let service: MyService;
beforeEach(() =&gt; {
    TestBed.configureTestingModule({
        providers: [
            { provide: MyService, useValue: { data: Observable.of(dataStub) } }
        ]
    });
    service = TestBed.get(MyService);
});

it('should be created', () =&gt; {
    expect(service).toBeTruthy();
    console.log(JSON.stringify(service)); 
    //LOG: '{""params"":{""_isScalar"":true,""scheduler"":null}}'
});


it('should call getValue', () =&gt; {
    //TypeError: service.getValue is not a function
    expect(service.getValue()).toBe('HelloWorld');
});
</code></pre>

<p>I couldnt figure out why unit test cant find the function <code>getValue()</code>, I have already imported and checked its there in the service file.</p>
",https://stackoverflow.com/questions/49484571/typeerror-service-getvalue-is-not-a-function-in-angular2-unit-testing-a-service,"['angular', 'unit-testing']",2011,FALSE,0,2
"Unit Testing in Mockito, Calling a chain of functions on an object?","<p>I've not done much testing and very minimal in Mockito. When I call delete on a certain object, I get a <code>DeleteResponse</code>. This has a method called <code>getProcessingErrors()</code> which is a set. I can then call <code>.isEmpty()</code> to see if there are errors or not. I'm trying to mock this out. </p>

<pre><code>DeleteResponse deleteResponse = mock(DeleteResponse.class);

when(catalogFramework.delete(any(DeleteRequest.class))).thenReturn(deleteResponse);

when(deleteResponse.getProcessingErrors()).thenReturn(new HashSet&lt;ProcessingDetails&gt;());

PowerMockito.when(deleteResponse.getProcessingErrors().isEmpty()).thenReturn(true);
</code></pre>

<h3>Error:</h3>

<pre><code>org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 
Boolean cannot be returned by getProcessingErrors()
getProcessingErrors() should return Set
***
If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1. This exception *might* occur in wrongly written multi-threaded tests.
   Please refer to Mockito FAQ on limitations of concurrency testing.
2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - 
   - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.
</code></pre>

<p>Now, from the way I am reading this, it is saying <code>isEmpty</code> cannot return a boolean, but I believe it's cutting out early and just looking at the getProcessingErrors. How can I fix this?</p>
",https://stackoverflow.com/questions/50168721/unit-testing-in-mockito-calling-a-chain-of-functions-on-an-object,"['java', 'unit-testing', 'mockito']",547,TRUE,0,3
Unit testing for an old app - Which components should be considers first?,"<p>I'm currently working on over-4-year-old project (iOS - with MVC design), which has been passed through many various developers. For years it has been developed in an as-long-as-it-works-its-ok manner. Now out of the blue my client asked to add Unit Testing to the project, and I really don't know where to start with the project. </p>

<p>Can any one suggest a good start point? I mean which class (view controllers, models, utilities) should I write the test cases first? </p>
",https://stackoverflow.com/questions/50213365/unit-testing-for-an-old-app-which-components-should-be-considers-first,"['ios', 'unit-testing']",27,TRUE,0,1
Unit Testing Laravel need help on how to pass my variables properly,"<p>So I'm getting into Unit Testing and I have created a test for creating and adjustment line in my DB.  Here is the code:</p>

<pre><code>        $response = $this-&gt;json('POST', '/quotes/3/adjustment',
               [
                    'adjustments' =&gt; array([
                        'description'   =&gt; 'TEST-Description',
                        'amount'        =&gt; 1000,
                        'quote_id'      =&gt; 3
                    ])
                ]
    );
    $response-&gt;assertStatus(201);
</code></pre>

<p>When creating it hits my controller then an instance of my Adjustment model is created, and in that model I have this code for the creating of it:</p>

<pre><code>            foreach($request-&gt;adjustments as $adjustment) {
            if(array_key_exists('id', $adjustment)) {
                $this-&gt;find($adjustment['id'])-&gt;update([
                    'description'   =&gt; $adjustment['description'],
                    'amount'        =&gt; $adjustment['amount'],
                    'quote_id'      =&gt; $quote-&gt;id
                ]);
            } else {
                $this-&gt;create([
                    'description'   =&gt; $adjustment['description'],
                    'amount'        =&gt; $adjustment['amount'],
                    'quote_id'      =&gt; $quote-&gt;id,
                ]);
            }
        }
        return $quote;
</code></pre>

<p>So it expects adjustments to be an array and I thought I had it coded properly in the test but i get back a 200 response, which is not the 201 as expected.  Any ideas on how to properly pass the single array in my test file so that it passes the test?</p>

<p>Here is my controller:</p>

<pre><code>        $adjustment = new Adjustment();
    return $adjustment-&gt;newAdjustment($quote, $request)-&gt;adjustments;
</code></pre>

<p>On a side note if I run this in postman as raw JSON(applicatoin/json) it creates the resource in the DB:</p>

<pre><code>{
""adjustments"": [{
        ""description"": ""testing-postman"",
        ""amount"": 1000,
        ""quote_id"": 1
}
    ]
</code></pre>

<p>}</p>
",https://stackoverflow.com/questions/53672424/unit-testing-laravel-need-help-on-how-to-pass-my-variables-properly,"['json', 'laravel', 'unit-testing', 'testing']",67,TRUE,0,1
Cannot read property &#39;navigate&#39; of undefined error when unit testing in angular,"<p>Why I am seeing this error when making my unit test on a function that need to be called : here is my code, first the code of .spec.ts :</p>

<pre><code>it(' doit appeller le serveur quand le boutton ok est cliqué, pour envoyer l option du choix du code', () =&gt; {
  let spy = spyOn(authService, 'choixReceptionCode').and.callFake(t =&gt; {
  // on est pas besoin de se qui retourner du serveur l essentiel la fonction a ete appelle 
  return Observable.empty();
});

component.choix('mail');
  // comme ça on a testé si la fonction 'connexion' a été appelle ou nn
  expect(spy).toHaveBeenCalled();
});
</code></pre>

<p>And here is the function in the component.ts:</p>

<pre><code>choix(choice:string)
{
  console.log(""ggggggggg""+choice);
  this.router.navigate(['saisirCode']);
  this.choiceReceptionCode.choix=choice;
  this.choiceReceptionCode.user=this.serviceAuthentification.getUserId();
  this.serviceAuthentification.choixReceptionCode(this.choiceReceptionCode).subscribe(
  (data)=&gt;{
      console.log(""the response in choixReceptionCode"");
      console.log(data);     


  },
  (error)=&gt;{
      console.log(""Error in choixReceptionCode "");
      console.log(error);
  });
}
</code></pre>

<p>when executing ng test i found this error,<br>
<a href=""https://i.stack.imgur.com/fWnad.png"" rel=""nofollow noreferrer"">the picture that showing the error</a>   </p>

<p>I know the problem is in this line:</p>

<pre><code>this.router.navigate(['saisirCode']);
</code></pre>

<p>in the component.ts file because when i comment it the test pass, so how can I solve it.</p>

<p>Thanks a lot</p>
",https://stackoverflow.com/questions/50195963/cannot-read-property-navigate-of-undefined-error-when-unit-testing-in-angular,"['angular', 'karma-jasmine', 'angular-test']",1823,FALSE,0,1
Unit Testing a Web API controller which Has Been Authorized with JWT,"<p>I'm trying to Unit Test below Web API controller.</p>

<pre><code>    [IdentityBasicAuthentication]
    [Authorize]
    [HttpPost]
    public HttpResponseMessage GetOrderByQR([FromBody]string id)
    {
        try
        {
            var identity = HttpContext.Current.User.Identity as ClaimsIdentity;

            var user = UserManager().IdentifyToken(identity);

            _orderManager.CheckOrderQRFraud(id);

            return Request.CreateResponse(HttpStatusCode.OK, _orderManager.GetSingleOrderWithUserPaymentAccountBy(user.UserID, id));
        }
        catch (BusinessException ex)
        {
            return CreateRawStringResponse(HttpStatusCode.NotFound, ex.Message);
        }
    }
</code></pre>

<p>But below test method throws null exception on <code>IdentifyToken()</code> as there is no current user, I understand that.</p>

<pre><code>    [TestMethod]
    public void GetOrderByQR_Returns_OK_On_Successful_Request()
    {
        string orderID = ""4B854B3D-397E-425F-AEAF-00F7B4110021"";

        var testResponse = _orderController.GetOrderByQR(orderID);

        Assert.AreEqual(HttpStatusCode.OK, testResponse.StatusCode);
    }
</code></pre>

<p>While I was searching for an answer, I saw that the solution lies on mocking this authorization attribute. So, although I install this <a href=""https://code.google.com/archive/p/moq/"" rel=""nofollow noreferrer"">Moq</a> package, couldn't achive to run as successful test as I'm new on unit testing.</p>

<p>Below is <code>IdentityToken()</code> method if you need to check it out also.</p>

<pre><code>    public User IdentifyToken(ClaimsIdentity identity)
    {
        string userEmail = """";
        string userPassword = """";

        if (identity != null)
        {
            IEnumerable&lt;Claim&gt; claims = identity.Claims;
            List&lt;Claim&gt; claimsArray = claims.ToList();
            string[] emailArray = claimsArray[0].ToString().Split(':');
            string emailValue = emailArray[2].ToString();
            userEmail = emailValue.Trim();
            string[] passwordArray = claimsArray[1].ToString().Split(':');
            string passwordValue = passwordArray[2].ToString();
            userPassword = passwordValue.Trim();
        }

        var user = base.GetSingleBy(x =&gt; x.Email == userEmail &amp;&amp; x.Password == userPassword);

        return user;
    }
</code></pre>

<p>How should I write my test method? Thank you in advance!</p>

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

<p>Manager class instances are as below.</p>

<pre><code>public class OrderController : BaseController
{
    OrderManager _orderManager;

    public OrderController()
    {
        _orderManager = new OrderManager();
    }

    //Order Controllers
}
</code></pre>
",https://stackoverflow.com/questions/52385940/unit-testing-a-web-api-controller-which-has-been-authorized-with-jwt,"['c#', 'unit-testing', 'asp.net-web-api', 'authorization', 'moq']",2235,FALSE,0,2
unit testing a java method by calling the method in multiple threads,"<p>I have a spring bootproject with several services. Im writing junit test for a method that defines a service that reads value from database and updates it with the new value in the database. I want to do unit testing for the method by calling it in 10 different threads. How can this be done?</p>
",https://stackoverflow.com/questions/53703924/unit-testing-a-java-method-by-calling-the-method-in-multiple-threads,"['java', 'spring-boot', 'junit', 'spring-boot-test']",247,FALSE,0,0
How to setup Karma and Jasmine unit-testing for common js library?,"<p>I am developing a browser-based JavaScript library. For that purpose, I have set up a directory structure where each module is in a separate file and the final build is generated using webpack in a single file that is to be included in the web-page.</p>

<p>I want to set up a unit testing environment similar to Angular's Karma + Jasmine testing setup where I can write test cases for each module in a separate file and run a single command to execute these tests. Any testing setup is fine as long as a single command is enough to run all the tests and they can be kept in separate files.</p>

<p>The intended structure is something like this:</p>

<pre><code>src
  index.js
  index.test.js
  my-module
    index.js
    index.test.js
</code></pre>

<p>I have looked into mocha's browser testing as I am somewhat familiar with mocha + expect testing for NodeJs but it seems like I have to include each file separately in the testing HTML file.</p>

<hr>

<p>The main goal here is to keep the tests file near the files they are supposed to test as is the case in Angular so that they are easy to maintain and have a single command to run all the tests. The tests must run in a browser similar to how testing works in Angular.</p>
",https://stackoverflow.com/questions/51189129/how-to-setup-karma-and-jasmine-unit-testing-for-common-js-library,"['javascript', 'angular', 'unit-testing', 'karma-jasmine']",481,FALSE,0,1
Php Unit Testing not covering all the attributes label of Yii2 model,"<p>I am writing testing code for Yii2 When I am testing with phpunit. Then Code coverage check is not covering the attributes labels method totally. It only cover the first line of that. This is My Testing Model code given below.</p>

<pre><code>public function testattributeLabels()
{
    $attribute = Academicrecords::attributeLabels();
    print_r($attribute);

    $this-&gt;assertInternalType('array',$attribute);
    $this-&gt;assertContains('Student Name',$attribute);

    $this-&gt;assertEquals('Student Name',$attribute['student_id']);
    $this-&gt;assertEquals('ID',$attribute['id']);
    $this-&gt;assertEquals('School Name',$attribute['school_name']);
    $this-&gt;assertEquals('Class',$attribute['class']);
    $this-&gt;assertEquals('Stream',$attribute['stream']);

    $this-&gt;assertEquals('Created On',$attribute['created_on']);
    $this-&gt;assertEquals('Modified On',$attribute['modified_on']);
    $this-&gt;assertEquals('Created By',$attribute['created_by']);
    $this-&gt;assertEquals('Modified By',$attribute['modified_by']);
}
</code></pre>

<p>This is my Model code</p>

<pre><code>public function attributeLabels()
{
    return [
        'id' =&gt; 'ID',
        'student_id' =&gt; 'Student Name',
        'school_name' =&gt; 'School Name',
        'class' =&gt; 'Class',
        'stream' =&gt; 'Stream',
        'created_by' =&gt; 'Created By',
        'created_on' =&gt; 'Created On',
        'modified_by' =&gt; 'Modified By',
        'modified_on' =&gt; 'Modified On',
    ];
}
</code></pre>

<p>This is my codeception result
<a href=""https://i.stack.imgur.com/CV8hs.png"" rel=""nofollow noreferrer"">This is my Codeception result code</a></p>
",https://stackoverflow.com/questions/50000130/php-unit-testing-not-covering-all-the-attributes-label-of-yii2-model,"['yii2', 'phpunit', 'code-coverage', 'yii2-basic-app']",98,FALSE,0,1
How to enable unit testing in a Java module in Android Studio?,"<p>I am new to Android development. I have an android project with two Java modules. I would like to create some unit tests for the two modules.</p>
",https://stackoverflow.com/questions/49338167/how-to-enable-unit-testing-in-a-java-module-in-android-studio,"['android', 'android-studio', 'junit', 'kotlin']",145,FALSE,0,0
Angular2 unit testing on Service fail TypeError: service.getValue is not a function,"<blockquote>
  <p>TypeError: service.getValue is not a function</p>
</blockquote>

<pre><code>let data: string;

@Injectable()
export class MyService {
constructor() {
    myOtherObservableReturning.subscribe((data: mydata) =&gt; {
           data.items.forEach((item: Object)  =&gt; {
               .....
           }
        ...
        ...
    });
}
   public getValue() { return 'HelloWorld'; }
}
</code></pre>

<p>unit test:</p>

<pre><code>beforeEach(() =&gt; {
    TestBed.configureTestingModule({
        providers: [
            { provide: MyService, useValue: { data: Observable.of(dataStub) } }
        ]
    });
    service = TestBed.get(MyService);
});

it('should be created', () =&gt; {
    expect(service).toBeTruthy();
    console.log(JSON.stringify(service)); 
    //LOG: '{""params"":{""_isScalar"":true,""scheduler"":null}}'
});


it('should call getValue', () =&gt; {
    //TypeError: service.getValue is not a function
    expect(service.getValue()).toBe('HelloWorld');
});
</code></pre>

<p>I couldnt figure out why unit test cant find the function <code>getValue()</code>, I have already imported and checked its there in the service file.</p>
",https://stackoverflow.com/questions/49446223/angular2-unit-testing-on-service-fail-typeerror-service-getvalue-is-not-a-funct,"['angular', 'unit-testing']",264,TRUE,0,1
An error occurs if unit testing is performed at the same time,"<p>Each unit test did not cause an error. However, it occurs when several are carried out at the same time. Is there a Google test feature that can put Sleep between unit tests running?</p>

<p>p.s I can not modify the source because it is not my source.</p>

<p>The following command causes an error.</p>

<pre><code>./ext_libs_test --gtest_filter=NAV_NC_0002_RouteController_Test*:IF1_LastDestination_Test*:NAV_NC_0029_TrafficInformationController_Test*:NAV_NC_0051_RouteMonitorListController_Test*:NAV_NC_0068_LocationInformationProvider_Test*:NAV_NC_0067_LearningRecordingController_Test*
</code></pre>

<p>I want to sleep between each of these files.
If you type each in this way, no errors will occur.</p>

<pre><code>./ext_libs_test --gtest_filter=NAV_NC_0002_RouteController_Test*
./ext_libs_test --gtest_filter=IF1_LastDestination_Test*
./ext_libs_test --gtest_filter=NAV_NC_0029_TrafficInformationController_Test*
./ext_libs_test --gtest_filter=NAV_NC_0051_RouteMonitorListController_Test*
./ext_libs_test --gtest_filter=NAV_NC_0068_LocationInformationProvider_Test*
./ext_libs_test --gtest_filter=NAV_NC_0067_LearningRecordingController_Test*
</code></pre>
",https://stackoverflow.com/questions/53000642/an-error-occurs-if-unit-testing-is-performed-at-the-same-time,"['unit-testing', 'googletest']",41,TRUE,0,1
C# Nuget or AutoCode Generator to Compare Multiple Objects in Unit Testing,"<p>The following test creates error when I test tuples. </p>

<blockquote>
  <p>'Assert.AreEqual(test,productRepository.GetById(1))' threw an exception of type 'NUnit.Framework.AssertionException'</p>
</blockquote>

<p>Many  solutions presented below require an override equals function for each model. This is very hard to maintain for software with 200+ models in project. Is there any Nuget package or auto code generator which will create equality override methods for all the 200 models?</p>

<p>These all ask to override</p>

<ul>
<li><a href=""https://stackoverflow.com/questions/2046121/how-to-compare-two-objects-in-unit-test"">How to Compare two objects in unit test?</a></li>
<li><a href=""https://stackoverflow.com/questions/23530982/c-sharp-asserting-two-objects-are-equal-in-unit-tests"">C# - Asserting two objects are equal in unit tests</a></li>
<li><a href=""https://stackoverflow.com/questions/2920399/c-sharp-how-to-find-if-two-objects-are-equal"">c# How to find if two objects are equal</a></li>
</ul>

<p><strong>NUnit Test</strong></p>

<pre><code>[Test]
public void TestProducts()
{
    var options = new DbContextOptionsBuilder&lt;ElectronicsContext&gt;()
        .UseInMemoryDatabase(databaseName: ""Products Test"")
        .Options;

    using (var context = new ElectronicsContext(options))
    {
        //DbContextOptionsBuilder&lt;ElectronicsContext&gt; context = new DbContextOptionsBuilder&lt;ElectronicsContext&gt;()

        context.Product.Add(new Product { ProductId = 1, ProductName = ""TV"", ProductDescription = ""TV testing"", ImageLocation = ""test"" });
        context.SaveChanges();
        ProductRepository productRepository = new ProductRepository(context);
        var test = new Product
            {ProductId = 1, ProductName = ""TV"", ProductDescription = ""TV testing"", ImageLocation = ""test""};

       **//This works**
        Assert.AreEqual(""TV"", productRepository.GetById(1).ProductName);

       **//This Fails**
        Assert.AreEqual(test,productRepository.GetById(1));

       **//This Fails**
        Assert.AreEqual(Object.Equals(test, productRepository.GetById(1)), 1);
    }
</code></pre>

<p><strong>Repository</strong></p>

<pre><code>public class ProductRepository : IProductRepository&lt;Product&gt;
{
    private readonly ElectronicsContext _context;
    public ProductRepository(ElectronicsContext context)
    {
        _context = context;
    }

    public IEnumerable&lt;Product&gt; GetAllProduct()
    {
        return _context.Product.ToList();
    }

    public IQueryable&lt;Product&gt; Products =&gt; _context.Product;

    public Product GetById(int productid)
    {
        return _context.Product.Find(productid);

    }
}
</code></pre>

<p><strong>Model</strong></p>

<pre><code>public partial class Product
{
    public int ProductId { get; set; }
    public string ProductName { get; set; }
    public string ProductDescription { get; set; }
    public string ImageLocation { get; set; }

    public int? ProductCategoryId { get; set; }
    public virtual ProductCategory ProductCategory { get; set; }
}
</code></pre>
",https://stackoverflow.com/questions/52882195/c-nuget-or-autocode-generator-to-compare-multiple-objects-in-unit-testing,"['c#', 'unit-testing', 'asp.net-core', 'nunit', 'asp.net-core-2.0']",137,FALSE,0,2
C# Unit Testing - Ensure That Loop Continues Until Valid Input is Given,"<p>I have the following code that asks the user for input and continues asking until they give valid input.  The user input is received via Console.ReadLine</p>

<pre><code>public int ChooseMove() {
        string input;
        do {
            input = ui.AskUserForInput();
        } while (!ValidateInput(input));
        return int.Parse(input);
    }

private bool ValidateInput(string input) {
    string [] positions = ui.GetValidInputs();
    if (Array.Exists(positions, position =&gt; position == input)) {
        return true;
    }
    return false;
}
</code></pre>

<p>I am trying to unit test the ChooseMove method, but I am stuck.</p>

<p>I have a basic case working in NUnit like this...</p>

<pre><code>[Test]
        public void TestValidMove() {
            StringReader consoleInput = new StringReader(""6"");
            Console.SetIn(consoleInput);
            Assert.That(player.ChooseMove(), Is.EqualTo(6));
        }
</code></pre>

<p>However, I don't know how to test if the user gives bad input that it continues until valid input is given.</p>

<p>I want to send to the input stream something ""52"" and then ""6"" the second time through.  How do I send one input after another using the StringReader?  Is there a different way I should be doing this?</p>

<p>Thanks in advance</p>
",https://stackoverflow.com/questions/51353855/c-unit-testing-ensure-that-loop-continues-until-valid-input-is-given,"['c#', 'unit-testing', 'nunit', 'console-application']",343,TRUE,0,2
When to use unit testing or snapshot testing with jest and enzyme?,"<p>I am starting to write tests to my react app with jest and enzyme for native and for the frontend and I want to have a clear Idea when to use snapshot tests and when to use unit testing</p>
",https://stackoverflow.com/questions/51079958/when-to-use-unit-testing-or-snapshot-testing-with-jest-and-enzyme,"['javascript', 'reactjs', 'react-native', 'jestjs', 'enzyme']",854,TRUE,0,1
Is there a pattern/technique that supports unit testing shared &quot;initiating flows&quot;,"<p>Is there a pattern/technique that supports unit testing shared ""initiating flows"" that have been implemented in a ""shared cordapp.jar""  that have multiple corresponding private ""responding flows "" each of which is implemented in its own ""private party name cordapp.jar""  ? Hope this question makes sense.
Terminology is as per <a href=""https://stackoverflow.com/questions/47835229/can-either-side-of-a-corda-flow-exist-in-separate-cordapps"">Can either side of a Corda flow exist in separate Cordapps?</a>.
Thanks for all info.
John</p>
",https://stackoverflow.com/questions/48338130/is-there-a-pattern-technique-that-supports-unit-testing-shared-initiating-flows,['corda'],67,FALSE,0,1
Best way to use production database data for unit testing database data?,"<p>I am wondering if anyone can tell me the best way to populate test data in a test database from a real live database? (For use in Unit testing)</p>

<p>For example. I have a Sql Server Database that contains 1000's of records. I want to use that data for test cases in my C# testing project. It would be very time consuming to create the data manually. </p>

<p>I figured the best way to do this would be to generate c# code that will recreate the data in a test database for when I run the tests. But how would one do that? or would people typically just export a big SQL Statement in this sort of scenario and execute that against a test database?</p>

<p>The other obvious way to do it is to use a copy of the production database. My issue with that is, the data structure is still changing...which causes problems...</p>

<p>I am using SqlServer LocalDB, C#.</p>

<p>Thank you kindly for any advice</p>
",https://stackoverflow.com/questions/50223783/best-way-to-use-production-database-data-for-unit-testing-database-data,"['c#', 'sql-server', 'unit-testing']",458,TRUE,-1,1
How to import a file for karma - javascript unit testing in rails?,"<p>I am using Karma to unit test some of my scripts that are part of my rails application, but I am having trouble importing a file 'utility.js' that has several utility functions which I use throughout my code.  It works fine in when I run the rails app, my manifest loads the file first and the functions are globally available, but when I use this code at the top of my karma test file, the function <code>make_index_array()</code> which is defined in utility.js is not found.  make_index_array() is called by one of the methods in the class I under test (DetailBudget).</p>

<pre><code>import  ""../../app/assets/javascripts/utility.js""
import {DetailBudget} from ""../../app/assets/javascripts/budgeting_scripts/detail_budget_classes.js""
</code></pre>

<p>Here is the error message:</p>

<pre><code>START:
Chrome 71.0.3578 (Mac OS X 10.14.2) ERROR
  {
    ""message"": ""An error was thrown in afterAll\nUncaught ReferenceError: make_index_array is not defined"",
    ""str"": ""An error was thrown in afterAll\nUncaught ReferenceError: make_index_array is not defined""
  }
  Confirm test setup
    ✔  does works

Finished in 0.002 secs / 0.002 secs @ 10:57:35 GMT-0800 (Pacific Standard Time)
</code></pre>

<p>Here is the make_index_array function as defined in utility.js:</p>

<pre><code>function make_index_array(low, high) {
    let list = [];
    for (let i = low; i &lt;= high; i++) {
        list.push(i);
    }
    return list;
}
</code></pre>

<p>Karma is set to use ChromeBrowser, running Rails 5.2 (There are two tests in this suite, the first one (the one that passes) is just there to make sure the setup works.</p>
",https://stackoverflow.com/questions/53972693/how-to-import-a-file-for-karma-javascript-unit-testing-in-rails,"['ruby-on-rails', 'karma-jasmine', 'karma-runner']",1946,TRUE,0,1
Creating coded data objects using real data from database for unit testing,"<p>I'm going to write some unit tests for my method:</p>

<pre><code>using System.Linq;
...
public int CountEnabledEvents(IEnumerable&lt;Event&gt; events) 
{
    return events.Count(e =&gt; e.IsEnabled);
}
</code></pre>

<p>As you can see the input of this method is a <code>IEnumerable&lt;Event&gt;</code> collection.</p>

<p>The <code>Event</code> class looks like </p>

<pre><code>public class Event
{
    public Guid Id { get;set; }
    public bool IsEnabled { get;set; }
    public string SomeOtherProp { get;set; }
    ...
}
</code></pre>

<p>So I was about to create some dummy events on my test class:</p>

<pre><code>var event1 = new Event() {
    Id = new Guid(""...""),
    IsEnabled = true
}
var event2 = new Event() {
    Id = new Guid(""xxx""),
    IsEnabled = false
}
</code></pre>

<p>The thing is A) this is very tedious, and B) I actually have a ton of real events in my database, and I would like to use the real events on my unit test as testing with real data will make our test more accurate.</p>

<p><strong>¿Is there any kind of software or method to create those dummy <code>Event</code> objects out of real data I have in the database in a automagical way?</strong> </p>

<p>Thank you for your time.</p>

<p><strong>EDIT</strong> </p>

<p>I thought it was obvius that the code I've provided is a simplification of the actual code. The real method I would like to Unit-test is more complex, as is the actual <code>Event</code>. </p>

<p>So yes, its quite tedious to write down the N^N possibilities for the real event object. And no, I'm not trying to test the integration with the database or anything like that. What I'm trying to do is <em>create static instances coded in the actual test with the data I've got in the database</em>. Not at the testing run-time, but earlier.</p>
",https://stackoverflow.com/questions/53342087/creating-coded-data-objects-using-real-data-from-database-for-unit-testing,"['c#', 'unit-testing', 'domain-driven-design']",338,TRUE,-2,3
Unit testing error: &quot;setUpClass error: NameError: global name &#39;doSomething()&#39; is not defined&quot;,"<p>I am trying to execute <em>doSomething()</em> before every test I have. I just want to execute doSomething() one time. However, I am getting the next error message: <strong>""setUpClass error: NameError: global name 'doSomething' is not defined""</strong> </p>

<p>I have seen several examples of the implementation of setUpClass here in stackoverflow and my code is exactly as in those examples. I have been trying to change a lot of things in my code to make it works with no luck and I feel I am a little bit lost here.</p>

<p>Can anybody help me? Am I missing something?</p>

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

<pre><code>class Test_A(unittest.TestCase):
   def doSomething(self):
        print(""class A"")

   @classmethod
   def setUpClass(cls):
        doSomething()

   def test_1(self):
        print(""test 1"")

   def test_2(self):
        print(""test 2"")
</code></pre>

<p>I am using <em>python 2.7</em></p>
",https://stackoverflow.com/questions/53343731/unit-testing-error-setupclass-error-nameerror-global-name-dosomething-is,"['python', 'python-2.7']",207,TRUE,-3,1
Unit testing a method that calls a method on newly created instance?,"<p>We need to write junit test for below method. </p>

<pre><code>public void Logout(){
  new SecurityContextLogoutHandler.logout();
}
</code></pre>

<p>How can we test where securitycontextLogoutHandler.logout method is called?
We are able to verify that a new instance of securitycontextLogoutHandler is created by usinf PowerMockito but not able to verify logout method call.</p>

<p>Below is the Test written:</p>

<pre><code>SecurityContextLogoutHandler securityContextLogoutHandler = 
PowerMockito.mock(SecurityContextLogoutHandler.class);

PowerMockito.verifyNew(SecurityContextLogoutHandler.class);
</code></pre>
",https://stackoverflow.com/questions/51319611/unit-testing-a-method-that-calls-a-method-on-newly-created-instance,"['spring-boot', 'junit4', 'powermockito']",75,FALSE,0,0
Can&#39;t get to load css styles in angular unit testing using jasmine karma,"<p>How can i get to load css styles in unit tests?
I am working with angular 5,and testing using Jasmine and Karma.The css styles dont show up completely.I imported the bootstrap.min.css but only few of the styles load up.I have done so like this ...</p>

<pre><code>files: [
  ""./node_modules/bootstrap/dist/css/bootstrap.min.css"",
  ""./src/app/core/**/components/**/*.css""
]
</code></pre>

<p>in the karma.config,</p>

<p>This loads up some of the styles from both the file paths but not completely.Is there anyother means of importing the styles or can i somehow get to load all the styles in to the unit testing browser.</p>

<p>I am not using material hence the below doesnt seem to work.</p>

<pre><code>files: [
     { pattern: '../node_modules/@angular/material/prebuilt-themes/indigo- 
       pink.css', watched: true, included: true, served: true },
       ]
</code></pre>

<p>Thanks in advance for the answers!</p>
",https://stackoverflow.com/questions/53442106/cant-get-to-load-css-styles-in-angular-unit-testing-using-jasmine-karma,"['css', 'angular', 'unit-testing', 'jasmine', 'karma-jasmine']",566,FALSE,4,0
How to do unit testing for recycler view and its adapter in Android,"<p>I am a newbie to Android and want to do unit testing on Recycler view and its adapter using Mockito.</p>

<p>I have mocked the activity and trying to mock its recycler view and add my unit tests to it. I digged into Google to find a solution for it. But didn't get any references. Final after gathering some of the references I have written my test class like this.</p>

<pre><code>public class PhotoViewActivityTest {
@Mock
Context context;
@InjectMocks
private PhotoViewActivity photoViewActivity;
RecyclerView recyclerView;

@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
    recyclerView = Mockito.mock(RecyclerView.class);
    MockitoAnnotations.initMocks(this);
    photoViewActivity = mock(PhotoViewActivity.class);
}

@Test
public void checkIfRecyclerViewClicked() {
    List&lt;PhotoListItem&gt; items = new ArrayList&lt;&gt;();
    Photo photo = Mockitio.mock(Photo.class);
    items.add(photo));
    PhotoViewerListAdapter adapter = Mockito.mock(PhotoViewerListAdapter);
    adapter.setData(items);
    recycleView.setAdapter(adapter);
    // simulate first item was clicked
    recyclerView.getChildAt(0).performClick();
    //Check if method was invoked with our object
    Mockito.verify(adapter).goToDetailActivity(photo);
 }
}
</code></pre>

<p>But it is giving null pointer exception. I referred this <a href=""https://stackoverflow.com/questions/42188261/how-do-i-unit-test-with-junit-or-mockito-recyclerview-item-clicks/42364421"">How do I unit test (with JUnit or mockito) recyclerview item clicks</a></p>
",https://stackoverflow.com/questions/49083217/how-to-do-unit-testing-for-recycler-view-and-its-adapter-in-android,"['android', 'unit-testing', 'android-recyclerview', 'mockito']",3854,FALSE,5,0
How can I combine test filters in the unit testing framework Google Test?,"<p>I have several unit test cases, which I have written with the Google Test framework:</p>

<ol>
<li><p>Test class:</p>

<pre><code>class Test: public testing::Test
{
public:
  virtual void SetUp() {}
  virtual void TearDown() {}
};
</code></pre></li>
<li><p>Actual tests:</p>

<pre><code>TEST_F(Test, SubTest1)
{
  // execute Test logic
}

TEST_F(Test, SubTest2)
{
  // execute Test logic
}

TEST_F(Test, SubTest3)
{
  // execute Test logic
}
</code></pre></li>
</ol>

<blockquote>
  <p>Assumed that I want to display only <code>SubTest1</code> and <code>SubTest3</code>, what do I have to do? Important is, that I want to see at a central place (main method), which tests are actually executed.</p>
</blockquote>

<p>I thought, that I can ""stack"" filters as in the following example, but this approach did not work:</p>

<pre><code>int main(int argc, char** argv)
{
  ::testing::InitGoogleMock(&amp;argc, argv);

  ::testing::GTEST_FLAG(filter) = ""Test.SubTest1"";
  ::testing::GTEST_FLAG(filter) = ""Test.SubTest3"";
  return RUN_ALL_TESTS();
}
</code></pre>

<p>→ The second filter removed the first one and only <code>SubTest3</code> is executed.</p>
",https://stackoverflow.com/questions/52402135/how-can-i-combine-test-filters-in-the-unit-testing-framework-google-test,"['c++', 'googletest']",2587,TRUE,4,2
Passing a mock DOM event to component method in Angular for unit testing,"<p>I am trying to test a method in one of my components as follows:</p>

<pre><code>toggle(event: Event): void {
    event.stopPropagation();
    this.isCollapsed = !this.isCollapsed;
}
</code></pre>

<p>I cannot find a way to pass the event object to the method in the unit test case for example:</p>

<pre><code>test('it should call stop propagation when toggled', () =&gt; {
    testHostComponent.toggleLineBreakDown(mockEventGoesHere, 0);
});
</code></pre>
",https://stackoverflow.com/questions/51521775/passing-a-mock-dom-event-to-component-method-in-angular-for-unit-testing,"['angular', 'unit-testing', 'jasmine']",17289,TRUE,4,1
How to inject a HttpSession and HttpServletRequest when unit-testing dropwizard in junit5?,"<p>This is very frustrating. I am building an application using dropwizard and testing it with <strong>junit5</strong> and the <strong>dropwizard-testing</strong> module (the junit5 version). Then, I am trying to test a simple endPoint in a resource. The endpoint receives a HttpSession (and the request) but it is always <code>null</code>. I have read a lot but I can not find how to inject the session.</p>

<p>This is my Resource:</p>

<pre><code>@POST
@Path(""/doStuff"")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_HTML)
public String doStuff(@Session HttpSession session
        , @Context HttpServletRequest request) {
     // Do the stuff with the session and the request
}
</code></pre>

<p>My test is something like this:</p>

<pre><code>@ExtendWith(DropwizardExtensionsSupport.class)
class MyResourceTest {
    ResourceExtension resources = ResourceExtension.builder()
        .addResource(new MyResource())
        .build();


    @BeforeEach
    void setup() {
    }

    @Test
    void testDoStuff() {
        Response response = resources.target(""/api/doStuff"")
            .request(MediaType.APPLICATION_FORM_URLENCODED)
            .accept(MediaType.TEXT_HTML)
            .post();
        System.out.println(response);
    }
}
</code></pre>

<p>I need to manipulate the session and the request by test.  Is it possible? all help is appreciated.</p>
",https://stackoverflow.com/questions/52929726/how-to-inject-a-httpsession-and-httpservletrequest-when-unit-testing-dropwizard,"['java', 'unit-testing', 'dropwizard', 'junit5']",874,TRUE,3,2
How to Use css selectors in jest unit testing while using css modules,"<p>I'm using css modules in my react project and using web pack for bundling. While using Jest for testing, as the jest will try to import css files like normal JS files got the below error,</p>

<blockquote>
  <p>SyntaxError: Unexpected token .</p>
</blockquote>

<p>The solution that I found is to use ""identity-obj-proxy"" to mock scss/css files.But now I cannot use css selectors to test components.For example</p>

<h3>Test</h3>

<pre><code>it('renders 2 children', () =&gt; {
  expect(component.find('.mockyApp').children().length).toBe(2);
});
</code></pre>

<h3>render method</h3>

<pre><code>render() {
  if (this.state.host) {
    return (
      &lt;div className={style.mockyApp}&gt;
        &lt;div className={style.sidePage}&gt;
          &lt;SideBar clickHandler={this.setPage} selected={this.state.page}/&gt;
        &lt;/div&gt;
        &lt;div className={style.mainPage}&gt;
          {this.renderComponent()}
        &lt;/div&gt;
     &lt;/div&gt;
  );
 }
// ... .. rest of render method
}
</code></pre>

<p>I'm using <strong>import style from './mocky.scss';</strong> to import styles and using the style object for class names. Before using css-modules the above test used to work.Now my question is how will I be able to test using css selectors and what change needs to be done to make this work?. Googling didn't help </p>
",https://stackoverflow.com/questions/48252638/how-to-use-css-selectors-in-jest-unit-testing-while-using-css-modules,"['javascript', 'reactjs', 'enzyme', 'jestjs', 'css-modules']",8155,TRUE,3,1
"&quot;Couldn&#39;t find object&quot; error with Silverstripe 4 unit testing, how to fixed it?","<p>""Couldn't find object"" error with Silverstripe 4 unit testing, how to fixed it?.</p>

<p>with silverstripe 4 unit test, im getting a error ""Couldn't find object 'transaction1' "".
can anyone suggest what's happening here?. Thanks.</p>

<pre><code>class CustomerCreditTransactionTest extends SapphireTest 
{



protected static $fixture_file = BASE_PATH.'/mysite/code/CustomerCreditTransactionTest.yml';


/**
 * @var string
 */
protected $readingmode = null;
/**
 * Default reading mode
 *
 * @var string
 */
protected $defaultMode = null;


public function setUp()
{
    $this-&gt;readingmode = 'Original';
    $this-&gt;defaultMode = 'Original';
}
public function tearDown()
{
    MirroredData::SetCurrentReadingStage($this-&gt;readingmode);
    MirroredData::SetDefaultWritingStage($this-&gt;defaultMode);
}


public function testCustomerName()
{
    $obj = $this-&gt;objFromFixture(CustomerCreditTransaction::class, 'transaction1');

    $this-&gt;assertEquals(
        'John@gmail.com',
        $obj-&gt;CustomerName(),
        'customer name is : '.$obj-&gt;CustomerName()
    );
}

 }
</code></pre>
",https://stackoverflow.com/questions/52074064/couldnt-find-object-error-with-silverstripe-4-unit-testing-how-to-fixed-it,"['php', 'silverstripe', 'silverstripe-4', 'phpunit']",225,FALSE,3,1
Unit testing method which only calls a single dependency method - c#/xUnit/Moq,"<p>Ashamed to admit it, but unit testing is still new to me. I have a pretty firm grasp on how to handle things properly. But a situation I find hard to understand the point of is when writing a unit test for a method that simply returns the result of a dependency method invocation. </p>

<p>I find it's come up a few times in situations where you're implementing a service layer to interop with your DAL layer.</p>

<p>A trivial code example will probably better describe what I'm asking.</p>

<blockquote>
  <p>Note: The code example below is using <strong>c#, xUnit and Moq</strong>.</p>
</blockquote>

<pre><code>public class Foo {
    Bar int;
    Baz string;
}

public interface IFooRepository {
    Foo GetByBar(bar int);
}

public interface IFooService {
    Foo GetByBar(bar int);
}

public class FooService : IFooService {
    private IFooRepository fooRepository;

    public FooService(
        IFooRepository fooRepository){
        this.fooRepository = fooRepository; 
    }

    public Foo GetByBar(bar int)
    {
        return fooRepository.GetByBar(bar);
    }
}

[Fact]
public class FooServiceTests 
{
    public class GetByBarMethod 
    {
        [Fact]
        public void ShouldReturnBar()
        {
            //arrange
            var expectedFoo = new Foo() { Bar = 1, Baz = ""baz"" };
            var repo = new Mock&lt;IFooRepository&gt;();
            repo.Setup(r =&gt; r.GetByBar(1)).Returns(expectedFoo);

            var service = new FooService(repo.Object);

            //act
            var result = service.GetByBar(1);

            //assert
            Assert.Same(result, expectedFoo);
        }
    }   
}
</code></pre>

<p>I understand that the point of the <code>FooService</code> unit tests is to test the logic within the methods, not that of the dependencies. So is there even a point to write a test in this case, if it's simply testing a mocked dependency's return value?</p>
",https://stackoverflow.com/questions/52121867/unit-testing-method-which-only-calls-a-single-dependency-method-c-xunit-moq,"['c#', 'moq', 'xunit']",368,TRUE,2,1
ERROR in TypeError: Cannot read property &#39;length&#39; of undefined - Angular 2.0 Unit Testing,"<p>I am able to successfully run the test application with ""ng test"" but whenever I'm making any change at run time to the test file I'm end up getting below error. I have tried couple of solutions mentioned in below links but no luck. Please help me to resolve this issue.</p>

<p><strong>Package.json</strong></p>

<pre><code>{
  ""name"": ""testing-demo"",
  ""version"": ""0.0.0"",
  ""license"": ""MIT"",
  ""angular-cli"": {},
  ""scripts"": {
    ""ng"": ""ng"",
    ""start"": ""ng serve"",
    ""lint"": ""tslint \""src/**/*.ts\"" --project src/tsconfig.json --type-check &amp;&amp; tslint \""e2e/**/*.ts\"" --project e2e/tsconfig.json --type-check"",
    ""test"": ""ng test"",
    ""pree2e"": ""webdriver-manager update --standalone false --gecko false"",
    ""e2e"": ""protractor""
  },
  ""private"": true,
  ""dependencies"": {
    ""@angular/cli"": ""^1.2.0"",
    ""@angular/common"": ""^2.3.1"",
    ""@angular/compiler"": ""^2.3.1"",
    ""@angular/core"": ""^2.3.1"",
    ""@angular/forms"": ""^2.3.1"",
    ""@angular/http"": ""^2.3.1"",
    ""@angular/platform-browser"": ""^2.3.1"",
    ""@angular/platform-browser-dynamic"": ""^2.3.1"",
    ""@angular/router"": ""^3.3.1"",
    ""core-js"": ""^2.4.1"",
    ""rxjs"": ""^5.0.1"",
    ""ts-helpers"": ""^1.1.1"",
    ""zone.js"": ""^0.7.2""
  },
  ""devDependencies"": {
    ""@angular/cli"": ""^1.6.7"",
    ""@angular/compiler-cli"": ""^2.3.1"",
    ""@ngtools/webpack"": ""^1.6.2"",
    ""@types/jasmine"": ""2.5.38"",
    ""@types/node"": ""^6.0.42"",
    ""codelyzer"": ""~2.0.0-beta.1"",
    ""jasmine-core"": ""2.5.2"",
    ""jasmine-spec-reporter"": ""2.5.0"",
    ""karma"": ""1.2.0"",
    ""karma-chrome-launcher"": ""^2.0.0"",
    ""karma-cli"": ""^1.0.1"",
    ""karma-coverage"": ""^1.1.1"",
    ""karma-jasmine"": ""^1.0.2"",
    ""karma-remap-istanbul"": ""^0.2.1"",
    ""protractor"": ""~4.0.13"",
    ""puppeteer"": ""^1.0.0"",
    ""ts-node"": ""1.2.1"",
    ""tslint"": ""^4.3.0"",
    ""typescript"": ""2.5.3""
  }
}
</code></pre>

<p><a href=""https://github.com/angular/angular-cli/issues/5053"" rel=""nofollow noreferrer"">https://github.com/angular/angular-cli/issues/5053</a></p>

<p><a href=""https://stackoverflow.com/questions/45219750/angular-cli-typescript-throws-cannot-read-property-length-of-undefined"">Angular CLI - Typescript throws: Cannot read property &#39;length&#39; of undefined</a></p>

<p>Pasting entire error for the reference -</p>

<pre><code>ERROR in TypeError: Cannot read property 'length' of undefined
    at createSourceFile (C:\testing-demo\node_modules\typescript\lib\typescri
pt.js:8982:109)
    at parseSourceFileWorker (C:\testing-demo\node_modules\typescript\lib\typ
escript.js:8941:26)
    at Object.parseSourceFile (C:\testing-demo\node_modules\typescript\lib\ty
pescript.js:8900:26)
    at Object.createSourceFile (C:\testing-demo\node_modules\typescript\lib\t
ypescript.js:8728:29)
    at new TypeScriptFileRefactor (C:\testing-demo\node_modules\@ngtools\webp
ack\src\refactor.js:79:35)
    at Object.findLazyRoutes (C:\testing-demo\node_modules\@ngtools\webpack\s
rc\lazy_routes.js:18:22)
    at AotPlugin._findLazyRoutesInAst (C:\testing-demo\node_modules\@ngtools\
webpack\src\plugin.js:216:50)
    at _donePromise.Promise.resolve.then.then.then.then.then (C:\testing-demo
\node_modules\@ngtools\webpack\src\plugin.js:494:24)
    at process._tickCallback (internal/process/next_tick.js:109:7)
</code></pre>
",https://stackoverflow.com/questions/48616646/error-in-typeerror-cannot-read-property-length-of-undefined-angular-2-0-uni,"['angular', 'karma-jasmine']",1125,FALSE,2,0
"Stencil, Leaflet, unit testing component, gives TypeError: Cannot read property &#39;deviceXDPI&#39; of undefined","<p>So we are developing a Stenciljs component which wraps leaflet map and adds some additional functionality. </p>

<p>Now obviously we don't want or need to test Leaflet, but instead, just the parts in our wrapper components.</p>

<p>So, using the test examples, we create our tests, </p>

<pre><code>import { LeMap } from ""./le-map"";

describe(""Map component tests"", () =&gt; {
    it(""Should build the map component"", async () =&gt; {
        const map = new LeMap();
        expect(map).not.toBeNull();
    });     
});
</code></pre>

<p>try and load the components and test the public functions, but we get </p>

<pre><code>TypeError: Cannot read property 'deviceXDPI' of undefined

&gt; 1 | import {Component, Element, Listen, Method, Prop, Watch} from 
'@stencil/core';
&gt; 2 | import L from 'leaflet';
    | ^
  3 |
  4 | @Component({
  5 |       shadow: false,
</code></pre>

<p>We believe this message is because the test is trying to render leaflet, and because it's not a true browser, it can't detect a view so throwing this error, so we've tried to mock leaflet in the tests, but still get the same problem.</p>

<p>We're tried to mock the leaflet module by using jest mocking</p>

<pre><code>jest.genMockFromModule('leaflet');
</code></pre>

<p>but this made no diffrence</p>

<p>Only idea I've had is to separate the logic from the components, but that feels wrong, as we'd just be doing this for purpose of testing.</p>

<p>Versions in use are: leaflet: 1.3.4, @stencil: 0.15.2, jest: 23.4.2</p>

<p>Any other suggestions?</p>

<p>Further investigation with, thanks to @skyboyer 's suggestions, leads me to this line of the leaflet core browser.js file</p>

<p>leads me to this line of the leaflet core browser.js file</p>

<pre><code>export var retina = (window.devicePixelRatio || (window.screen.deviceXDPI/window.screen.logicalXDPI)) &gt; 1;
</code></pre>

<p>But I'm unable to mock the screen property of window as I get the following error </p>

<pre><code>[ts] Cannot assign to 'screen' because it is a constant or a read-only property, 
</code></pre>

<p>so I try the following.</p>

<pre><code>const screen =  {
    deviceXDPI:0,
    logicalXDPI:0
}

Object.defineProperty(window, 'screen', screen);
Object.defineProperty(window, 'devicePixelRatio', 0);
</code></pre>

<p>Same error, completely ignores this, so I try over riding the export.</p>

<pre><code>jest.spyOn(L.Browser,'retina').mockImplementation(() =&gt; false);
</code></pre>

<p>No joy either, so tried </p>

<pre><code>L.Browser.retina = jest.fn(() =&gt; false); 
</code></pre>

<p>but get it tells me it's a constant and can't be changed (yet the implication stats var so ¯_(ツ)_/¯ )</p>

<p>Anything else I can try?</p>

<p>Further update, 
I've managed to mock the window, but this sadly doesn't solve it.</p>

<pre><code>const screenMock = {            
    deviceXDPI: 0,
    logicalXDPI: 0          
}

const windowMock = {
    value: {
        'devicePixelRatio': 0,
        'screen': screenMock
    }
}
Object.defineProperty(global, 'window', windowMock);
</code></pre>

<p>If I console log this, I get the right properties but as soon as I test the instantiation of the component it fails with</p>

<pre><code>  TypeError: Cannot read property 'deviceXDPI' of undefined
</code></pre>

<p>Reading around it seems Leaflet doesn't check for a DOM and just tries to render anyway, I can't see anyway around this, I saw a leaflet-headless package, but I don't know how I could swap them out just for testing.</p>

<p>Think I will need to look at another strategy for testing, probably protractor.</p>
",https://stackoverflow.com/questions/53612772/stencil-leaflet-unit-testing-component-gives-typeerror-cannot-read-property,"['unit-testing', 'leaflet', 'jestjs', 'jsdom', 'stenciljs']",1485,TRUE,2,1
Unit Testing an ASP.Net Web API Controller that relies on the User.Identity object,"<p>I'll start by saying that I am reasonably new to unit testing, but I'm a firm believer now. I always had a tester at my previous jobs so I never had to worry about this.</p>

<p>I have an ASP.Net MVC API that is replacing a web service. The API takes an HTTP Post from a web application, logs the request to that database and then makes a request and returns data from another database. The web service that it is replacing had the additional overhead of making sure the user name submitted with the request is the logged in user. To replace this, I am using the site authentication and the associated controller's User.Identity object.</p>

<p>Now I need to write a unit test for this. I can use Moq to mock up an authenticated user for an MVC controller, but can't seem to find how to mock up the authenticated user for an API. Here is what I am trying to do:</p>

<pre><code>... // In the test method
        DbApiController controller = new DbApiController ();
        controller.ControllerContext = GetMockContext();
...

    private HttpControllerContext GetMockContext()
    {
        var identity = new GenericIdentity(""testuser"");
        var controllerContext = new Mock&lt;HttpControllerContext&gt;();
        var principal = new Mock&lt;IPrincipal&gt;();
        principal.Setup(p =&gt; p.IsInRole(""SalesAndEstimating""));
        principal.SetupGet(p =&gt; p.Identity.Name).Returns(""testuser"");
        controllerContext.SetupGet(c =&gt; c.RequestContext.Principal).Returns(principal.Object);

        return controllerContext.Object;
    }
</code></pre>

<p>I am getting the exception:</p>

<pre><code>System.NotSupportedException: Invalid setup on a non-virtual (overridable in VB) member: mock =&gt; mock.RequestContext
</code></pre>

<p>What am I doing wrong here?</p>

<p>Updated Code:</p>

<pre><code>        ApiController controller = new DbApiController();

        var context = new Mock&lt;HttpContextBase&gt;();

        var identity = new GenericIdentity(""testuser"");
        identity.AddClaim(new Claim(""http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier"", ""1""));
        var principal = new GenericPrincipal(identity, new[] { ""user"" });
        context.Setup(s =&gt; s.User).Returns(principal);

        controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);

        var results = ((DbApiController)controller).Post(...);

        Assert.AreEqual(results.Success, true);
</code></pre>

<p>After I made the changes above, I still get the error ""Argument 3: cannot convert from 'System.Web.Http.ApiController' to 'System.Web.Mvc.ControllerBase'"".</p>
",https://stackoverflow.com/questions/49652919/unit-testing-an-asp-net-web-api-controller-that-relies-on-the-user-identity-obje,"['c#', 'unit-testing', 'asp.net-web-api']",1253,TRUE,2,3
Why does my Oracle DataSource have a replay error only when unit testing?,"<p>My Spring Boot 1.5.17 (Spring 4.3.20) server works fine with bootRun or when deployed.</p>

<p>However, I have an Oracle DataSource that fails <strong>only when unit-testing</strong>:</p>

<blockquote>
  <p>java.lang.AssertionError: Server is sending a non-null replay context
  but our replayModes=[]</p>
</blockquote>

<p>A Google Search for this error doesn't have exact results.</p>

<p>I am able to unit-test with a different Oracle database.</p>

<p>I get the error with a full Application testing context</p>

<pre><code>@RunWith(SpringRunner.class)
@SpringBootTest(
        webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
        classes = { TestingUserConfiguration.class, Application.class }
)
</code></pre>

<p>As well as just the single DataSource config and Service</p>

<pre><code>@RunWith(SpringRunner.class)
@SpringBootTest(classes = {
        MyDbConfig.class,
        MyService.class
})
</code></pre>

<p>Both <code>oracle.jdbc.pool.OracleDataSource</code> and <code>oracle.jdbc.replay.OracleConnectionPoolDataSourceImpl</code> have the error.
UCP makes no difference.</p>

<p><code>OracleConnectionPoolDataSourceImpl</code> has a different error:</p>

<blockquote>
  <p>java.sql.SQLException: Unsupported feature</p>
</blockquote>

<p>Tried upgrading from OJDBC 12.2 to 2018.3, no difference.</p>

<p>Has anyone seen this error before?
Any ideas on why it only appears with Spring unit tests?</p>
",https://stackoverflow.com/questions/53383705/why-does-my-oracle-datasource-have-a-replay-error-only-when-unit-testing,"['oracle', 'spring-boot', 'jdbc']",2272,TRUE,2,2
Kafka: Are there are examples on how to use Mockito for unit testing Kafka?,"<p>I have a producer application that needs unit testing. I don't want to spin up a Zookeeper and Kafka server for this purpose. Is there a simpler way to test it using Mockito?</p>
",https://stackoverflow.com/questions/49417720/kafka-are-there-are-examples-on-how-to-use-mockito-for-unit-testing-kafka,"['unit-testing', 'apache-kafka', 'mockito']",17158,TRUE,8,2
How to exclude Folder (components) for unit testing in Angular 4 using Karma config?,"<p>I am using angular cli version 1.4.5 and below is the karma.conf.ts file</p>

<pre><code>module.exports = function (config) {
  config.set({
  basePath: '',
  exclude: [
     ""src/app/components/panel/panel.component.spec.ts"",
     ""src/app/components/accordion/accordion.component.spec.ts""
   ],
   frameworks: ['jasmine', '@angular/cli'],
   plugins: [
     require('karma-jasmine'),
     require('karma-chrome-launcher'),
     require('karma-jasmine-html-reporter'),
     require('karma-coverage-istanbul-reporter'),
     require('@angular/cli/plugins/karma')
   ],
   client:{
     clearContext: false 
   },
   coverageIstanbulReporter: {
     reports: [ 'html', 'lcovonly' ],
     fixWebpackSourcePaths: true
   },
   angularCli: {
     environment: 'dev'
   },
   reporters: ['progress', 'kjhtml'],
   port: 9876,
   colors: true,
   logLevel: config.DEBUG,
   autoWatch: true,
   browsers: ['Chrome'],
   singleRun: false
 });
};
</code></pre>

<p>and I even added the exclude in the tsconfig.spec.json file to exclude to pick those files for test. </p>

<pre><code>{
 .....,
 ""include"": [
 ""**/*.spec.ts"",
 ""**/*.d.ts""
 ],
 ""exclude"": [
     ""app/components/panel/panel.component.spec.ts"",
     ""app/components/accordion/accordion.component.spec.ts""
 ]
}
</code></pre>

<p>is that am missing something to add for exclusion ?</p>
",https://stackoverflow.com/questions/48637506/how-to-exclude-folder-components-for-unit-testing-in-angular-4-using-karma-con,"['angular', 'karma-jasmine']",5754,TRUE,7,1
How to add tap action for button in &quot;Unit Testing&quot; and show Alert,"<p>I am trying to write a unit test case for my Login Form, in this if Username and Password empty then we click login button it will show alert, i want to write testcases for this scenario, for me button action not working and alert not showing with unit testing , i am searching for solution long time any one could help..Thanks! </p>
",https://stackoverflow.com/questions/49321917/how-to-add-tap-action-for-button-in-unit-testing-and-show-alert,"['ios', 'unit-testing', 'xctest', 'uialertcontroller']",5956,TRUE,1,1
Angular Unit Testing RouterLink error TypeError: null is not an object (evaluating &#39;this.urlSerializer.serializer&#39;),"<p>I have component which display some image and a routerLink in a a tag. Now I am not able to fix the test case for the component, I remove the routerLink from the component Html test case is passing I am sharing my code let me know if some more information is needed.</p>

<p>Error Message: 
TypeError: null is not an object (evaluating 'this.urlSerializer.serializer')</p>

<pre><code>&lt;div  class=""error-page""&gt;
  &lt;div class=""padding-bottom""&gt;
    &lt;img role=""button"" class=""img-fluid"" alt=""Infinity Insurance"" src=""/assets/KemperAuto-Infinity_Logo.png""&gt;
  &lt;/div&gt;
  &lt;div class=""error-header my-3""&gt;&lt;h1&gt;{{'errorMessages.errorHeader' | translate}}&lt;/h1&gt;
    &lt;h3&gt;{{'errorMessages.errorHeaderDescription' | translate}}&lt;/h3&gt;
  &lt;/div&gt;
  &lt;div class=""error-description my-5""&gt;
    &lt;h1&gt;Error Code: {{statusCode}}&lt;/h1&gt;
    &lt;h2&gt;Trace Id: {{traceId}}&lt;/h2&gt;
    &lt;h3&gt;{{""errorMessages.""+ errorKey | translate}}&lt;/h3&gt;
  &lt;/div&gt;
  &lt;div class=""error-alternative""&gt;
    &lt;h3&gt;{{'errorMessages.errorAlternative' | translate}}&lt;/h3&gt;
    &lt;a [routerLink]=""[checkEmptyString(location) ? '/' : location]"" class=""btn btn-primary p-3 mr-3""&gt;&lt;i class=""fas fa-sync""&gt;&lt;/i&gt; {{'errorMessages.errorAlternativeOptionOne' | translate}}&lt;/a&gt;
    &lt;a href=""mailto:support@infinity.com?subject=Internal Server Error Message"" class=""btn btn-secondary p-3""&gt;&lt;i class=""fas fa-envelope""&gt;&lt;/i&gt; {{'errorMessages.errorAlternativeOptionTwo' | translate}}&lt;/a&gt;
  &lt;/div&gt;
&lt;/div&gt;
</code></pre>

<p>test case file </p>

<pre><code>import {ComponentFixture, TestBed} from '@angular/core/testing';
import {ErrorPageComponent} from './error-page.component';
import {TranslateModule, TranslateService} from '@ngx-translate/core';
import {configureTestSuite} from ""../../../../test/configuretest.spec"";
import {ErrorService} from ""../../../services/errorhandler/error.service"";
import {ErrorPageModule} from ""./error-page.module"";
import {ModalModule} from ""ngx-bootstrap"";
import {Router, RouterModule} from ""@angular/router"";
import {MockRouter} from ""../../../../test/classes/MockRouter"";
import {RouterTestingModule} from ""@angular/router/testing"";


describe('ErrorPageComponent', () =&gt; {
  let component: ErrorPageComponent;
  let fixture: ComponentFixture&lt;ErrorPageComponent&gt;;
  const mockRouter = new MockRouter();
  configureTestSuite();
  beforeAll((done) =&gt; (async () =&gt; {
    TestBed.configureTestingModule({
      declarations: [],
      imports: [

        ModalModule.forRoot(),
        ErrorPageModule,
        RouterTestingModule.withRoutes([{ path: '/error', component: ErrorPageComponent }]),
        TranslateModule.forRoot(),
      ],
      providers: [
        ErrorService,
        {provide: Router, useValue: mockRouter},
        TranslateService
      ]
    })
      await TestBed.compileComponents();
  })().then(done).catch(done.fail));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(ErrorPageComponent);
    component = fixture.componentInstance;
    component.ngOnInit();
    // component.location = '/';
    fixture.detectChanges();
  });

  it('should create', () =&gt; {
    expect(component).toBeDefined();
  });
});
</code></pre>
",https://stackoverflow.com/questions/53962138/angular-unit-testing-routerlink-error-typeerror-null-is-not-an-object-evaluati,"['angular', 'unit-testing']",176,FALSE,1,0
local variable for unit testing in python to verify functionality of test function,"<p>I am new to unit test &amp; python. I am starting with unit testing for different modules (developed in c) in python. In some of the case, I found that function will not return any value &amp; will not modify the value of any global variable. </p>

<p>In such case, How I will verify the functionality of the function based on some local variables value. As local will not be available outside the function, I can't verify the value of the local variable. What should be the right way unit test such functions? </p>

<p>I have gone through below links for asking this, which says we should not perform the unit test for a local variable. </p>

<p><a href=""https://stackoverflow.com/questions/28688057/override-python-function-local-variable-in-unittest"">override python function-local variable in unittest</a></p>

<p>Here I can see some methods which can be used to test the local variable at the end of function execution. 
<a href=""https://coderanch.com/t/679691/engineering/test-local-variable-method-junit"" rel=""nofollow noreferrer"">https://coderanch.com/t/679691/engineering/test-local-variable-method-junit</a></p>

<p>Is there is any way by which we can export the local variable for the unit test that function? </p>
",https://stackoverflow.com/questions/53223246/local-variable-for-unit-testing-in-python-to-verify-functionality-of-test-functi,"['python', 'c', 'unit-testing']",2716,TRUE,2,1
Difference between assertRaises in a with versus statement for Unit Testing in Python?,"<p>I am unit testing in python and I was told the with raises is the correct procedure versus the plain statement? Why is this?</p>

<pre><code>def test_update(self):
   with self.assertRaises(object.api_call) as error:
         browser_update.fill_fields()
    self.assertEqual(error.exception.code, -1)
</code></pre>

<p>versus</p>

<pre><code>def test_update(self):
    self.assertRaises(object.api_call, browser_update.fill_fields)
</code></pre>
",https://stackoverflow.com/questions/51620312/difference-between-assertraises-in-a-with-versus-statement-for-unit-testing-in-p,"['python', 'unit-testing']",34,FALSE,1,0
C# Unit Testing - Actual: (null) Result using List in xUnit with Moq Framework,"<p>Good day,</p>

<p>I'm new in Unit Testing using xUnit and Moq Framework in C#.</p>

<p>I'm trying to test an method wherein it returns list the method is responsible for returning list of info from Queryable method inside the repository class.</p>

<p>Here's my test method.</p>

<pre><code>[Fact]
public void SelectInfoByName_InfoHasValue_ReturnInfoSelect()
{
    var service = new Mock&lt;ISearchInfoRepository&gt;();

    var selectInfo = new SelectInfoService(null, service.Object);

    service.Setup(s =&gt; s.SearchInfoByName(""info"")).Returns(new List&lt;Info&gt;
    {
        new Info{ Name = ""name1"",InfoId = 1},
        new Info{Name = ""name2"",InfoId = 2}
    }.AsQueryable);

    var expectedResult = new List&lt;Info&gt;
    {
        new Info{Name = ""name1"", InfoId = 1},
        new Info{Name = ""name2"", InfoId = 2}
    };

    var result = selectInfo.SelectInfoByName(""info"").Result;

    Assert.Equal(expectedResult, result);
}
</code></pre>

<p>Here's my <code>SelectInfoByName</code> responsible for returning the list of info by name</p>

<pre><code>public async Task&lt;IEnumerable&lt;SearchSelect&gt;&gt; SelectInfoByName(string info)
{
    var infoByName = searchInfoRepo.SearchInfoByName(info);

    return await infoByName.Select(info =&gt; new SearchSelect
    {
        text = info.Name,
        value = info.InfoId
    }).ToListAsync();
}
</code></pre>

<p>Lastly, here's my repository or storage class where it communicates with the database using EF.</p>

<pre><code>// storage or repo class
public IQueryable&lt;Info&gt; SearchInfoByName(string info)
{
    return infoRepo.Info().Where(info =&gt; info.Name.Contains(name.Trim().ToLower()));
}
</code></pre>

<p>Note: Change from <code>.AsyncState</code> to <code>.Result</code> but still, the actual value is <code>null</code></p>

<p>Thank you in advance. </p>
",https://stackoverflow.com/questions/50742408/c-unit-testing-actual-null-result-using-list-in-xunit-with-moq-framework,"['c#', 'mocking', 'moq', 'xunit', 'xunit.net']",2142,TRUE,1,2
Unit Testing Core API Controller Using Custom HttpClient and Polly policy within ConfigureServices,"<p>I have problems performing unit testing when using <code>Polly</code> and <code>HttpClient</code>.</p>

<p>Specifically, Polly and HttpClient are used for ASP.NET Core Web API Controller following the links below:</p>

<p><a href=""https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests</a></p>

<p><a href=""https://github.com/App-vNext/Polly/wiki/Polly-and-HttpClientFactory"" rel=""nofollow noreferrer"">https://github.com/App-vNext/Polly/wiki/Polly-and-HttpClientFactory</a>  </p>

<p>The problems (1 and 2) are specified at the bottom. I wonder if this is the correct way to using <code>Polly</code> and <code>HttpClient</code>.</p>

<p><strong>ConfigureServices</strong></p>

<p>Configure Polly policy and sepecify custom HttpClient, <code>CustomHttpClient</code></p>

<pre><code>  public void ConfigureServices(IServiceCollection services)
{
   services.AddHttpClient();
   services.AddHttpClient&lt;HttpClientService&gt;()                                
                .AddPolicyHandler((service, request) =&gt;
                    HttpPolicyExtensions.HandleTransientHttpError()
                        .WaitAndRetryAsync(3,
                            retryCount =&gt; TimeSpan.FromSeconds(Math.Pow(2, retryCount)))
                );
 }
</code></pre>

<p><strong>CarController</strong> </p>

<p>CarController depends on <code>HttpClientService</code>, which is injected by the framework automatically without explicit registration. </p>

<p>Please note that <code>HttpClientService</code> causes issues with unit test as <code>Moq</code> cannot mock a non virtual method, which is mentioned later on.</p>

<pre><code> [ApiVersion(""1"")]
    [Route(""api/v{version:apiVersion}/[controller]"")]
    [ApiController]
    public class CarController : ControllerBase
    {
        private readonly ILog _logger;
        private readonly HttpClientService _httpClientService;
        private readonly IOptions&lt;Config&gt; _config;

        public CarController(ILog logger, HttpClientService httpClientService, IOptions&lt;Config&gt; config)
        {
            _logger = logger;
            _httpClientService = httpClientService;
            _config = config;
        }

        [HttpPost]
        public async Task&lt;ActionResult&gt; Post()
        {  

            using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
            {
                string body = reader.ReadToEnd();

                    var statusCode = await _httpClientService.PostAsync(
                        ""url"",
                        new Dictionary&lt;string, string&gt;
                        {
                            {""headerID"", ""Id""}                           
                        },
                        body);
                    return StatusCode((int)statusCode);               
            }
        }
      }
</code></pre>

<p><strong>HttpClientService</strong> </p>

<p>Simiar to <code>CarController</code>, <code>HttpClientService</code> has an issue with Unit test, because <code>HttpClient</code>'s PostAsync cannot be mocked. <code>HttpClient</code> is injected by the framework automatically without explicit registration. </p>

<pre><code> public class HttpClientService
{
    private readonly HttpClient _client;
    public HttpClientService(HttpClient client)
    {
        _client = client;
    }

    public async Task&lt;HttpStatusCode&gt; PostAsync(string url, Dictionary&lt;string, string&gt; headers, string body)
    {
        using (var content = new StringContent(body, Encoding.UTF8, ""application/json""))
        {
            foreach (var keyValue in headers)
            {
                content.Headers.Add(keyValue.Key, keyValue.Value);
            }

            var response = await _client.PostAsync(url, content);

            response.EnsureSuccessStatusCode();
            return response.StatusCode;
        }

    }
</code></pre>

<p><strong>Problem 1</strong></p>

<p>Unit Test: <code>Moq</code> cannot mock <code>HttpClientService</code>'s <code>PostAsync</code> method. I CAN change it to virtual, but I wonder if it is the best option.</p>

<pre><code>public class CarControllerTests
    {
        private readonly Mock&lt;ILog&gt; _logMock;
        private readonly Mock&lt;HttpClient&gt; _httpClientMock;
        private readonly Mock&lt;HttpClientService&gt; _httpClientServiceMock;
        private readonly Mock&lt;IOptions&lt;Config&gt;&gt; _optionMock;
        private readonly CarController _sut;


        public CarControllerTests()  //runs for each test method
        {
            _logMock = new Mock&lt;ILog&gt;();
            _httpClientMock = new Mock&lt;HttpClient&gt;();
            _httpClientServiceMock = new Mock&lt;HttpClientService&gt;(_httpClientMock.Object);
            _optionMock = new Mock&lt;IOptions&lt;Config&gt;&gt;();
            _sut = new CarController(_logMock.Object, _httpClientServiceMock.Object, _optionMock.Object);
        }

            [Fact]
               public void Post_Returns200()
            {
                    //System.NotSupportedException : Invalid setup on a non-virtual (overridable in VB) member
                        _httpClientServiceMock.Setup(hc =&gt; hc.PostAsync(It.IsAny&lt;string&gt;(),
                        It.IsAny&lt;Dictionary&lt;string, string&gt;&gt;(),
                        It.IsAny&lt;string&gt;()))
                    .Returns(Task.FromResult(HttpStatusCode.OK));
                    }
             }


}
</code></pre>

<p><strong>Problem 2</strong></p>

<p>Unit test: similar to <code>HttpClientService</code>,  <code>Moq</code> cannot mock <code>HttpClient</code>'s <code>PostAsync</code> method.</p>

<pre><code>  public class HttpClientServiceTests
{
        [Fact]
           public void Post_Returns200()
        {

            var httpClientMock = new Mock&lt;HttpClient&gt;();

            //System.NotSupportedException : Invalid setup on a non-virtual (overridable in VB) member
        httpClientMock.Setup(hc =&gt; hc.PostAsync("""", It.IsAny&lt;HttpContent&gt;()))
            .Returns(Task.FromResult(new HttpResponseMessage()));
            }

}
</code></pre>

<p>ASP.NET Core API 2.2</p>

<p><strong>Update</strong></p>

<p>Corrected a typo of CustomHttpClient to HttpClientService</p>

<p><strong>Update 2</strong></p>

<p><a href=""https://stackoverflow.com/questions/44715602/mock-httpclient-using-moq/44716910#44716910"">Solution</a> to problem 2</p>
",https://stackoverflow.com/questions/53958427/unit-testing-core-api-controller-using-custom-httpclient-and-polly-policy-within,"['c#', 'unit-testing', 'asp.net-core', '.net-core', 'asp.net-core-webapi']",1263,TRUE,1,1
Unit testing C Code in Visual Studio 2017 with Native Unit Test Project,"<p>I want to do Unit Tests for a C project in Visul Studio 2017. It is a embedded project lib. I want make as few changes as possible to lib. Just compile c code in VS I have added some #ifdef WIN32. It ok for added some more. </p>

<p>Started with using Visual C++ Native Unit Test Project. But run in problems when wanted test private static functions from C files and inject values varibales in project.  </p>

<ol>
<li>Include my embedded project as Static Library in to VS solution. (or should use Dynamic-Link library or something else?)</li>
<li>Created Native Unit Test Project, and gave it the name <em>UnitTest1</em>.</li>
<li>In UnitTest1 added this line as I understand it will include the my lib that want test. 
<code>#pragma comment(lib, ""../Release/Embedded.lib"")</code></li>
<li><p>In the embedded code header file I added this Macro to create lib that I will preform the test on.</p>

<pre><code>#pragma once<li>
<code>#ifdef EXPORT_TEST_FUNCTIONS</code>
<code>#define UNITTEST_Embedded_EXPORT __declspec(dllexport)</code>
<code>#else</code>
<code>#define UNITTEST_Embedded_EXPORT</code>
<code>#endif</code><li>

inline UNITTEST_ZAP_EXPORT static bool isActiv(void);</code></pre>

<ol start=""5"">
<li>In the embedded C file, I added this line <code>#define EXPORT_TEST_FUNCTIONS</code> and this function:</li>
</ol>

<p><pre><code>UNITTEST_ZAP_EXPORT static bool isActiv();
{
    return false;
}</code></pre></li></p>

<ol start=""6"">
<li>But when I build <em>UnitTest1</em> get error LNK2001.</li>
</ol></li>
</ol>

<p>Very unsure how to proceed to make it work. Anyone who can guide me through my problem? I would like to be able to test all functions in C code. Hope it not hard understand what want get help with. I have only developed couple of years.</p>
",https://stackoverflow.com/questions/50737053/unit-testing-c-code-in-visual-studio-2017-with-native-unit-test-project,"['c', 'visual-studio', 'unit-testing', 'embedded', 'lib']",2001,FALSE,1,1
Karma unit testing webpack:API fatal error handler returned after process out of memory,"<p>I am trying to execute karma unit test cases for my project. When I run the whole test cases which are available in the application, it is failing with the below error. But when I configure to run fewer test cases by executing all the controllers in a folder, it works. How to increase the memory size to execute all the test cases.</p>

<p>Tried searching but couldn't get any working solutions. Any guidance would be helpful.`</p>

<pre><code>$ karma start karma.conf.js


#
# Fatal error in , line 0
# API fatal error handler returned after process out of memory
#
/c/Users/AB18082/AppData/Roaming/npm/karma: line 14: 20164 Segmentation fault      node ""$basedir/node_modules/karma-cli/bin/karma"" ""$@""
</code></pre>

<p><strong>EDIT 1:</strong></p>

<p>When i try to increase size</p>

<pre><code>$ node --max_old_space_size=10240 node_modules/karma/bin/karma start karma.conf.js

&lt;--- Last few GCs ---&gt;

[13860:002BF998]   214803 ms: Scavenge 1021.9 (1358.6) -&gt; 1021.6 (1365.1) MB, 146.9 / 0.0 ms  allocation failure
[13860:002BF998]   217090 ms: Mark-sweep 1026.8 (1365.9) -&gt; 1014.7 (1355.9) MB, 2263.4 / 0.0 ms  allocation failure GC in old space requested
[13860:002BF998]   217243 ms: Scavenge 1022.6 (1359.5) -&gt; 1022.5 (1363.5) MB, 75.4 / 0.0 ms  allocation failure
[13860:002BF998]   217479 ms: Scavenge 1029.7 (1364.1) -&gt; 1029.6 (1366.6) MB, 225.5 / 0.0 ms  allocation failure


&lt;--- JS stacktrace ---&gt;
Cannot get stack trace in GC.
FATAL ERROR: NewSpace::Rebalance Allocation failed - process out of memory
</code></pre>

<p><strong>EDIT 2:</strong></p>

<p>After setting those node --max_old_space_size=4096 changes my application itself is not loading now. tried uninstalling the nodejs and cleared </p>

<ul>
<li>npm and npm-cache directories from %appdata% directory</li>
</ul>

<p>Now getting these error when i start the application also.</p>

<pre><code>FATAL ERROR: Committing semi space failed. Allocation failed - process out of memory
1: 00BF287E
2: 00FD3013
3: 00FD1B24
4: 00FD16FC
</code></pre>

<p>EDIT:3</p>

<p>After so much googling able to fix loading the application using the below cmd and still the testing is having the same issue.</p>

<pre><code>env NODE_OPTIONS=--max_old_space_size=2048 node node_modules/webpack/bin/webpack
</code></pre>
",https://stackoverflow.com/questions/51070599/karma-unit-testing-webpackapi-fatal-error-handler-returned-after-process-out-of,"['angularjs', 'node.js', 'webpack', 'karma-jasmine']",1035,TRUE,1,1
Unit Testing a JS script with Jest: Can I mock an ES6 class,"<p>when I import a class from a module</p>

<pre><code>const { OAuth2Client } = require('google-auth-library');
</code></pre>

<p>How can I mock it ?</p>

<pre><code>jest.mock(""google-auth-library"");  // not mocking directly OAuth2Client

jest.mock(""google-auth-library"", OAuth2Client ) // is incorrect
</code></pre>

<p>And if I add the online implementation, I don't have the class name</p>

<pre><code>jest.mock(""google-auth-library"", () =&gt; {
   return jest.fn().mockImplementation(() =&gt; {
      return {
        setCredentials: setCredentialsMock,
        getAccessToken: getAccessTokenMock
      }
   })
});
</code></pre>

<p>so I cannot call the constructor :</p>

<pre><code>const oAuth2Client = new OAuth2Client({...});
</code></pre>

<p>Feedback welcome</p>

<p><strong>UPDATE 1 --</strong></p>

<p>Here as the most important coding from google-auth-library-nodejs related  to my issue</p>

<p><strong>google-auth-library-nodejs module</strong></p>

<p><strong>=======================================
/src/auth/index.ts</strong>
        ...
        export {.., OAuth2Client,...} from './auth/oauth2client';
        ...
        const auth = new GoogleAuth();
        export {auth, GoogleAuth};</p>

<pre><code>    =======================================
    /src/auth/oauth2client.js

    import {AuthClient} from './authclient';
    ...
    export class OAuth2Client extends AuthClient {
      ....
      constructor(clientId?: string, clientSecret?: string, redirectUri?: string);
      constructor(
         ...
        super();
        ...
        this._clientId = opts.clientId;
        this._clientSecret = opts.clientSecret;
        this.redirectUri = opts.redirectUri;
        ...
      }
      ...
      getAccessToken(): Promise&lt;GetAccessTokenResponse&gt;;
      ...
    }
</code></pre>

<p><strong>=======================================
/src/auth/authclient.ts</strong></p>

<pre><code>    import {Credentials} from './credentials';
    ...
    export abstract class AuthClient extends EventEmitter {
       ...
      setCredentials(credentials: Credentials) {
        this.credentials = credentials;
      }
    }
</code></pre>

<p><strong>=======================================
/src/auth/credentials.js</strong></p>

<pre><code>    export interface Credentials {
      refresh_token?: string|null;
      expiry_date?: number|null;
      access_token?: string|null;
      token_type?: string|null;
      id_token?: string|null;
    }
    ...
</code></pre>
",https://stackoverflow.com/questions/53740341/unit-testing-a-js-script-with-jest-can-i-mock-an-es6-class,"['javascript', 'mocking', 'jestjs', 'es6-class']",2435,TRUE,1,1
"We use uiSpec4J for unit testing the GUI, what to do with JDK9?","<p>The last <a href=""https://github.com/UISpec4J/UISpec4J"" rel=""nofollow noreferrer"">Github</a> commit to UiSpec4J was back in 2015.<br>
Seeing that it doesn't support JDK9 (it has a lot of dependancies on JDK internal API)  </p>

<p>I'd like to hear suggestions to alternatives for testing the application through GUI interaction.  </p>

<p>Kind regards.</p>

<hr>

<p><strong>note:</strong> Seeing this kind of questions is prohibited,<br>
may i suggest people with such line of questions to the javahelp-reddit<br>
<a href=""https://www.reddit.com/r/javahelp/"" rel=""nofollow noreferrer"">https://www.reddit.com/r/javahelp/</a></p>
",https://stackoverflow.com/questions/48296090/we-use-uispec4j-for-unit-testing-the-gui-what-to-do-with-jdk9,"['java', 'unit-testing', 'user-interface', 'java-9']",251,FALSE,1,0
How to import or inject AngularJS services in Angular 2 in Unit testing,"<p>I have one service of my own in AngularJS. I have used it in one of my component in Angular 2. Now when i write unit test for the component I am not able to import or inject that service. Can anyone help me out here with this issue.</p>
",https://stackoverflow.com/questions/49972882/how-to-import-or-inject-angularjs-services-in-angular-2-in-unit-testing,['angularjs'],190,TRUE,0,1
Angular JS Unit testing: how to test function in service that doesn&#39;t return,"<p>I'm sorry for possible duplicate, I didn't find any solution for my problem.</p>

<p>I'm need to write tests for a service in Angular JS app.</p>

<p>So I have one main function that returns and uses as an external method. And a couple help functions for external. So how can I call and test things inside help functions (<code>subFunc</code>)?</p>

<p>service.js</p>

<pre><code>function TestService() {
  return {
    mainFunc: mainFunc
  };

  funcion mainFunc() {
    //do some and call subFunc()
    subFunc(a)
  }

  function subFunc(a) {
    if (a === 1) {
      // ... magic 1
      return true;
    } else {
      // ... magic 2
      return false;
    }
  }
}
})()
</code></pre>

<p>service.spec.js</p>

<pre><code>describe('Test Service', function() {
  beforeEach(module('TestService'));
  var TestService;

  beforeEach(inject(function($injector) {
      TestService = $injector.get('TestService');
  }));

  it('should return true if subFunc called with 1', function () {
    // ....
  });
})
</code></pre>
",https://stackoverflow.com/questions/52893267/angular-js-unit-testing-how-to-test-function-in-service-that-doesnt-return,"['javascript', 'angularjs', 'unit-testing', 'karma-jasmine']",39,FALSE,0,1
Hyperledger composer unit testing using Cucumber. TypeError: Cannot read property &#39;getClassDeclaration&#39; of null,"<p>I am using cucumber to run some unit tests on hyperledger composer.I am constantly getting this <strong>TypeError: Cannot read property 'getClassDeclaration' of null</strong> </p>

<p><strong>ASSET CODE IS</strong> </p>

<pre><code>asset Clicks identified by id {
  o String id
  o String ipAddress
  o String publisherId
  o String advertiserId
  o String CreatedAt
}
</code></pre>

<p><strong>TRANSACTION CODE IS</strong></p>

<pre><code>transaction Clicks_Add 
{
  o Clicks clicks
}
</code></pre>

<p><strong>CODE FOR THE TRANSACTION IN .JS FILE</strong></p>

<pre><code>/**
 * transaction
 * @param {org.adverce.Clicks_Add} Clicks_Add
 * @transaction
 * This transaction is used to add new users to an already created Advertiser.
 */

function Clicks_Add(newClick) {
    var factory = getFactory();
    var NS='org.adverce';
    var clicks = factory.newResource(NS,'Clicks',newClick.clicks.id);
    clicks.ipAddress = newClick.clicks.ipAddress;
    clicks.publisherId = newClick.clicks.publisherId;
    clicks.advertiserId = newClick.clicks.advertiserId;
    clicks.CreatedAt = newClick.clicks.CreatedAt;

    return getAssetRegistry('org.adverce.Clicks')
    .then(function(newclicks){
        newclicks.addAll([clicks]);
    })
}
</code></pre>

<p><strong>NOW THE CUCUMBER TEST THAT I WROTE IS THIS.</strong></p>

<pre><code>Feature: Want to test the Clicks transactions

  Scenario: Clicks Transaction send value to Clicks Assets

      Given I have deployed my network

      When I submit the following transaction of type org.adverce.Clicks_Add
        | id | ipAddress   | publisherId | advertiserId | CreatedAt |
        | 01 | 192.168.1.1 | 12          | 22           | 27/1/2017 |

      Then I should have the following Assets
       """"""
        [
        {""$class"":""org.adverce.Clicks"", ""id"":""01"", ""ipAddress"":""192.168.1.1"", ""publisherId"":""23"", ""advertiserId"":""22"", ""CreatedAt"":""27,1,2017""}
        ]
        """"""
</code></pre>

<p><strong>THE METHODS WRITTEN FOR THESE TESTS ARE</strong></p>

<pre><code>'use strict';


module.exports = function () {

    this.Given('I have deployed my network', function () {  
         // Write code here that turns the phrase above into concrete actions
        });

    this.When(/^I submit the following transactions? of type ([.\w]+)\.(\w+)$/, function (namespace, name, table) {
        return this.composer.submitTransactions(namespace, name, table);
    });

    this.Then(/^I should have the following Assets?$/, function (docString) {
        return this.composer.testAssets(null, null, docString);
        }); 

};
</code></pre>

<p>I will share the error screenshot here as well.</p>

<p><a href=""https://i.stack.imgur.com/is7b1.png"" rel=""nofollow noreferrer"">Error output in terminal after running the test</a></p>
",https://stackoverflow.com/questions/51821837/hyperledger-composer-unit-testing-using-cucumber-typeerror-cannot-read-propert,"['javascript', 'unit-testing', 'cucumber', 'hyperledger-composer', 'ibm-blockchain']",268,FALSE,0,1
.NET Unit Testing on Service that requires it run in it&#39;s own context,"<p>I am attempting to write unit tests for a windows service which runs as the business layer of a multi-tier application. It doesn't seem feasible to mock the functions of this. Ideally it would be nice to create an instance of the service in the test context. However, when running the service in test context I run into all sorts of issues because the service is running in the unit test context. Things like dlls and classes not being available or xml files missing because it's looking in the test bin directory rather than the service directory.</p>

<p>With all the in memory caching, etc we do, we need the service running in order to really test it. Is there a way to run the service in it's own context, rather than the test context and still unit test it? I feel like I'm at a loss here.</p>
",https://stackoverflow.com/questions/52524094/net-unit-testing-on-service-that-requires-it-run-in-its-own-context,"['c#', '.net', 'visual-studio', 'unit-testing']",296,FALSE,0,0
VueJS and Webpack: Unit Testing error -- do I need the default HelloWorld component?,"<p>I am using vue-cli with webpack for the first time and trying out the unit testing feature. However, I deleted the default HelloWorld.vue component because I didn't need that in my custom app. So, when running the following command in terminal I get a unit testing 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-js lang-js prettyprint-override""><code>$ npm run test

&gt; vuetemplate@1.0.0 test D:\Users\myName\Desktop\vue-cli-webpacktemplate
&gt; npm run unit


&gt; vuetemplate@1.0.0 unit D:\Users\myName\Desktop\vue-cli-webpacktemplate
&gt; jest --config test/unit/jest.conf.js --coverage

 FAIL  test\unit\specs\HelloWorld.spec.js
  ● Test suite failed to run

    Configuration error:

    Could not locate module @/components/HelloWorld (mapped as D:\Users\myName\Desktop\vue-cli-webpacktemplate\src\components/HelloWorld)

    Please check:

    ""moduleNameMapper"": {
      ""/^@\/(.*)$/"": ""D:\Users\myName\Desktop\vue-cli-webpacktemplate\src\$1""
    },
    ""resolver"": undefined

Test Suites: 1 failed, 1 total</code></pre>
</div>
</div>
</p>

<p>My question: I'd like to do unit testing on my app. Do I need to put that default HelloWorld component back in order to successfully do testing on my app? Or, is there a way to skip it? Not sure what to do here. Thanks.</p>
",https://stackoverflow.com/questions/48686006/vuejs-and-webpack-unit-testing-error-do-i-need-the-default-helloworld-compon,"['unit-testing', 'webpack', 'vuejs2']",159,FALSE,0,1
How to perform unit testing for a particular function in c# desktop application?,"<p>I have a function named LoadCitation.</p>

<pre><code>public void LoadCitation()
    {

        cmd = new SqlCommand(""select * from tbl_Users where isLogin=1"", con);
        sqlDataAdapter = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        sqlDataAdapter.Fill(ds);
        String username = ds.Tables[0].Rows[0][""username""].ToString();
        sqlDataAdapter = new SqlDataAdapter(""select id,title,author1_fname,author1_lname,author2_fname,author2_lname,author3_fname,author3_lname,doctype,year,publisher,abstract,nameofdoc,issue,volume,pgno,url,accessdate,notes,tag from tbl_Citation  where username ='"" + username + ""'"", con);
        DataSet = new DataSet();
        con.Open();
        sqlDataAdapter.Fill(DataSet, ""tbl_Citation"");
        con.Close();

        dgeviewcitation.DataSource = DataSet;
        dgeviewcitation.DataMember = ""tbl_Citation"";
    }
</code></pre>

<p>I want to perform unit testing for this method.</p>

<pre><code>[TestClass()]
public class EditcitationTests
{

    [TestMethod()]
    public void LoadCitationTest()
    {

    }
}
</code></pre>

<p>I have created method but didn't know what to write inside the function for unit testing...</p>
",https://stackoverflow.com/questions/52974822/how-to-perform-unit-testing-for-a-particular-function-in-c-desktop-application,"['c#', 'unit-testing']",88,TRUE,0,1
How can we do unit testing asynchronous functions using test package in angulardart?,"<p>I tried creating async function using angulardart code which will call internal service and from service will return response from a test url. How will i mock the particular function getUserDetails().</p>

<p><strong>login_component.html</strong></p>

<pre><code>&lt;div class=""container""&gt;
   &lt;button type=""button"" (click)=""getUserDetails()""&gt;Click me to see 
     details
   &lt;/button&gt;
&lt;/div&gt;
&lt;div *ngFor=""let user of userDetails""&gt;{{user.id}}&lt;/div&gt;
</code></pre>

<p><strong>login_component.dart:</strong></p>

<pre><code>Future&lt;Null&gt; getUserDetails() async {
 try {
   userDetails = await _loginService.userDetails();
   print(userDetails);
 } catch (e) {
   errMsg = e.toString();
 }
}
</code></pre>

<p><strong>login_service.dart:</strong></p>

<pre><code>Future&lt;dynamic&gt; userDetails() async {
    var _url = 'https://jsonplaceholder.typicode.com/users';
    try {
      var res = await _http.get(_url);
      var response = _extractData(res).map((value) =&gt; new 
      List.fromJson(value)).toList();
      return response;
       } catch (e) {
         print(e);
        }
}
dynamic _extractData(Response resp) =&gt; JSON.decode(resp.body);
</code></pre>

<p><strong>list.dart</strong></p>

<pre><code>class List {
  int id;
  String name;
  List(this.id, this.name);
  factory List.fromJson(Map&lt;dynamic, dynamic&gt; list) =&gt;
  new List(list['id'], list['name']);
  Map toJson() =&gt; {'id': id, 'name': name};
}
</code></pre>

<p>Please help me in finding out solution. Also how can i check the test code coverage in angulardart ?</p>
",https://stackoverflow.com/questions/50719520/how-can-we-do-unit-testing-asynchronous-functions-using-test-package-in-angulard,"['unit-testing', 'asynchronous', 'testing', 'dart', 'angular-dart']",106,TRUE,0,1
How to allow .Net Unit Testing to Reference .Net core 2 web application,"<p>I have a bit of a problem and I have tried researching it everywhere but I cannot find an answer. </p>

<p>I going to be doing TDD development in Visual studio using MSTesting (Unit Testing .Net). However, I am going to developing a web application running Asp.Net Core 2.</p>

<p>This is where I am having a problem, The Unit testing project is running .NET Framework 4.7.1 meaning I can not reference the web application. <strong>I CAN NOT CHANGE THE FRAMEWORK OF THE WEB APPLICATION.</strong></p>

<p>Please have a look at these screenshots:</p>

<p><a href=""https://i.stack.imgur.com/r9AeG.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/r9AeG.png"" alt=""Unit Testing application""></a></p>

<p><a href=""https://i.stack.imgur.com/z1FSA.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/z1FSA.png"" alt=""Web Application""></a></p>

<p><a href=""https://i.stack.imgur.com/0DKEL.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/0DKEL.png"" alt=""Error Message""></a></p>

<p>I can not change the framework of the web application and the unit testing cant use Core 2. Please Help Thanks.</p>
",https://stackoverflow.com/questions/50413620/how-to-allow-net-unit-testing-to-reference-net-core-2-web-application,"['c#', 'asp.net', '.net', 'unit-testing']",343,TRUE,0,1
How to make Unit Testing for a UITextField to see if is empty,"<p>I try to implement a Unit Test for a textfield to check if that textfield is empty but I'm getting the error <code>Unexpectedly found nil while unwrapping an Optional value</code>. And I'm using Guard but I don'w know what I'm doing wrong.</p>

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

<pre><code>class AdminPanelViewController: UITableViewController {

// Func to insert data from TextFields into CoreData
    func insertProduct(){

        guard let productName = productNameTextfield.text, productName != """" else{
            SCLAlertView().showError(Constants.nameRequired, subTitle: Constants.messageNameRequired)
            return
        }
        guard let productCategory = productCategoryTextField.text, productCategory != """" else{
            SCLAlertView().showError(Constants.categoryRequired, subTitle: Constants.messageCategoryRequired)
            return
        }
        guard let productPrice = productPriceTextfield.text, productPrice != """" else{
            SCLAlertView().showError(Constants.priceRequired, subTitle: Constants.messagePriceRequired)
            return
        }
        guard let productDescription = productDescriptionTextView.text, productDescription != """"else{
            SCLAlertView().showError(Constants.descriptionRequired, subTitle: Constants.messageDescriptionRequired)
            return
        }

        let product = Product(context: context) // Start inserting in Core Data
        let productUUID = UUID().uuidString
        product.id = productUUID
        product.name = productName
        product.category = productCategory
        product.price = Float(productPrice)!
        product.prodDescription = productDescription

        appDelegate.saveContext() // End inserting and save the content in Core Data
        resetAllFields()
        SCLAlertView().showSuccess(Constants.done, subTitle: Constants.messageProductAdded)
    }
}


// UNIT TESTING

import XCTest
@testable import ShoppingLand

class AdminPanelViewControllerTests: XCTestCase {

    var collection: AdminPanelViewController!

    // Test if ProductNameTextfield is empty
    func testIfProductNameTextfieldIsEmpty(){

        guard let productNameTextField = collection.productNameTextfield else{
            XCTFail(""Product name is required !"")
            return
        }
        productNameTextField.text = """"

        XCTAssertEqual(productNameTextField.text, ""Product name is required !"")
    }

}
</code></pre>

<p>Thank you so much for your time if you are reading this !</p>
",https://stackoverflow.com/questions/51250238/how-to-make-unit-testing-for-a-uitextfield-to-see-if-is-empty,"['ios', 'swift', 'unit-testing', 'swift4']",627,FALSE,0,0
"In unit testing loosely typed languages, should the return type of methods be checked?","<p>In strongly typed languages such as Java, there is no need to explicitly check the type of object returned since the code cannot compile if the return types do not match method signature.  Ex.  You cannot return a boolean when an integer is expected.</p>

<p>In loosely typed languages such as Ruby, JavaScript, Python, etc.,  anything can be returned.  Would it make sense to write a unit test that checks the type of object returned from a method?  This, in my opinion, will ensure that a boolean is returned where a boolean is expected.</p>

<p>Is it even necessary to have the Unit test below?</p>

<p>=============================</p>

<p>An attempt at Ruby example:</p>

<p>first_module.rb:</p>

<pre><code>module FirstModule
  TypeA = Struct.new(
    :prop1,
    :prop2)

  self.create_type_a
    TypeA.new(
      'prop1Val',
      'prop2Val')
  end
end
</code></pre>

<p>type_a_repository.rb:</p>

<pre><code>module TypeARepository
  def self.function_to_test
    FirstModule.create_type_a  # This will return TypeA object
  end
end
</code></pre>

<p>type_a_repository_spec.rb:</p>

<pre><code>RSpec.describe '' do
  describe '' do
    before do
      allow(FirstModule).to receive(:create_type_a)
          .and_return(FirstModule.create_type_a)
    end

    it '' do
      result = TypeARepository.function_to_test
      expect(result).to be_a(FirstModule::TypeA) # is this necessary?
    end
  end
end
</code></pre>
",https://stackoverflow.com/questions/52878197/in-unit-testing-loosely-typed-languages-should-the-return-type-of-methods-be-ch,"['javascript', 'python', 'ruby', 'unit-testing']",161,TRUE,6,1
Getting error while unit testing in angular:-&quot;TypeError: Illegal constructor at new SignalrWindow &quot;,"<p>I have used signalR in angular 4 project.
While performing unit test getting this error</p>

<blockquote>
  <p><strong>TypeError:</strong> Illegal constructor at new Signalr Window</p>
</blockquote>

<p>Below is the service code which is injected in component.</p>

<p>When I am trying to inject the same service in component while unit testing, I am getting this issue.</p>

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

<pre><code>export class SignalRService {

    starting$: Observable&lt;any&gt;;
    error$: Observable&lt;string&gt;;
    refreshData$: Observable&lt;any&gt;;
    wideAlert$: Observable&lt;any&gt;;
    updatedTime$: Observable&lt;any&gt;;

    // These are used to feed the public observables 
    private startingSubject = new Subject&lt;any&gt;();
    private errorSubject = new Subject&lt;any&gt;();
    private wideAlertSubject = new Subject&lt;any&gt;();
    private refreshDataSubject = new Subject&lt;any&gt;();
    private updatedTimeSubject = new Subject&lt;any&gt;();


    // These are used to track the internal SignalR state 
    public hubConnection: any;
    public hubProxy: any;


    signalrURL = ServiceConfig.URL.signalRURL ;
    signalRHubName  = ServiceConfig.HUB_NAME.dataHub ;

    constructor(@Inject(SignalrWindow) private window: SignalrWindow,
                @Inject(""channel.config"") private channelConfig: ChannelConfig, 
                private http: Http) {

        this.error$ = this.errorSubject.asObservable();
        this.starting$ = this.startingSubject.asObservable();
        this.refreshData$ = this.refreshDataSubject.asObservable();
        this.wideAlert$ = this.wideAlertSubject.asObservable();
        this.updatedTime$ = this.updatedTimeSubject.asObservable() ;

        this.hubConnection = this.window.$.hubConnection();
        this.hubConnection.url = this.signalrURL ;
        this.hubProxy = this.hubConnection.createHubProxy(this.signalRHubName);

        //Define handlers for any errors
        this.hubConnection.error((error: any) =&gt; {
           // Push the error on our subject
           this.errorSubject.next(error);
        });

       this.hubProxy.on('BroadcastRefresh',(data) =&gt; {
            this.refreshDataSubject.next(data);
       });

       this.hubProxy.on('BroadcastWideAlert', (data) =&gt; {
           this.wideAlertSubject.next(data);
       });

       this.hubProxy.on('BroadcastUpdatedTime', (data) =&gt; {
           this.updatedTimeSubject.next(data);
       });

    }


    start(): void {

        this.hubConnection.start()
            .done(() =&gt; {
                this.startingSubject.next();
            })
            .fail((error: any) =&gt; {
                this.startingSubject.error(error);
            });
    }
}
</code></pre>
",https://stackoverflow.com/questions/53882347/getting-error-while-unit-testing-in-angular-typeerror-illegal-constructor-at,"['angular', 'signalr', 'angular-unit-test']",1358,FALSE,0,0
Unit testing a Configuration in spring Batch which runs in spring boot application,"<p>I am Using Spring boot application to run  spring batch and I have a Config java class which loads all configuration related stuff like getting some values from properties file and setting them, calling reader,writers etc.</p>

<p>I am trying to run a junit for just few methods in that config class from my unit test class. how can we achieve that. I am trying to use SpringRunner Can someone through some light . </p>
",https://stackoverflow.com/questions/53870765/unit-testing-a-configuration-in-spring-batch-which-runs-in-spring-boot-applicati,"['java', 'spring', 'spring-batch']",386,FALSE,0,0
when unit testing shelljs doesn&#39;t use my mocked filesystem but the real one,"<p>in my node.js app I have a function that should rename directory path when the user do a http put request.
Anyway this function uses shelljs and when I test it manually it works but when I try to test in mocha on my mocked filesystem then shelljs run all the shell commands on my real file system.</p>

<p>How can I fix it?</p>

<p>btw I use mock-fs for this and I am very new to unit tests.</p>

<p>thanks </p>

<p>Amit</p>
",https://stackoverflow.com/questions/52169538/when-unit-testing-shelljs-doesnt-use-my-mocked-filesystem-but-the-real-one,"['node.js', 'unit-testing', 'mocking', 'mocha.js', 'shelljs']",240,FALSE,0,1
How to require rakefile for unit testing the tasks in Ruby (not rails)?,"<p>I have a spec that looks like this for testing the Rakefile tasks:</p>

<pre><code>require 'spec_helper'

describe 'Rakefile' do
  describe ""redeem_orders"" do
    context ""with default paths"" do
      subject { Rake::Task['redeem_orders'].invoke }

      let(:input_path) { ""./public/input/orders.csv"" }
      let(:output_path) { ""./public/output/redemptions.csv"" }

      it ""transfer the data from input to output path"" do
        expect(DataController).to receive(:transfer).with(
          input_path: input_path,
          output_path: output_path,
          input_format: kind_of(Proc),
          output_format: kind_of(Proc)
        )

        subject
      end
    end

    context ""with different paths"" do
      subject { Rake::Task['redeem_orders'].invoke(some_new_input_path, some_new_output_path) }

      let(:some_new_input_path) { ""./some/new/path/orders.csv"" }
      let(:some_new_output_path) { ""./some/new/path/redemptions.csv"" }

      it ""transfer the data from input to output path"" do
        expect(DataController).to receive(:transfer).with(
          input_path: some_new_input_path,
          output_path: some_new_output_path,
          input_format: kind_of(Proc),
          output_format: kind_of(Proc)
        )

        subject
      end
    end
  end
end
</code></pre>

<p>How do I actually require the Rakefile? Currently these tasks aren't found. What's the best way to do this? I can't seem to require the <code>Rakefile</code>. When I put <code>require 'Rakefile'</code> on top, it fails to find the file. What can I do? Is <code>require</code> appending an <code>.rb</code> or something at the end of this file?</p>

<p>this is my tree:</p>

<pre><code>├── Gemfile
├── Gemfile.lock
├── Rakefile
├── Readme.md
├── lib
│   ├── chocolates
│   │   └── chocolate_totals_calculator.rb
│   ├── data
│   │   ├── csv_processor.rb
│   │   ├── data_controller.rb
│   │   ├── data_processor.rb
│   │   ├── file_processor_factory.rb
│   │   └── file_type_processor.rb
│   ├── errors
│   │   └── errors.rb
│   └── promotions
│       └── chocolates
│           ├── chocolate_promotion.rb
│           ├── dark_chocolate_promotion.rb
│           ├── milk_chocolate_promotion.rb
│           ├── promotions_factory.rb
│           ├── sugar_free_chocolate_promotion.rb
│           └── white_chocolate_promotion.rb
├── public
│   ├── input
│   │   └── orders.csv
│   └── output
│       └── redemptions.csv
└── spec
    ├── chocolates
    │   └── chocolate_totals_calculator_spec.rb
    ├── data
    │   ├── csv_processor_spec.rb
    │   ├── data_controller_spec.rb
    │   ├── data_processor_spec.rb
    │   ├── file_processor_factory_spec.rb
    │   └── file_type_processor_spec.rb
    ├── fixtures
    │   └── test_orders.csv
    ├── integration
    │   └── orders_to_redemptions_spec.rb
    ├── promotions
    │   └── chocolates
    │       ├── chocolate_promotion_spec.rb
    │       ├── dark_chocolate_promotion_spec.rb
    │       ├── milk_chocolate_promotion_spec.rb
    │       ├── promotions_factory_spec.rb
    │       ├── sugar_free_chocllate_promotion_spec.rb
    │       └── white_chocolate_promotion_spec.rb
    ├── rakefile_spec.rb
    └── spec_helper.rb
</code></pre>
",https://stackoverflow.com/questions/50973527/how-to-require-rakefile-for-unit-testing-the-tasks-in-ruby-not-rails,"['ruby-on-rails', 'ruby']",157,FALSE,0,0
Checking For Json response is true or false in unit testing with Nunit?,"<p>This is my method..</p>

<pre><code>  public ActionResult AddModelAliasData(ModalAliasModel modalAliasModel)
    {
        if (!ModelState.IsValid)
        {
            ModelState.LogModelStateError();
            throw new BusinessException(""COMMON_ERROR"");
        }
        var response = _vehicleDataBusinessService.AddModelAliasData(modalAliasModel);
        return Json(response);
    }
</code></pre>

<p>As i am new to unit testing ... I am confused for some things, for the given above method in controller we are getting the json response in return. I want to check whether the return Json we are getting  back has success true or false How should i do it???</p>

<p>The Response object result is</p>

<pre><code> public class GetVehicleDataAliases : DefaultResponse
{
    public List&lt;SearchData&gt; FindData { get; set; }
    public List&lt;VehicleDto&gt; MakeDtos { get; set; }
}
</code></pre>

<p>The defaultResponse are Success , ErrorCode, ErrorMessage</p>

<p>I had wrote the unit test for this </p>

<pre><code>  [Test]
    public void ShouldReturnJsonInAddMakeAlias()
    {
        var data = new GetVehicleDataAliases
        {
            MakeDtos = new List&lt;VehicleDto&gt;(),
            Success = true,
            FindData = new List&lt;SearchData&gt;()
        };

        mockVehicleDataBusinessService.Setup(x =&gt; x.AddMakeAliasData(It.IsAny&lt;MakeAliasModel&gt;())).Returns(() =&gt; data);
        var vehicleDataController = new VehicleDataController(mockVehicleDataBusinessService.Object);
        var result = vehicleDataController.AddMakeAliasData(makeAliasModel) as JsonResult;

        Assert.AreEqual(data, result.Data);
    }
</code></pre>

<p>But I am Able to clarify that is it the Right way to check for True or False Json result</p>
",https://stackoverflow.com/questions/49355844/checking-for-json-response-is-true-or-false-in-unit-testing-with-nunit,"['c#', 'unit-testing', 'nunit']",341,FALSE,0,0
"Getting NPE while unit testing a class using JUnit, Spring 4 and Vaadin","<p>I am trying to unit test a very basic class that is extending some classes from <code>Vaadin</code> framework. But I am getting <code>NullPointerException</code> when I run the test.</p>

<p>Do I need to mock the <code>UI</code> class? Please guide.</p>

<p><strong>Error Log:</strong></p>

<pre><code>into the enter method......

java.lang.NullPointerException
    at com.jpmorgan.tss.payhub.template.views.MainView.enter(MainView.java:46)
    at com.jpmorgan.tss.payhub.template.views.MainViewTest.testEnter(MainViewTest.java:17)
    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:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    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><strong>MainViewTest.java</strong></p>

<pre><code>public class MainViewTest {

    @Mock
    ViewChangeListener.ViewChangeEvent viewChangeEvent = Mockito.mock(ViewChangeListener.ViewChangeEvent.class);

    @Test
    public void testEnter() {
        MainView instance = new MainView();
        instance.enter(viewChangeEvent);
        assertNotNull(instance);
    }

}
</code></pre>

<p><strong>MainView.java (Class Under Test)</strong></p>

<pre><code>@Component
@Scope(""prototype"")
@VaadinView(MainView.NAME)
@Title(""Mortgage Banking"")
@Theme(""PymtTemplateUI"")
public class MainView extends VerticalLayout implements View {

    @PostConstruct
    public void PostConstruct() {
    }

    @Override
    public void enter(ViewChangeListener.ViewChangeEvent event) {
        System.out.println(""into the enter method......"");
        UI ui = UI.getCurrent();
        Navigator nav = ui.getNavigator();
        nav.navigateTo(""homePageView"");
    }

}
</code></pre>
",https://stackoverflow.com/questions/52878129/getting-npe-while-unit-testing-a-class-using-junit-spring-4-and-vaadin,"['java', 'spring', 'junit', 'vaadin', 'spring-junit']",253,TRUE,0,1
Unit testing: Sending complex object as a input parameter to my test method using MSTest,"<p>I'm trying to send a <code>List&lt;DataStatusItem&gt;</code> as a input parameter to my unit test method using <code>DataRow</code> attribute as below,</p>

<pre><code>[TestClass]
public class UpdateProcessingTestController
{
    private List&lt;DataStatusItem&gt; DataStatusItemsTestSetup = new List&lt;DataStatusItem&gt;() {
            new DataStatusItem { DataItemID = 1, DataItemCurrentStatusID = 1, DataItemStatusID = 1, DateEffective = DateTime.Now }
    };

    private readonly Mock&lt;IEmployee&gt; moqEmployee;

    public UpdateProcessingTestController()
    {
        moqEmployee = new Mock&lt;IEmployee&gt;();
    }

    [TestMethod]
    [DataRow(DataStatusItemsTestSetup, 1, 8, 1)] // **This is where it is throwing me compilation error**
    public void SetDataItems(List&lt;DataStatusItem&gt; DataStatusItems,int brand, int dataType, int processingStatus)
}
</code></pre>

<p>Please let me know how to send the List as a input parameter to my test method.</p>
",https://stackoverflow.com/questions/51345370/unit-testing-sending-complex-object-as-a-input-parameter-to-my-test-method-usin,"['c#', 'unit-testing', 'mstest']",10735,TRUE,10,1
Unit testing custom Input React Component to be used with redux-form Fails,"<blockquote>
  <p>I am having a tough time testing the custom React Input Element.</p>
</blockquote>

<p>I have implemented a reusable Input React Component to be used both inside a ReduxForm and outside as well. It is as follows:</p>

<pre><code>&lt;!-- Unit Test --&gt;       
import React from 'react';
import ReactDOM from 'react-dom';
import { shallow, mount } from 'enzyme';
import 'jest-enzyme';
import InputField from '../InputField';
import { Field, reduxForm } from 'redux-form';


describe('InputField tests', () =&gt; {
   // MyForm.js
   function MyForm (props) {
    return (
      &lt;form&gt;
        &lt;Field label=""firstName"" name=""firstName"" placeholder=""test"" component={InputField}/&gt;
      &lt;/form&gt;
   );
 }

 var testForm = reduxForm({form: 'test'})(MyForm);

  test('InputField used as a Field on the redux-form', () =&gt; {
     let formFieldFixture = mount(&lt;testForm /&gt;);
     // let formFieldFixture = shallow(&lt;Field label=""firstName"" name=""firstName"" placeholder=""test"" component={InputField} withRef/&gt;);
     let fieldElem = formFieldFixture.find('label');
     expect(labelElem.text()).toEqual('firstName');
  });

});

&lt;!-- InputField.js --&gt; 
/**
 * InputField is a generic React component to be used for html input field both in the redux-form and otherwise.
 */
import React, { Component, PropTypes } from 'react';


const InputField = ({ name, input, label, placeholder, value, readOnly, meta }) =&gt; {
  const { touched, error, warning, dirty } = meta ? meta : {};
  let inputClasses = `text-input input--regular ${(touched &amp;&amp; error) ? 'validation-error' : ((touched &amp;&amp; warning) ? 'validation-warning' : '')}`;
  return (&lt;div&gt;
    &lt;label htmlFor={name}&gt;{label}&lt;/label&gt;
    {(readOnly) ? &lt;input type=""text"" value={value} className={inputClasses} placeholder={placeholder} readOnly /&gt; :
      &lt;input {...input} type=""text"" className={inputClasses} placeholder={placeholder} /&gt;}
    {touched &amp;&amp;
      ((error &amp;&amp; &lt;div className=""validation-error""&gt;{error}&lt;/div&gt;) ||
        (warning &amp;&amp; &lt;div className=""validation-error""&gt;{warning}&lt;/div&gt;))}
  &lt;/div&gt;);
};

export default InputField;
</code></pre>

<blockquote>
  <p>It fails on the line</p>
</blockquote>

<pre><code>  expect(labelElem.text()).toEqual('firstName'); with error     
</code></pre>

<blockquote>
  <p>ReferenceError: labelElem is not defined.</p>
</blockquote>

<p>What am I missing? or doing wrong.</p>
",https://stackoverflow.com/questions/50165387/unit-testing-custom-input-react-component-to-be-used-with-redux-form-fails,"['javascript', 'reactjs', 'redux-form']",469,FALSE,0,0
How can I create fake data and the data object for unit testing?,"<p>I have a class that implements a cache and I want to write a JUnit test for it.<br>
The class implements and interface with methods like:  </p>

<pre><code>public void insert(Object key, Object value);  
public Object getFromCache(Object key);
</code></pre>

<p>and the basic implementation is a singleton.<br>
I am writing a JUnit test but I don't know how to properly create a dummy cache with data in order to use for testing.<br>
Right now I am doing:  </p>

<pre><code>@Test
public void myTest() {  
    MyCache cache = MyCache.getInstance();  
    populateWithData(cache);  
    //test cache  
    asserEquals etc  
}  
</code></pre>

<p>How can I avoid using the <code>getInstance()</code> and not populate on each test?</p>
",https://stackoverflow.com/questions/53364170/how-can-i-create-fake-data-and-the-data-object-for-unit-testing,"['java', 'junit', 'junit5']",2091,TRUE,0,3
"Unit testing, is it a good idea to verify methods are not called","<p>Let's say you've got the following method to test:</p>

<pre><code>public void foo(object myObject, bool myBool)
{
     if(myBool)
        repositoryA.save(myObject)
     else
        repositoryB.save(myObject)
}
</code></pre>

<p>What is the best way to unit test such a function? If you write 2 tests 
 that assert repositoryA is called when myBool is true, and repositoryB is called when myBool is false, then the following change to the function would still make the tests pass but would potentially break the functionality of the application:</p>

<pre><code>public void foo(object myObject, bool myBool)
{
    repositoryA.save(myObject)
    repositoryB.save(myObject)
}
</code></pre>

<p>On the other hand, if you assert that when myBool is true then repositoryA is called AND that repositoryB is not called, that gives you more confidence that any change to the function will not introduce bugs, but then you have a test which depends on implementation details. What's the best way to do it?</p>

<p>And what if you use TDD, what tests would you write in order the reach the desired functionality?</p>
",https://stackoverflow.com/questions/52835424/unit-testing-is-it-a-good-idea-to-verify-methods-are-not-called,"['unit-testing', 'testing', 'tdd']",146,TRUE,0,2
How to do unit testing on a repository with putfile in the function,"<p>How to do unit testing on a repository with this in the function:</p>

<pre><code>\Storage::putFile($path, $file);
</code></pre>

<p>When I test this I get:</p>

<blockquote>
  <p>1) Tests\Unit\SellPageTest::testSellPageRepoStore Error: Call to a
  member function hashName() on integer</p>
</blockquote>
",https://stackoverflow.com/questions/52586909/how-to-do-unit-testing-on-a-repository-with-putfile-in-the-function,"['php', 'laravel', 'file', 'unit-testing', 'phpunit']",45,TRUE,0,1
Is there a way to accurately measure heap allocations in Unity for unit testing?,"<p>Allocating temporary objects on the heap every frame in Unity is costly, and we all do our best to avoid this by caching heap objects and avoiding garbage generating functions. It's not always obvious when something will generate garbage though. For example:</p>

<pre><code>enum MyEnum {
  Zero,
  One,
  Two
}

List&lt;MyEnum&gt; MyList = new List&lt;MyEnum&gt;();
MyList.Contains(MyEnum.Zero); // Generates garbage
</code></pre>

<p>MyList.Contains() generates garbage because the default equality comparer for List uses <code>objects</code> which causes boxing of the enum value types.</p>

<p>In order to prevent inadvertent heap allocations like these, I would like to be able to detect them in my unit tests.</p>

<p>I think there are 2 requirements for this:</p>

<ol>
<li>A function to return the amount of heap allocated memory</li>
<li>A way to prevent garbage collection occurring during the test</li>
</ol>

<p>I haven't found a clean way to ensure #2. The closest thing I've found for #1 is GC.GetTotalMemory()</p>

<pre><code>        [UnityTest]
        IEnumerator MyTest()
        {
          long before = GC.GetTotalMemory(false);
          const int numObjects = 1;
          for (int i = 0 ; i &lt; numObjects; ++i)
          {
            System.Version v = new System.Version();
          }
          long after = GC.GetTotalMemory(false);
          Assert.That(before == after); 
        }
</code></pre>

<p>The problem is that GC.GetTotalMemory() returns the same value before and after in this test. I suspect that Unity/Mono only allocates memory from the system heap in chunks, say 4kb, so you need to allocate &lt;= 4kb before Unity/Mono will actually request more memory from the system heap, at which point GC.GetTotalMemory() will return a different value. I confirmed that if I change numObjects to 1000, GC.GetTotalMemory() returns different values for before and after.</p>

<p>So in summary, 1. how can i accurately get amount of heap allocated memory, accurate to the byte and 2. can the garbage collector run during the body of my test, and if so, is there any non-hacky way of disabling GC for the duration of my test</p>

<p>TL;DR
Thanks for your help!</p>
",https://stackoverflow.com/questions/51579982/is-there-a-way-to-accurately-measure-heap-allocations-in-unity-for-unit-testing,"['unity-game-engine', 'garbage-collection', 'heap-memory']",712,TRUE,4,2
click dispatchEvent doesn&#39;t triggers the angular 6 directive while unit testing in Jasmine/Karma,"<p>This is my directive. It is directive for the rich text which is used in the html file in the [innerHtml] field.</p>

<pre><code>import { Directive, ElementRef } from '@angular/core';
import { Router } from '@angular/router';

@Directive({
  selector: '[appRichTextLink]'
})  

export class RichTextLinkDirective { 
  rawHTML: string;
  checkRouter = false;
  checkLink = false;
  constructor(public elem: ElementRef, private router: Router) {
    setTimeout(() =&gt; {
      if (this.elem.nativeElement.querySelectorAll) {
        const routerLinks: any[] = this.elem.nativeElement.querySelectorAll(""[href]"");
        const ref = this;
        if (routerLinks.length &gt; 0) {
          for (let i = 0; i &lt; routerLinks.length; i++) {
            routerLinks[i].addEventListener('click', function(e) {
              const hrefValue: string = this.getAttribute('href').toString();
              if (hrefValue !== """" &amp;&amp; hrefValue !== ""#"" &amp;&amp; hrefValue.indexOf('http://') === -1
                &amp;&amp; hrefValue.indexOf('https://') === -1 &amp;&amp; hrefValue.indexOf('//') === -1) {
                e.preventDefault();
                ref.router.navigate([hrefValue]);
              } else {
                window.open(hrefValue); 
                e.preventDefault();
                this.checkLink = true;
              }
            });
          }
        }
      }
    }, 2000);
  }
}
}
</code></pre>

<p>==============</p>

<p>This is my unit test. When the dispatch event triggers the url changes and the test breaks giving the error - ""VM435 main.js:946 GET <a href=""http://localhost:9876/test"" rel=""nofollow noreferrer"">http://localhost:9876/test</a> 404 (Not Found)"". Please help</p>

<pre><code>import { RichTextLinkDirective } from './rich-text-link.directive';
import { Component, DebugElement } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser'
import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { fakeAsync, tick } from '@angular/core/testing';
import { AppComponent } from 'src/app/app.component';
import { routes } from '../../app-routing.module'
import { from } from 'rxjs';
import {Location} from '@angular/common';
import { Router } from '@angular/router';


@Component({
  template: `&lt;p appRichTextLink type=""text"" [innerHtml]=""richText1""&gt;&lt;/p&gt;`
})
class TestingComponent {
  richText1 = ""&lt;!DOCTYPE html&gt; THIS IS A TEST COMPONENT&lt;a href=\""/test\""&gt;test&lt;/a&gt;&lt;a href=\""https://www.google.com\""&gt;shop products&lt;/a&gt;."";
}

describe('RichTextLinkDirective', () =&gt; {

  let fixture: ComponentFixture&lt;TestingComponent&gt;;
  let appFixture: ComponentFixture&lt;AppComponent&gt;;

  let directive: RichTextLinkDirective;
  let debugElement: DebugElement;

  let router: Router;
  let location: Location;
  //let hrefElements: any[];
  beforeAll(() =&gt; {
    TestBed.resetTestEnvironment();
    TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());
  });

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [RouterTestingModule.withRoutes(routes)],
      declarations: [TestingComponent, RichTextLinkDirective, AppComponent],
    })
      .compileComponents();
  }));
  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(TestingComponent);
    appFixture = TestBed.createComponent(AppComponent);

    debugElement = fixture.debugElement.query(By.directive(RichTextLinkDirective));
    directive = debugElement.injector.get&lt;RichTextLinkDirective&gt;(RichTextLinkDirective);

    router = TestBed.get(Router);
    location = TestBed.get(Location);

    fixture.detectChanges(); 
  });

  it('should create an instance', () =&gt; {
    const directive1 = new RichTextLinkDirective(null, null);
    expect(directive1).toBeTruthy();
  });

  it('should route to the desired link', fakeAsync(() =&gt; {
      const event = new MouseEvent('click', { bubbles: true, cancelable: true });
      tick(2000);
      const spy  = spyOn(TestBed.get(Router), 'navigate');
      directive.elem.nativeElement.querySelectorAll(""[href]"")[0].dispatchEvent(event);
      fixture.detectChanges(); 
      expect(spy).toHaveBeenCalledWith(['/test']); 
    }));
});
</code></pre>
",https://stackoverflow.com/questions/53425259/click-dispatchevent-doesnt-triggers-the-angular-6-directive-while-unit-testing,"['typescript', 'unit-testing', 'jasmine', 'karma-runner', 'angular7']",1230,FALSE,3,1
Unit testing mails won&#39;t work when it&#39;s created with a view in Laravel 5.5,"<p>I'm starting my test with <code>Mail::fake();</code>. Then, an event triggers a listener, which sends an email:</p>

<pre><code>Mail::send('path_to_a_view', $data, function(Message $message) {
    // set ""to"" and subject.
});
</code></pre>

<p>The listener implements the <code>ShouldQueue</code> interface.</p>

<p>In my test, I tried to check if the email was queued using <code>Mail::assertQueued(...);</code> (I've tried multiple class names for this method because I was not sure which would apply in my case).<br>
But as that always failed, I found out that the <code>send</code> method in the <code>MailFake</code> class rejects mails which were created with a view. Responsible for that behaviour is <a href=""https://github.com/laravel/framework/blob/v5.5.28/src/Illuminate/Support/Testing/Fakes/MailFake.php#L281"" rel=""nofollow noreferrer"">following line</a>.</p>

<p>Why does it simply return? And how can I test if my mail was queued?</p>
",https://stackoverflow.com/questions/48064346/unit-testing-mails-wont-work-when-its-created-with-a-view-in-laravel-5-5,"['php', 'laravel', 'unit-testing']",671,TRUE,3,1
Angular unit testing - How can I get the child component inside an overlay container,"<p>I have a custom component called <code>MatSelectControls</code> that is used like so:</p>

<pre><code>&lt;component-im-testing&gt;
   &lt;mat-select&gt;
      &lt;mat-select-controls&gt;&lt;/mat-select-controls&gt;
      &lt;mat-option *ngFor=""...""&gt;&lt;/mat-option&gt;
   &lt;/mat-select&gt;
&lt;/component-im-testing&gt;
</code></pre>

<p>In my test, I can retrieve the <code>MatSelect</code> instance like so:</p>

<pre><code>const matSelectRef = fixture.debugElement.query(By.directive(MatSelect));
const matSelect = matSelectRef.componentInstance as MatSelect;
matSelect.open();
</code></pre>

<p>But what I'm really after is the <code>MatSelectControls</code> component. Trying to select it the same way does not work:</p>

<pre><code>const matControlsRef = fixture.debugElement.query(By.directive(MatSelectControls)); //returns null
</code></pre>

<p>I'm assuming this doesn't work because the <code>MatSelectControls</code> actually renders inside of the cdk overlay that <code>MatSelect</code> creates.</p>

<p>How can I retrieve the <code>MatSelectControls</code> component instance even though it actually renders inside the cdk overlay?</p>
",https://stackoverflow.com/questions/53935191/angular-unit-testing-how-can-i-get-the-child-component-inside-an-overlay-conta,"['angular', 'angular-material2', 'angular-test']",1743,FALSE,3,1
When to use stubs/mocks and when to use real objects in unit testing?,"<p>I recently tried to improve my unit testing skills and read quite some literature about unit testing and I am also trying to realize what I learned in a php-project I am currently developing with phpunit. But I still have a in my opinion very fundamental question how to unit test methods which interact with objects of other classes or even with other methods of the same class.</p>

<p>Is there some rule of thumb or some help how I can decide what dependencies I should stub/mock and for what dependencies I should simply use a normal object? To clarify my question, here is an example code, with different scenarios:</p>

<pre><code>interface DependencyInterface {
    public method dependentMethod() { ... }
}
class Dependency implements DependencyInterface {...}

class ClassUnderTest {
    private $dependency
    public __construct(DependencyInterface $dependency) {
        $this-&gt;dependency = dependency;
    }
    public function methodUnderTest() {
        ...
        $result1 = $this-&gt;dependency-&gt;dependentMethod();
        ...
        $result2 = $this-&gt;otherMethod();
        ...
        $result3 = $this-&gt;usedInMultiplePublicMethods();
    }

    public function otherMethod() {...}
    private function usedInMultiplePublicMethods() {...}
}
</code></pre>

<p>So my questions are now for a unit test which tests the functionality of the method methodUnderTest, should I:</p>

<ol>
<li>stub the interface DependencyInterface and inject it in the constructor, or should I simply use an instance of the implementation Dependency?</li>
<li>partially stub the class ClassUnderTest itself to deliver a fixed result for otherMethod, since this maybe very complex method has already its own complete unit tests?</li>
<li>I decided to not unit tests private methods, since they are not part of the interface of the class (I know this is a controversial topic and is not the scope of my question). Do I have now to cover for each public method which uses the private method usedInMultiplePublicMethods all possible effects which may occur in the private method? Or should I only test all possible effects in one of the public methods which uses it and stub the private method in the tests for all other public methods?</li>
</ol>

<p>I am quite not sure about when to use stubbing/mocking and when not.</p>
",https://stackoverflow.com/questions/48176358/when-to-use-stubs-mocks-and-when-to-use-real-objects-in-unit-testing,"['php', 'unit-testing', 'mocking', 'phpunit']",963,TRUE,3,2
Unit testing - getting TypeError: You provided an invalid object where a stream was expected,"<p>I'm trying to do a unit test where an effect uses a service to fetch results from an API, then fires either a success action, or an error action. I keep getting the error <code>TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.</code>. Not entirely sure what needs to be changed to get this working.</p>

<p>Including the error check test and relevant code.</p>

<p>Angular</p>

<pre><code>Angular CLI: 7.1.4
Node: 10.5.0
OS: win32 x64
Angular: 7.1.4
... animations, cli, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.10.7
@angular-devkit/build-angular     0.10.7
@angular-devkit/build-optimizer   0.10.7
@angular-devkit/build-webpack     0.10.7
@angular-devkit/core              7.0.7
@angular-devkit/schematics        7.1.4
@angular/cdk                      7.2.0
@angular/material                 7.2.0
@ngtools/webpack                  7.0.7
@schematics/angular               7.1.4
@schematics/update                0.11.4
rxjs                              6.3.3
typescript                        3.1.6
webpack                           4.19.1
</code></pre>

<p>Test</p>

<pre><code>describe('ResultsEffects', () =&gt; {
    let store: jasmine.SpyObj&lt;Store&lt;FeatureState&gt;&gt;;
    let ebs: jasmine.SpyObj&lt;EBSService&gt;;
    let snackbar: jasmine.SpyObj&lt;SnackBarService&gt;;

    beforeEach(() =&gt; {
        store = jasmine.createSpyObj('store', ['pipe']);
        ebs = jasmine.createSpyObj('EBSService', ['getPollResults', 'getUserHasVoted', 'getSettings']);
        snackbar = jasmine.createSpyObj('SnackBarService', ['notify']);
    });

    describe('fetchResults', () =&gt; {
        it(`should dispatch 'FetchPanelResultsError'`, () =&gt; {
            const fetchAction = new FetchPanelResults();
            const error = { statusText: 'ERROR' };
            const errorAction = new FetchPanelResultsError({ error: error.statusText });
            const values = {
                a: fetchAction,
                e: errorAction
            };
            const source = cold('a', values);
            const expected = cold('--e', values);
            const actions = new Actions(source);

            ebs.getPollResults.and.returnValue(throwError(error));

            const effects = new ResultsEffects(
                actions,
                store,
                snackbar,
                ebs
            );

            expect(
                effects.fetchResults$({
                    debounce: 20,
                    scheduler: getTestScheduler()
                })
            ).toBeObservable(expected);
        });
    });
});
</code></pre>

<p>Effect</p>

<pre><code>@Effect()
fetchResults$ = ({ debounce = 500, scheduler = asyncScheduler } = {}) =&gt; this.actions$.pipe(
    ofType&lt;SetPanelResults&gt;(PanelResultsActionTypes.FETCH_PANEL_RESULTS),
    // need alternate method for this
    // withLatestFrom(this.featureState$),
    // map(([_, state]) =&gt; state.twitch.token),
    debounceTime(debounce, scheduler),
    switchMap((token) =&gt;
        this.ebs.getPollResults(token).pipe(
            map(res =&gt; new SetPanelResults(res.data.results)),
            catchError(error =&gt; of(new FetchPanelResultsError({ error: error.statusText })))
        )
    )
)
</code></pre>

<p>Service</p>

<pre><code>getPollResults(token: string): Observable&lt;PollResultsFetchData&gt; {
    const options = {
        headers: ebsHeaders(token)
    };

    return this.http.get&lt;PollResultsFetchData&gt;(`${this.ebsURL}/poll/results`, options);
}
</code></pre>

<p>Update: Added debounce to trigger the error with marbles. Still need alternative to <code>withLatestFrom</code>.</p>
",https://stackoverflow.com/questions/53919120/unit-testing-getting-typeerror-you-provided-an-invalid-object-where-a-stream,"['angular', 'jasmine', 'ngrx', 'jasmine-marbles']",2696,TRUE,2,2
Angular unit testing: How to serve css files now in karma with angular 6+,"<p>I wanna have material css in my specs. Before I had it like this in karma config:</p>

<pre><code>files: [
   // make sure material styles are served
   { pattern: './node_modules/@angular/material/prebuilt-themes/indigo-pink.css', watched: true, included: true, served: true },

   { pattern: './src/test.ts', watched: false }
]
</code></pre>

<p>But new projects don't have a files property anymore in karma config.</p>

<p>I tried adding it in angular.json but it doesnt work:</p>

<pre><code>""test"": {
      ...
      ""options"": {
        ""main"": ""src/test.ts"",
        ...
        ""karmaConfig"": ""src/karma.conf.js"",
        ""styles"": [
          ""node_modules/@angular/material/prebuilt-themes/indigo-pink.css"",
          ""src/styles.scss""
        ],
</code></pre>

<p>Any idea how to do it now?</p>
",https://stackoverflow.com/questions/52180410/angular-unit-testing-how-to-serve-css-files-now-in-karma-with-angular-6,"['angular', 'angular-cli', 'karma-jasmine', 'angular-cli-v6']",2397,TRUE,2,2
Create an iQueryable which is case insensitive for unit testing linq to entities - NSubstitute,"<p>I'm trying to unit test Linq to entities, I want to search for the same word in different casing and return the same word.</p>

<p>The current case is I'm trying to unit test searching for lower and uppercase words, EG ""Hi"" and ""hi"".</p>

<p>Linq to entities using entity framework currently supports this, I can search for both terms in a where clause and it does the work for me.</p>

<p><strong>Problem</strong>:
I am trying to make a mock querable that behaves the same:</p>

<pre><code> public class SimpleWord
    {
        public string Text;
    }

    [Test]
    public void someTest()
    {
        //arrange
        var lowerWords = new[] { ""hi"" };
        var upperWords = new[] { ""Hi"" };

        var wordsList = new List&lt;SimpleWord&gt; {new SimpleWord { Text = ""hi"" } };
        IDbSet&lt;SimpleWord&gt; wordsDbSet = Substitute.For&lt;DbSet&lt;SimpleWord&gt;, IDbSet&lt;SimpleWord&gt;&gt;();

        //set up the mock dbSet
        var dataAsList = wordsList.ToList();
        var queryable = dataAsList.AsQueryable();
        wordsDbSet.Provider.Returns(queryable.Provider);
        wordsDbSet.Expression.Returns(queryable.Expression);
        wordsDbSet.ElementType.Returns(queryable.ElementType);
        wordsDbSet.GetEnumerator().Returns(queryable.GetEnumerator());

        //act
        var resultLower = wordsDbSet.Where(wrd =&gt; lowerWords.Contains(wrd.Text)).ToList();
        var resultHigher = wordsDbSet.Where(wrd =&gt; upperWords.Contains(wrd.Text)).ToList();
        //assert
        Assert.That(resultHigher.Count, Is.EqualTo(1), ""did not find upper case"");
        Assert.That(resultLower.Count, Is.EqualTo(1), ""did not find lower case"");
    }
</code></pre>

<p>Question:
How do I make the wordsDbSet be case insensitive when i call a search on it when I do any .Where() search on it.</p>

<p><strong>I don't want to change the Acts:</strong></p>

<pre><code> var resultHigher = wordsDbSet.Where(wrd =&gt; 
                    upperWords.Contains(wrd.Text, StringComparer.OrdinalIgnoreCase)).ToList();
</code></pre>

<p><strong>The answer I'm looking for is a change to the arrange:</strong></p>

<pre><code>wordsDbSet.When(contains.IsCalled).Return(contains.OrdinalIgnoreCasing)
</code></pre>

<p>Thanks for looking!</p>
",https://stackoverflow.com/questions/50906643/create-an-iqueryable-which-is-case-insensitive-for-unit-testing-linq-to-entities,"['c#', 'linq', 'linq-to-sql', 'linq-to-entities', 'nsubstitute']",884,TRUE,1,1
Assertion Error (200 Success != 400 Bad Request) while unit testing a Dockerized Flask App,"<p>Okay, I am struggling with this problem for 2 days now. When I am manually posting data in the form in the browser, everything works fine, and I am getting the flash message that should say 'Thanks...'. While testing my Flask application, this test does not pass because I am getting a 400 Bad Request error while sending a post request on my Flask form. To be clear, I am using Flask-Mail and WTForms for the form, and my application is dockerized and also running redis and celery. I am kinda new to these stuff, so if my question is not clear enough, please be kind and tell me if I should provide more detailed info. Thanks, and here is the relevant code and the error that is shown while testing with py.test. And sorry about the links, I am still not allowed to post pictures on StackOverflow.</p>

<p>The error code:
<a href=""https://i.stack.imgur.com/jiSyB.jpg"" rel=""nofollow noreferrer"">Pytest Assertion Error</a></p>

<p><strong>contact/forms.py:</strong></p>

<pre><code>from flask_wtf import FlaskForm
from wtforms import TextAreaField, StringField
from wtforms.validators import DataRequired, Length, Email


class ContactForm(FlaskForm):
    email = StringField(""What's your e-mail address?"",
                        [Email(), DataRequired(), Length(3, 254)])
    message = TextAreaField(""What's your question or issue?"",
                            [DataRequired(), Length(1, 8192)])
</code></pre>

<p><strong>contact/views.py:</strong></p>

<pre><code>from flask import (
    Blueprint,
    flash,
    redirect,
    request,
    url_for,
    render_template)

from flexio.blueprints.contact.forms import ContactForm

contact = Blueprint('contact', __name__, template_folder='templates')


@contact.route('/contact', methods=['GET', 'POST'])
def index():
    form = ContactForm()

    if form.validate_on_submit():
        # This prevents circular imports.
        from flexio.blueprints.contact.tasks import deliver_contact_email

        deliver_contact_email(request.form.get('email'),
                                    request.form.get('message'))

        flash('Thanks, expect a response shortly.', 'success')
        return redirect(url_for('contact.index'))

    return render_template('contact/index.html', form=form)
</code></pre>

<p><strong>contact/tasks.py:</strong></p>

<pre><code>from lib.flask_mailplus import send_template_message
from flexio.app import create_celery_app

celery = create_celery_app()


@celery.task()
def deliver_contact_email(email, message):
    """"""
    Send a contact e-mail.

    :param email: E-mail address of the visitor
    :type user_id: str
    :param message: E-mail message
    :type user_id: str
    :return: None
    """"""
    ctx = {'email': email, 'message': message}

    send_template_message(subject='[Flexio] Contact',
                          sender=email,
                          recipients=[celery.conf.get('MAIL_USERNAME')],
                          reply_to=email,
                          template='contact/mail/index', ctx=ctx)

    return None
</code></pre>

<p><strong>lib/tests.py:</strong></p>

<pre><code>def assert_status_with_message(status_code=200, response=None, message=None):
    """"""
    Check to see if a message is contained within a response.

    :param status_code: Status code that defaults to 200
    :type status_code: int
    :param response: Flask response
    :type response: str
    :param message: String to check for
    :type message: str
    :return: None
    """"""
    assert response.status_code == status_code
    assert message in str(response.data)
</code></pre>

<p><strong>tests/contact/test_views.py:</strong></p>

<pre><code>from flask import url_for
from lib.tests import assert_status_with_message
class TestContact(object):
    def test_contact_page(self, client):
        """""" Contact page should respond with a success 200. """"""
        response = client.get(url_for('contact.index'))
        assert response.status_code == 200
    def test_contact_form(self, client):
        """""" Contact form should redirect with a message. """"""
        form = {
          'email': 'foo@bar.com',
          'message': 'Test message from Flexio.'
        }
        response = client.post(url_for('contact.index'), data=form,
                               follow_redirects=True)
        assert_status_with_message(200, response, 'Thanks')
</code></pre>
",https://stackoverflow.com/questions/51810471/assertion-error-200-success-400-bad-request-while-unit-testing-a-dockerized,"['python', 'flask', 'pytest', 'http-status-code-400']",3434,TRUE,1,1
How to get the currentUser provided by spring security in Grails 2 unit testing,"<p>Hi guys i am on trouble about getting the current user provided by spring.</p>

<p>Here's my unit test code </p>

<pre><code>   void ""Test if adding project will sucess""() {

    given:
        def createProjectMock = mockFor(UserService)

        createProjectMock.demand.createNewProject { Map projectMap -&gt;
            return true
        }

        controller.userService = createProjectMock.createMock()

    when: ""saveProject is execute""

        controller.saveProject()

    then: ""page will to the list to view the saved project""
        response.redirectedUrl == '/user/index2'
}
</code></pre>

<p>Here's my controller</p>

<pre><code>def saveProject(ProjectActionCommand projectCmd) {

  def currentUser = springSecurityService.currentUser
  if (projectCmd.hasErrors()) {

    render view: 'createProject', model: [projectInstance: projectCmd, user:currentUser]
  } else {

    def getProjectMap = [:]

    getProjectMap = [
      projectName: params.projectName,
      user: currentUser
    ]

    def saveProject = userService.createNewProject(getProjectMap)

    if (saveProject) {   

      redirect view: 'index2'         
    } else {
      render 'Error upon saving'
    }
  }
}
</code></pre>

<p>And here's my service</p>

<pre><code>  Project createNewProject(Map projectMap){
    def createProject = new Project()

    createProject.with {
      projectName = projectMap.projectName
      user = projectMap.user
    }

    createProject.save(failOnError:true, flush: true)
  }
</code></pre>

<p>And i always getting this error:</p>

<p>Cannot get property 'currentUser' on null object.</p>

<p>Hope you can help me. Thanks </p>
",https://stackoverflow.com/questions/51415310/how-to-get-the-currentuser-provided-by-spring-security-in-grails-2-unit-testing,"['unit-testing', 'grails', 'spring-security', 'mocking']",135,TRUE,1,1
Xcode Unit Testing - Add a common function to be used across all test classes,"<p>I've implemented unit testing for my project using Swift. In the test cases, I'm reading input values are results from a CSV file and validates them. Currently all the functions to read the CSV file and parse it needs to be copied and pasted to the new test class whenever I create a new test case class. Is there some way to use the functions to read the CSV file at one place so that all test classes can use them? The code I would like to reuse is :</p>

<pre><code>func csv(data: String) -&gt; [[String]] {
    var result: [[String]] = []
    let rows = data.components(separatedBy: ""\n"")
    for row in rows {
        let columns = row.components(separatedBy: "","")
        result.append(columns)
    }
    return result
}

func cleanRows(file:String)-&gt;String{
    var cleanFile = file
    cleanFile = cleanFile.replacingOccurrences(of: ""\r"", with: ""\n"")
    cleanFile = cleanFile.replacingOccurrences(of: ""\n\n"", with: ""\n"")
    return cleanFile
}

func readDataFromCSV(fileName:String, fileType: String)-&gt; String!{
    let bundle = Bundle(for: type(of: self))
    let path = bundle.path(forResource: fileName, ofType: fileType)!

    do {
        let contents = try String(contentsOfFile: path, encoding: .utf8)
        return contents
    } catch {
        print(""File Read Error for file \(path)"")
        return nil
    }
}
</code></pre>
",https://stackoverflow.com/questions/51822718/xcode-unit-testing-add-a-common-function-to-be-used-across-all-test-classes,"['ios', 'swift', 'xcode', 'unit-testing', 'xctest']",1365,TRUE,1,1
Dot Net Core Unit Testing using Xunit -&gt; How to write initialization function for class,"<p>I've started work on Unit Testing in Dot Net Core 2.0.
I've written a class to Unit Test controller class of my Web API.</p>

<p>Please find below the code of my Unit Test Class</p>

<pre><code>public class ArticlesControllerTests
{
    private ArticlesController _articlesController;

    private Mock&lt;IArticleRepository&gt; _articleRepositoryMock = new Mock&lt;IArticleRepository&gt;();

    public ArticlesControllerTests()
    {
        _articlesController = new ArticlesController(_articleRepositoryMock.Object);
    }

    [ClassInitialize]
    public static void Init()
    {
        AutoMapperInit.Initialize();
    }
}
</code></pre>

<p>I want to write Init function that will call once and initialize AutoMapper configurations. But <code>[ClassInitialize]</code> is not there. I've searched online  but I was not able to find that attribute.</p>

<p>What should I do to make it work for Dot Net Core 2.0.</p>
",https://stackoverflow.com/questions/49731057/dot-net-core-unit-testing-using-xunit-how-to-write-initialization-function-fo,"['c#', 'unit-testing', '.net-core', 'xunit']",930,TRUE,1,1
Difficulty simulating events for unit testing in Jest/Enzyme/ReactTS with third party controls,"<p>I am using BlueprintJS controls in my React controls, and one of them is a Blueprint Select control. What I need to be able to do is simulate changing the value in the dropdown, just like I would be able to with a standard html select, however because this is a separate 3rd party control, I do not know how to simulate this event.</p>

<p>I've pasted the output template for the blueprint control below, but if I try and simulate itemselected or changed, it says cannot simulate these events.</p>

<p>Any idea how I can simulate this using Enzyme/Jest?</p>

<pre><code>&lt;Blueprint2.Select
          disabled={false}
          filterable={false}
          itemRenderer={[Function]}
          items={
            Array [
              ""JK"",
              ""User1"",
              ""User2"",
            ]
          }
          onItemSelect={[MockFunction]}
        &gt;
          &lt;Blueprint2.QueryList
            disabled={false}
            itemRenderer={[Function]}
            items={
              Array [
                ""JK"",
                ""User1"",
                ""User2"",
              ]
            }
            onActiveItemChange={[Function]}
            onItemSelect={[Function]}
            query=""""
            renderer={[Function]}
          &gt;
            &lt;Blueprint2.Popover
              autoFocus={false}
              className=""""
              defaultIsOpen={false}
              disabled={false}
              enforceFocus={false}
              hasBackdrop={false}
              hoverCloseDelay={300}
              hoverOpenDelay={150}
              inheritDarkTheme={true}
              interactionKind=""click""
              isOpen={false}
              minimal={false}
              modifiers={Object {}}
              onInteraction={[Function]}
              openOnTargetFocus={true}
              popoverClassName=""pt-select-popover""
              popoverDidOpen={[Function]}
              popoverWillClose={[Function]}
              popoverWillOpen={[Function]}
              position=""bottom-left""
              rootElementTag=""span""
              targetElementTag=""div""
              transitionDuration={300}
              usePortal={true}
            &gt;
              &lt;Manager
                className=""pt-popover-wrapper""
                tag=""span""
              &gt;
                &lt;span
                  className=""pt-popover-wrapper""
                &gt;
                  &lt;Target
                    className=""pt-popover-target""
                    component=""div""
                    innerRef={[Function]}
                    onClick={[Function]}
                  &gt;
                    &lt;div
                      className=""pt-popover-target""
                      onClick={[Function]}
                    &gt;
                      &lt;div
                        className=""""
                        key="".0""
                        onKeyDown={[Function]}
                      &gt;
                        JK
                      &lt;/div&gt;
                    &lt;/div&gt;
                  &lt;/Target&gt;
                  &lt;Blueprint2.Overlay
                    autoFocus={false}
                    backdropClassName=""pt-popover-backdrop""
                    backdropProps={Object {}}
                    canEscapeKeyClose={true}
                    canOutsideClickClose={true}
                    didOpen={[Function]}
                    enforceFocus={false}
                    hasBackdrop={false}
                    isOpen={false}
                    lazy={true}
                    onClose={[Function]}
                    transitionDuration={300}
                    transitionName=""pt-popover""
                    usePortal={true}
                  /&gt;
                &lt;/span&gt;
              &lt;/Manager&gt;
            &lt;/Blueprint2.Popover&gt;
          &lt;/Blueprint2.QueryList&gt;
        &lt;/Blueprint2.Select&gt;
</code></pre>
",https://stackoverflow.com/questions/51196535/difficulty-simulating-events-for-unit-testing-in-jest-enzyme-reactts-with-third,"['reactjs', 'typescript', 'jestjs', 'enzyme']",541,TRUE,1,1
Angular 6 Unit testing: I want to stub a declared property for my test,"<p>I'm using angular version 6 and jasmine.</p>

<p>When I run ng test --sourceMap=false</p>

<p><strong>Error I get is: videojs is not defined</strong></p>

<p>I would like to stub videojs if possible.
Also, note that the component runs fine, its just the unit test that fails.</p>

<p>Videojs is an npm library I use for showing videos etc.</p>

<p><strong>My component that I'm testing:</strong></p>

<pre><code>import { AfterViewInit, Component } from '@angular/core';

declare const videojs: any;

@Component({
  selector: 'test-details',
  templateUrl: './test-details.component.html'
})
export class TestDetailsComponent implements AfterViewInit {
  public videoJSplayer: any;

  constructor() {}

  ngAfterViewInit(): void {
    this.initVideo();
  }

  public initVideo(): void {
    this.videoJSplayer = videojs(
      document.getElementById('video_player_id'),
      { controls: true, autoplay: false, preload: 'auto' }
    );
  }
}
</code></pre>

<p><strong>My Unit test</strong></p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { TestDetailsComponent } from './test-details.component';

declare const videojs: any;

fdescribe('TestDetailsComponent', () =&gt; {
  let component: TestDetailsComponent;
  let fixture: ComponentFixture&lt;TestDetailsComponent&gt;;

  beforeEach(
    async(() =&gt; {
      TestBed.configureTestingModule({
        imports: [],
        declarations: [ TestDetailsComponent ],
        schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
        providers: [
           { provide: videojs, useValue: {} }
        ]
      }).compileComponents();
    })
  );

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(TestDetailsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () =&gt; {
    expect(true).toBeTruthy(true);
  });
});
</code></pre>
",https://stackoverflow.com/questions/50626719/angular-6-unit-testing-i-want-to-stub-a-declared-property-for-my-test,"['angular', 'unit-testing', 'testing', 'jasmine']",1160,TRUE,1,2
Why I&#39;m getting NullReferenceException while trying to refer to Moq Object in unit testing?,"<p>I have two classes:</p>

<ul>
<li><code>ProductController</code> class with <code>SingleProduct</code> action</li>
<li><code>Helper</code> class with its own method <code>getProduct(ProductsContext db, string id)</code> which retrieves specified product from database</li>
</ul>

<p>I'm trying to create unit test for <code>SingleProduct</code> action using Moq framework. 
I'm creating mock for <code>Helper</code> object, but when test runs I receive <code>NullReferenceException</code> for mocked <code>Helper</code> object.</p>

<p>What am I doing wrong?</p>

<pre><code>[TestMethod]
public void ProductNotFoundTest()
{
    var mockHelper = new Mock&lt;Helper&gt;();
    mockHelper.Setup(h =&gt; h.getProduct(It.IsAny&lt;ProductsContext&gt;(), It.IsAny&lt;string&gt;())).Returns(It.IsAny&lt;Product&gt;());

    ProductController controller = new ProductController(mockHelper.Object);

    ViewResult result = controller.SingleProduct(""i'm not exist"") as ViewResult;
    Assert.AreEqual(""~/Views/Product/ProductNotFound.cshtml"", result.ViewName);
}
</code></pre>

<hr>

<pre><code>namespace OnlineStoreParser.Controllers
{
    public class ProductController : Controller
    {
        private Helper _h;        

        public ProductController(Helper h)
        {
            Helper _h = h;
        }

        public ProductController()
        {
            _h = new Helper();
        }

        public ActionResult SingleProduct(string id)
        {            
            Product product;

            using (var context = new ProductsContext())
            {
                // Find product with specified ID
                product = _h.getProduct(context, id);

                if(product != null)
                {
                    ViewBag.History = product.History;
                    ViewBag.Images = product.Photos;
                    return View(product);
                }                
                else
                {
                    return View(""~/Views/Product/ProductNotFound.cshtml"");
                }
            }
       }
   }   
}  
</code></pre>

<hr>

<pre><code>namespace OnlineStoreParser.Models
{
    public class Helper
    {
        public Helper() { }

        public virtual Product getProduct(ProductsContext db, string id)
        {
            return db.Products.SingleOrDefault(p =&gt; p.ProductId == id);
        }
    }
}  
</code></pre>
",https://stackoverflow.com/questions/52422177/why-im-getting-nullreferenceexception-while-trying-to-refer-to-moq-object-in-un,"['c#', 'asp.net-mvc', 'unit-testing', 'moq']",63,TRUE,-1,1
Getting &quot;Class extends value undefined&quot; when importing Electron app for unit testing using Mocha,"<p>I am currently working on an electron based app and I have a class that extends electron's BrowserWindow in an ""imports.js"" file that look like this:</p>

<pre><code>const
  electron = require('electron')
  app = electron.app
  BrowserWindow = electron.BrowserWindow
  BrowserView = electron.BrowserView

module.exports.impor = class impor extends BrowserWindow {
     constructor (){
         super()
     }
    // some stuff here
}
</code></pre>

<p>I want to test it using mocha so I have a test file that look like this:</p>

<pre><code>const impor = require('./imports').impor
// tests go there
</code></pre>

<p>But when i run the test using mocha ( cmd: ""mocha test.js"") I get this error:</p>

<pre><code>module.exports.impor = class impor extends BrowserWindow {
                                       ^

TypeError: Class extends value undefined is not a constructor or null
    at Object.&lt;anonymous&gt; (/media/athoir/Storage/OrganiKnowledge/test/imports.js:2:44)
    at Module._compile (module.js:660:30)
    at Object.Module._extensions..js (module.js:671:10)
    at Module.load (module.js:573:32)
    at tryModuleLoad (module.js:513:12)
    at Function.Module._load (module.js:505:3)
    at Module.require (module.js:604:17)
    at require (internal/module.js:11:18)
    at Object.&lt;anonymous&gt; (/media/athoir/Storage/OrganiKnowledge/test/test_import.js:7:15)
    at Module._compile (module.js:660:30)
    at Object.Module._extensions..js (module.js:671:10)
    at Module.load (module.js:573:32)
    at tryModuleLoad (module.js:513:12)
    at Function.Module._load (module.js:505:3)
    at Module.require (module.js:604:17)
    at require (internal/module.js:11:18)
    at /usr/lib/node_modules/mocha/lib/mocha.js:231:27
    at Array.forEach (&lt;anonymous&gt;)
    at Mocha.loadFiles (/usr/lib/node_modules/mocha/lib/mocha.js:228:14)
    at Mocha.run (/usr/lib/node_modules/mocha/lib/mocha.js:536:10)
    at Object.&lt;anonymous&gt; (/usr/lib/node_modules/mocha/bin/_mocha:573:18)
    at Module._compile (module.js:660:30)
    at Object.Module._extensions..js (module.js:671:10)
    at Module.load (module.js:573:32)
    at tryModuleLoad (module.js:513:12)
    at Function.Module._load (module.js:505:3)
    at Function.Module.runMain (module.js:701:10)
    at startup (bootstrap_node.js:193:16)
    at bootstrap_node.js:617:3
</code></pre>

<p>I already tried importing electron in the test before my class but it didn't change anything and I don't see how I could have a circular import in this situation.
Also when i try to import it in my main.js file it work just fine.</p>

<p>I may be overlooking something obvious but I am lost here.</p>
",https://stackoverflow.com/questions/48465796/getting-class-extends-value-undefined-when-importing-electron-app-for-unit-tes,"['javascript', 'mocha.js', 'electron', 'extends']",443,TRUE,0,1
"Unit testing jQuery getJSON function errors with the fail method, using Jasmine and Karma","<p>I've written a unit test for a function that calls the jQuery <code>getJSON</code> method. The only thing that I'm testing is that it is called with the expected URL. My unit test uses a Jasmine Spy to mock the API call. However, when I run my unit tests I get this error:</p>

<pre><code>1) should make a request to the expected URL when running on localhost
     test module getDataFromApi function
     TypeError: Cannot read property 'fail' of undefined
</code></pre>

<p>In my unit test I've created a Jasmine Spy, which returns the <code>done</code> and <code>fail</code> methods. What am I doing wrong here?</p>

<p><strong>Here is my unit test:</strong></p>

<pre><code>describe('getFundDataFromApi function', function () {
    beforeEach(function () {
        spyOn($, ""getJSON"").and.callFake(function () {
            return {
                done: function () {},
                fail: function () {}
            };
        });
    });
    it('should make a request to the expected URL when running on localhost', function () {
        var expectedUrl = '/assets/mock-data/mock-data.json';
        module.getDataFromApi();
        expect($.getJSON).toHaveBeenCalled();
        expect($.getJSON).toHaveBeenCalledWith({url:expectedUrl});
    });
});
</code></pre>

<p><strong>Function I'm trying to test: getDataFromApi</strong></p>

<pre><code>getDataFromApi: function () {
    var mod = this;
    var url = this.settings.apiUrl;

    $.getJSON({
        url: url
    })
    .done(function (data) {
        mod.processApiData(data);
    })
    .fail(function () {
        mod.displayErrorMessage();
    });
},
</code></pre>
",https://stackoverflow.com/questions/53392072/unit-testing-jquery-getjson-function-errors-with-the-fail-method-using-jasmine,"['javascript', 'unit-testing', 'jasmine', 'karma-jasmine']",878,TRUE,0,1
Unit Testing Libgdx classes that call a ShaderProgram (such as a Stage) via a HeadlessApplication,"<p>I am trying to unit test the <code>core</code> package of my libgdx application. </p>

<p><strong>What is the best way to mock the <code>ShaderProgram</code> such that the root class may be tested?</strong>  </p>

<p>Given the following init for a Libgdx test runner,</p>

<pre><code>init {
    val conf = HeadlessApplicationConfiguration()

    HeadlessApplication(this, conf)
    Gdx.gl = mock(GL20::class.java) 
    Gdx.gl20 = mock(GL20::class.java)
    Gdx.gl30 = mock(GL30::class.java)
    Gdx.graphics = mock(Graphics::class.java)
    `when`(Gdx.graphics.height).thenReturn(dimensions)
    `when`(Gdx.graphics.width).thenReturn(dimensions)
}
</code></pre>

<p>and the function under test (which is in a class that is a child of <code>Application Listener</code>),</p>

<pre><code>override fun create() {
    ...
    stage = Stage(ScreenViewport())
    ...
}
</code></pre>

<p>an error occurs inside of Stage when it attempts to compile a shader.</p>

<p>I.e., in <code>SpriteBatch.java</code> from <code>com.badlogic.gdx.graphics.g2d</code>,</p>

<pre><code>ShaderProgram shader = new ShaderProgram(vertexShader, fragmentShader);
if (shader.isCompiled() == false) throw new IllegalArgumentException(""Error compiling shader: "" + shader.getLog());
</code></pre>

<p><code>shader.isCompiled()</code> appears to always return false for a <code>HeadlessApplication</code>.</p>
",https://stackoverflow.com/questions/51728471/unit-testing-libgdx-classes-that-call-a-shaderprogram-such-as-a-stage-via-a-he,"['unit-testing', 'kotlin', 'libgdx']",301,TRUE,5,1
"Simple example of a complex situation in Unit Testing, how should this be designed?","<p>I've simplified the code in the example to keep the question shorter, but basically I am struggling with designing more testable code and isolating them from each other. </p>

<p>With just two methods here listed below I've outlined exactly what tests I need to do. </p>

<ol>
<li>Verify that the correct URL was utilized</li>
<li>Verify the appropriate headers were used, such as the request was in JSON.</li>
<li>Verify a POST request was used  (I have a HttpMessageHandler and using delegates to intercept and mock out the internet as a dependency in the actual code)</li>
<li>Verify that the serialized JSON value doesn't have any extra properties not filled out.</li>
</ol>

<p>The code example is below:</p>

<pre class=""lang-cs prettyprint-override""><code>class RESTAPI
{
    private IHttpService _webService;

    public void ChangeAssignedAgent(ITicket ticket, string agentName)
    {
        string agentID = GetAgentIDFromName(agentName);
        _webService.PostRequest($""https://localhost/{agentID}"", new StringContent(JsonConvert.SerializeObject(ticket), Encoding.UTF8,""application/json""));
    }

    private string GetAgentIDFromName(string agentName)
    {
        return JsonConvert.DeserializeObject&lt;JObject&gt;(_webService.GetStringContent($""https://localhost/{agentName}""))[""sys_id""].Value&lt;string&gt;();
    }
}
</code></pre>

<p>In theory, these tests should be completely isolated from each other.
But they're not because in each test, I must setup and configure GetAgentFromName() even when it is not relevant.</p>

<p>Here are my ideas in fixing this problem, but I am not sure what the best resolution would be to make something more SRP oriented and testable.</p>

<ol>
<li><p>Utilize a decorator or adapter to simply convert the agentName to an agentID, then pass this information to the base class to post the request. </p></li>
<li><p>Change the private method to protected internal, have a mocking framework replace the implementation of the GetAgentIDFromName() method, and simply call the base implementation for any method that's not been mocked.</p></li>
<li><p>Change the method signature of the ChangeAssignedAgent() method to instead refer to getting an agentID instead of a name, make the GetAgentIDFromName() public and expect the consumers of your class to utilize it in order to use the ChangeAssignedAgent() method.</p></li>
</ol>

<p>It's possible that the first option is the best way to tackle this scenario, but something tells me it may not be the right solution because technically the base class is misleading... it wants an agentName... not an ID.</p>

<p>The second option seems more of a hack and code smell to me, it is effectively testing a private method... I am not sure... open for suggestions.</p>

<p>Lastly, the last option... it's similar to the second option in terms how I feel it may be a hack/code smell but it makes most logical sense to me. However, with this design it feels like you can never have private methods and it may also increase complexity of your class.</p>

<p>Am I overthinking this? I would love to hear some suggestions...</p>
",https://stackoverflow.com/questions/53509616/simple-example-of-a-complex-situation-in-unit-testing-how-should-this-be-design,"['c#', '.net', 'unit-testing', 'oop', 'single-responsibility-principle']",616,TRUE,0,2
How do I replace frequently used new keyword with Spring calls 4 Unit testing?,"<p>Clarification:</p>

<p>The legacy code wasn't Sprung completely ( see what I did there ) and also test coverage is low. We are working to improve it now but we see uses of the new keyword everywhere and this is going to ruin our unit isolation. I'd rather not wire in a ref to the Spring Context as that ties us pretty closely to Spring and I can't use PowerMock due to an Architects directive. What we've been doing is putting all calls to <strong><em>new</em></strong> in protected methods so we can override but shouldn't Spring be doing that and how do we get Spring to do it?  I can easily imagine creating an appropriately annotated method in a @Configuration annotated class with scope set to... hmmm.. nothing at all? That should mean that the class generates a new one on every call. Question is, how do I use that in my subject under test? </p>
",https://stackoverflow.com/questions/51158817/how-do-i-replace-frequently-used-new-keyword-with-spring-calls-4-unit-testing,"['java', 'spring']",39,FALSE,0,0
Unit testing a PHP class that accepts string arguments to create a PDO object,"<p>I have a class (<code>PDOMySQLForeignKeysToURLsService</code>) that does exactly what it says on the tin, it takes a JSON encoded database entity, compares it to a configuration file and transforms any foreign key fields into URLs linking to other RESTful resources. i.e.</p>

<pre><code>[
  {
    ""ID"": ""1"",
    ""person_id"": ""1"",
    ""pc_name"": ""my_computer""
  }
]
</code></pre>

<p>assuming <code>person_id</code> is a foreign key in the database, will become something like</p>

<pre><code>[
  {
    ""ID"": ""1"",
    ""person_id"": ""http://localhost/api/db/person/1"",
    ""pc_name"": ""my_computer""
  }
]
</code></pre>

<p>because this service itself is initalized from a configuration file it can only accept text in it's constructor,</p>

<p><code>public function __construct(string $pdoDSN, string $username, string $password, string $tablename, string $schemaname)</code></p>

<p>everything seems to running fine and dandy, but now I want to write some unit tests for this class, and part of it requires that a <code>PDO</code> object is instantiated and the <code>INFORMATION_SCHEMA</code> table queried like below</p>

<pre><code>  SELECT 
    *
  FROM
    INFORMATION_SCHEMA.KEY_COLUMN_USAGE
  WHERE
    TABLE_SCHEMA = ? AND
    CONSTRAINT_NAME != ""PRIMARY"" AND
    REFERENCED_TABLE_NAME IS NOT NULL AND
    REFERENCED_COLUMN_NAME IS NOT NULL
</code></pre>

<p>The method in which this occurs is in an implementation of an interface <code>Resolvable</code>, defining <code>function resolveRequest(ServiceRequest $request, ServiceResponse $response)</code></p>

<p>I basically have no idea how to go around testing all of this besides setting up a schema/some tables in the tests set up? I have heard from my peers that this is bad practice and does not constitute unit testing but rather integration testing - so my question is how could I go about unit testing this method, is unit testing even appropriate here? The class is by definition very dependant on MySQL (and PDO). Should I write some kind of adapter around PDO and use a DI framework to inject it, and interface with that rather than PDO directly? I'm pretty lost at what to do, tbh, and don't understand the idea/how to mock dependencies that are only used within the scope of a method</p>
",https://stackoverflow.com/questions/51207499/unit-testing-a-php-class-that-accepts-string-arguments-to-create-a-pdo-object,"['php', 'mysql', 'unit-testing', 'pdo', 'phpunit']",59,TRUE,0,1
Unit testing view model that uses SelectMany to call an async method in ReactiveUI,"<p>I am new to ReactiveUI and trying to test a view model that looks like this:</p>

<pre><code>public interface IService
{
    Task&lt;SessionModel&gt; GetData(string id);
}

/// Provides a group of schedulers available to be used
public interface ISchedulers
{
    IScheduler Default { get; }
    IScheduler Dispatcher { get; }
}

public class MyVm : ReactiveObject
{
    IService service;

    public MyVm(ISchedulers schedulers, IService service)
    {
        this.service = service;
        this.session = this.WhenAnyValue(x =&gt; x.SessionId)
                           .SelectMany(SearchSession)
                           .ObserveOn(schedulers.Default)
                           .ToProperty(this, x =&gt; x.Session);
    }

    private async Task&lt;SessionModel&gt; SearchSession(string id)
    {
        return await this.service.GetData(id);
    }

    private string sessionId;
    public string SessionId
    {
        get =&gt; sessionId;
        set =&gt; this.RaiseAndSetIfChanged(ref sessionId, value);
    }


    readonly ObservableAsPropertyHelper&lt;SessionModel&gt; session;
    public SessionModel Session
    {
        get { return session.Value; }
    }

}

public class SessionModel { }
</code></pre>

<p>I'm mocking the service call to return dummy data, but not sure what I need to do with a <code>TestScheduler</code> in order to get the <code>SelectMany</code> to work.</p>

<p>Here's a test class that shows how i would create a test for the view model.  The goal is to eventually be able to check that the model got set:</p>

<pre><code>[TestClass]
public class MyVmTests
{
    [TestMethod]
    public void CreateClass
    {
       var subject = new MyVm(/*pass in mocks*/);

       subject.SessionId=""test"";

       Assert.IsNotNull(subject.Session);
     }
}
</code></pre>
",https://stackoverflow.com/questions/52950510/unit-testing-view-model-that-uses-selectmany-to-call-an-async-method-in-reactive,"['unit-testing', 'tdd', 'system.reactive', 'reactiveui']",182,TRUE,0,1
How to count # of events sent to event hub via Moq for Unit Testing,"<p>I am writing <strong>Unit Test</strong> using <strong>MOCK (Moq)</strong> for my <strong>Azure Event Hub</strong>. The Unit Test is simple. When I send 1 message to my Event Hub, I need to make sure it does receive 1 message. This is what I am doing... </p>

<pre><code>Mock&lt;IEventHub&gt; eventHubMock;

eventHubMock
    .Setup( client =&gt; client.SendBatchAsync( It.IsAny&lt;IEnumerable&lt;EventData&gt;&gt;() ) )
    .Returns( Task.CompletedTask );

// Some processing which sends 1 message to Event Hub.

// Now to verify that my mock did receive 1 message.

eventHubMock.Verify(
    client =&gt; client.SendBatchAsync(
    It.IsAny&lt;IEnumerable&lt;EventData&gt;&gt;() ) );
</code></pre>

<p><strong>QUESTIONS</strong></p>

<ol>
<li>The above will just validate it received some EventData. How do I verify that it received 1 EventData ?</li>
<li>What other validation can I perform using Mock?</li>
<li>My code deals with 2 event Hubs. How do I make sure the message is sent to correct event hub ?</li>
</ol>
",https://stackoverflow.com/questions/48960341/how-to-count-of-events-sent-to-event-hub-via-moq-for-unit-testing,"['c#', 'unit-testing', 'mocking', 'moq', 'azure-eventhub']",1050,TRUE,0,1
How to use Mockery for unit testing in PHP 7.2 and mocking Eloquent queries,"<p>I want to create a set of unit tests for an existing production system, that will be executed locally, triggered by a pre-commit hook.</p>

<p>As a requirement the tests have to run 3-4 secs max.</p>

<p>By definition, the unit tests should call methods in isolation. However, the system is heavily DB dependent so I want to be able to mock the database calls.</p>

<p>The application is running PHP 7.2, Laravel 5.5.4.</p>

<p>I have been trying to use Mockery with no success. Here is a simple example of what I had been trying to do:</p>

<pre><code>public function testExample()
{
    // Create a new user
    $newUser = new User();
    $newUser-&gt;id = 1;

    // Mock the User
    $mockedUser = Mockery::mock(User::class);
    // Mock the Builder
    $mockedBuilder = Mockery::mock(Builder::class);
    $this-&gt;app-&gt;instance(Builder::class, $mockedBuilder);
    $this-&gt;app-&gt;instance(User::class, $mockedUser);
    // Set the expectations
    $mockedBuilder-&gt;shouldReceive('first')-&gt;once()-&gt;andReturn($newUser);
    $mockedUser-&gt;shouldReceive('where')
        -&gt;with('id', 5)
        -&gt;once()
        -&gt;andReturn($mockedBuilder);

    $this-&gt;assertEquals($newUser-&gt;id, User::where('id', 5)-&gt;first()-&gt;id);
}
</code></pre>

<p>However, since ""where"" is actually a static call to Builder, it doesn't work.
Is there any way to achieve it? I though of mocking the DB facade (or PDO) but it seems too .. rough. Any better ideas?</p>
",https://stackoverflow.com/questions/50842223/how-to-use-mockery-for-unit-testing-in-php-7-2-and-mocking-eloquent-queries,"['php', 'unit-testing', 'laravel-5.5', 'mockery']",481,FALSE,0,0
How to mock a calendar object to get a specific time in unit testing,"<p>I am new to the concept of writing unit tests so I'm not sure how to go on about this. I have the following method in my class which is a class full of helper functions which gets used around my app:</p>

<pre><code>public static float getCurrentTime() {
    Calendar calandar = Calendar.getInstance();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(""HH:mm"");
    String[] time = simpleDateFormat.format(calandar.getTime()).split("":"");
    float returnResult = /*perform some calculations*/
    return returnResult ;
}
</code></pre>

<p>Now in this method, the result depends on what time it is. In my unit test, I want to control that aspect to ensure to gives me the right time but I'm not sure how to do that. I looked up powermockito and using the <code>when(..).then(..)</code> method, also looked into mocking the calender object but because its instantiated in the method, it doesn't look like that'll work. Any ideas? I have no constructors in this class as all the methods in this class is static so I simply call the methods by class name rather than instantiating an object of this class.</p>
",https://stackoverflow.com/questions/48596125/how-to-mock-a-calendar-object-to-get-a-specific-time-in-unit-testing,"['java', 'android', 'unit-testing', 'mocking']",1232,TRUE,0,1
nock: can we have two scopes for two different hosts in nock unit testing?,"<p>I'm using nock with  I'd like to know if I can mock api calls from two different hosts defined with their scopes like :</p>

<pre><code>const scopeOne = nock('https://myurl1.com/users', allowUnmocked)
.persist();
const scopeTwo = nock('https://myurl2.com/orders', allowUnmocked)
</code></pre>

<p>API CALLS :</p>

<pre><code>scopeOne.post('/users')
.reply(200, (uri, params) =&gt;
({
  users: {
    mtu: 1450
  }
}));

scopeTwo.post('/orders')
.reply(200, (uri, params) =&gt;
({
  orders: {
    mtu: 1420
  }
}));
</code></pre>

<p>I was able to mock only one url which scopeOne which i defined earlier than scopeTwo. And I also tried seperating scopes in two different files which did not work. Can some one guide me where I was going wrong .</p>
",https://stackoverflow.com/questions/52940482/nock-can-we-have-two-scopes-for-two-different-hosts-in-nock-unit-testing,"['javascript', 'node.js', 'unit-testing', 'nock']",854,FALSE,0,0
Microsoft Unit Testing-Mark test as a utility method to only run on demand,"<p>Seems like every project I have a set of tasks I need to run like generating XML files according to an object definition, stuff I do occasionally and only on demand.  I've found that just putting that into a [TestMethod] is a very easy way to have those things in one place.</p>

<p>Is there a way to mark those methods as on demand, not run during normal unit testing?  I tried the [Ignore] attribute but that prevents them from running entirely.  These methods have side effects and aren't really tests.  I invoke them individually as needed.</p>

<p>Note that I'm <strong>NOT</strong> asking about static utility methods.  These are implemented inside the unit test method.</p>

<p>This is for Microsoft's Unit Testing framework, .Net.  Do other unit testing frameworks have this?</p>
",https://stackoverflow.com/questions/52117988/microsoft-unit-testing-mark-test-as-a-utility-method-to-only-run-on-demand,"['.net', 'unit-testing']",120,TRUE,0,1
Is it a good practice loading local json file for unit testing js web request?,"<p>I plan to write multiple simulated web request response and store locally as  json. Is it a good practice? I don't use spy like the following because my json file is too long and is not convenient to fit into code</p>

<pre><code>it('should send post params in request body', function() {
    var params = { foo: 'bar' };
    var expected = JSON.stringify(params);

    var request = new PassThrough();
    var write = sinon.spy(request, 'write');

    this.request.returns(request);

    api.post(params, function() { });

    assert(write.withArgs(expected).calledOnce);
});
</code></pre>
",https://stackoverflow.com/questions/51738190/is-it-a-good-practice-loading-local-json-file-for-unit-testing-js-web-request,"['javascript', 'unit-testing']",875,TRUE,4,1
how to do stop jasmine unit testing if any one of the test is failed,"<p>I wrote above 500 unit test methods. when i give <code>ng test</code> command. it starting to test all the 500 methods. </p>

<p>If any test cases failed, it wont stop and still it continue to execute all methods. So i need wait more time to rerun the unit test again. </p>

<p>I know we can exist  by  doing <code>ctr+c</code>  and again rerun the unit test by using <code>ng test</code> command. This way also taking too much time. </p>

<p>So is it possible to stop (not exist)  the unit test, if any one of the test is failed?  </p>
",https://stackoverflow.com/questions/48700673/how-to-do-stop-jasmine-unit-testing-if-any-one-of-the-test-is-failed,"['angular', 'unit-testing', 'typescript', 'jasmine', 'command']",2230,TRUE,3,2
How do I test the Elements value in React Native unit testing using Enzyme (Jest),"<p>I have the following Flash.js component to Test</p>

<pre><code>export default class SnapshotChild extends Component {

render() {
    return (
        &lt;View&gt;
            &lt;Text&gt;First Text&lt;/Text&gt;
            &lt;Text&gt;Second Text&lt;/Text&gt;
        &lt;/View&gt;
    );
}}
</code></pre>

<p>And My test cases is</p>

<pre><code>describe('Flash Card', () =&gt; {
      const flash = shallow(&lt;Flash /&gt;);

      it('test the `&lt;Text/&gt;` value',()=&gt;{
       console.log(flash.debug());
       expect(flash.find('Component Text').at(0).text()).toEqual('First Text');
      })});
</code></pre>

<p>Now when I run this code using <strong>npm test</strong> the result is showing </p>

<pre><code>Expected value to equal:
  ""First Text""
Received:
  ""&lt;Text /&gt;""
</code></pre>

<p>My expected result is <strong>""First Text""</strong> and getting ""<strong>Text tag</strong>"".
What's the wrong, please please somebody help me on this. Thanks in advance.</p>
",https://stackoverflow.com/questions/53447022/how-do-i-test-the-elements-value-in-react-native-unit-testing-using-enzyme-jest,"['reactjs', 'react-native', 'jestjs', 'enzyme']",4624,TRUE,3,2
Unit testing a controller with DI DbContext and Model that uses LINQ -- EF Core 2,"<p><em>Before you start:</em></p>

<ol>
<li>We use PostgreSQL with Postgis extension (Can't use inMemoryDB option, because of Postgis' geometry that we are using)</li>
<li>We do not use the repository pattern </li>
<li>We use DbContext to access the DbModels and use Linq expressions on them</li>
<li>We use Database First principle</li>
</ol>

<p>This sort of question has been asked before in varying degrees<a href=""https://stackoverflow.com/questions/40476233/how-to-mock-an-async-repository-with-entity-framework-core"">Like here, where they talk about it, however we do NOT implement the repository pattern </a> but I feel it has not been answered in a concise way and so I ask it again.
References or general guide is welcomed, so thank you in advance.</p>

<p>This is what I have so far.
Controller:</p>

<pre><code>public class StartTripController : Controller
{
    private readonly DbContext _dbContext;

    public StartTripController(DbContext DbContext) =&gt; _DbContext = DbContext;

    [Route(""connect"")]
    [HttpGet]
    public async Task&lt;IActionResult&gt; StartTrip(MessageDto messageDto, StartTripDto startTripDto)
    {

        if (ModelState.ErrorCount &gt; 0)
            return StatusCode(400);

        var userToCheck = await _DbContext.User
                                            .Select(i =&gt; new UserDto { UserId = i.Id, PhoneId = i.PhoneId, AppInfoDto = new AppInfoDto { IsAppInDebug = false } })
                                            .SingleOrDefaultAsync(u =&gt; u.PhoneId == startTripDto.UserDto.PhoneId);   //checks if User is in DB, returns Null if not

        if (userToCheck == null) //user does not exist
        {
          //Make new User entity and save the changes to DB async

            UserDto newUserToReturn = new UserDto { UserId = user.Id, AppInfoDto = new AppInfoDto { IsAppInDebug = user.DebugMode } };

            return GenerateResponseWithStatus200(messageDto, newUserToReturn);
        }

        //user exists
        return GenerateResponseWithStatus200(messageDto, userToCheck);
    }
</code></pre>

<p>My Test looks like this:</p>

<pre><code> public class StartTripControllerTest : ControllerTest&lt;StartTripController&gt;
{
    private DbContext _mockDbContext;

    protected override StartTripController GetController()
    {

        var mockDbContext = new Mock&lt;DbContext&gt;();

        var userData = new List&lt;User&gt;
        {
            new User{PhoneId = ""Phone1"", Id = 1, ReportProviderId = 1, UserPhone = null, DebugMode = true, IpAddress = ""empty"", DeviceUser = null, Credential = null},
            new User{PhoneId = ""Phone2"", Id = 2, ReportProviderId = 2, UserPhone = null, DebugMode = true, IpAddress = ""empty"", DeviceUser = null, Credential = null}
        };

        var mockData = userData.AsQueryable().BuildMock(); //BuildMock is from https://github.com/romantitov/MockQueryable
        mockDbContext.Setup(x =&gt; ???what do I write here??).Returns(mockData.Object);

        return new StartTripController(mockDbContext.Object);
    }



    [Fact]
    public async System.Threading.Tasks.Task StartTrip_ReturnUser_JsonAsync()
    {
        // Arrange
        StartTripController startTripController = GetController();

        MessageDto messageDto = new MessageDto ();
        StartTripDto startTripDto = new StartTripDto();
         //code omitted for readiblity
        var result = await startTripController.StartTrip(messageDto, startTripDto);
    }
}
</code></pre>

<p>Things I figured out:</p>

<ol>
<li>You have to Mock Interfaces in order for async methods to work <a href=""https://msdn.microsoft.com/en-us/library/dn314429.aspx"" rel=""nofollow noreferrer"">As per Microsoft's post</a></li>
</ol>

<p>Things I am stuck on:</p>

<ol>
<li>How do I mock the DbContext or I guess the Model in this case, so that I can use LINQ expressions, like I do I my regular code?</li>
</ol>
",https://stackoverflow.com/questions/49507084/unit-testing-a-controller-with-di-dbcontext-and-model-that-uses-linq-ef-core,"['asp.net', 'unit-testing', 'moq', 'xunit']",1458,TRUE,2,1
USQL Unit testing with ADL tools for VS 2017 - Error after upgrading to 2.3.4000.x,"<p>One of the team member after upgrading the ADL tools for VS to version 2.3.4000.x, getting the  below error..</p>
<blockquote>
<p>Error : (-1,-1) 'E_CSC_SYSTEM_INTERNAL: Internal error!</p>
<p>The ObjectManager found an invalid number of fixups.</p>
<p>This usually indicates a problem in the Formatter.'
Compile failed!</p>
</blockquote>
<p>Tried to downgrade back to version ( 2.3.3000.2 ), it didn't help much.</p>
<p>If encountered similar issue, found the reason and resolved it, please share it.</p>
",https://stackoverflow.com/questions/51181503/usql-unit-testing-with-adl-tools-for-vs-2017-error-after-upgrading-to-2-3-4000,"['testing', 'azure-data-lake', 'u-sql']",263,TRUE,2,1
angular 6 unit testing - how can I inject a class with static property for testing,"<p>I have a class AppGlobal which get injected in the AppModule and then I am using this singleton class for creating dependencies instances.
but I am getting the following error :</p>

<blockquote>
  <p>TypeError: Cannot read property 'get' of undefined
      at new StopWatchComponent (webpack:///./src/app/UserSection/Components/StopWatchComponent.ts?:27:109)</p>
</blockquote>

<pre><code> @Injectable()
export class AppGlobal {
AppModule.injector.get(MyService)`
  public static injector: Injector;
  constructor(injector: Injector) {
    AppGlobal.injector = injector;
  }
 }
</code></pre>

<p><strong>component to be tested</strong></p>

<pre><code>export class StopWatchComponent  implements OnInit {
      public title: string;
         private stopWatchService: StopWatchService;
      constructor() {
         this.stopWatchService = AppGlobal.injector.get(StopWatchService);
         console.log('constructor');
}
</code></pre>

<p><strong>root module</strong></p>

<pre><code>export class AppModule {
      constructor(_appGlobal: AppGlobal) {
      }
}
</code></pre>

<p><strong>test cases</strong></p>

<pre><code>describe('StopWatchComponent', () =&gt; {
  let component: StopWatchComponent;
  let fixture: ComponentFixture&lt;StopWatchComponent&gt;;
  // let el: HTMLElement;

  beforeEach(async(() =&gt; {

    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule,
        FormsModule
      ],
      declarations: [ StopWatchComponent ],
      providers: [AppGlobal
        {provide: StopWatchService, useClass: StopWatchServiceMock}]
    }).compileComponents()
      .then(() =&gt; {
        console.log('configureTestingModule ok');

      }).catch((e) =&gt; {
      console.log(e.message);
      throw e;
    });

    fixture = TestBed.createComponent(StopWatchComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

  }));

  it('should have title User stopwatch', () =&gt; {
    expect(component.title).toEqual('User stopwatch');
  });
</code></pre>
",https://stackoverflow.com/questions/53473058/angular-6-unit-testing-how-can-i-inject-a-class-with-static-property-for-testi,"['angular', 'unit-testing']",368,FALSE,2,0
What&#39;s the difference between importing a target into unit testing and including that file among the target Membership?,"<p>When I'm writing tests I can do:</p>

<pre><code>@testable import TestProduct
</code></pre>

<p>How is the above different from adding the Test File to a specific Target?</p>

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

<p>Ultimately my question is: Had I made my unitTests a target to all my files...would it be equivalent to doing: </p>

<pre><code>@testable import TestProduct
</code></pre>

<p>If not, then what is the difference?</p>
",https://stackoverflow.com/questions/51070263/whats-the-difference-between-importing-a-target-into-unit-testing-and-including,"['swift', 'xcode', 'unit-testing']",4197,TRUE,16,3
"Unit testing fails when listing DLLs in particular order, but only in 32 bit compiles","<p>We have some unit tests in different DLLs.  These DLLs house our main code as well, so they do have some dependency between them, though I don't <em>think</em> that the tests should cross the DLL boundary.  However, we do a lot of /DELAYLOAD on the linker command line for a bunch of DLLs, but not directly between each other.</p>

<p>If we load the test using the command line: </p>

<pre><code>vstest.console.exe dll1.dll dll2.dll /platform:x86 /UseVsixExtensions:true /inIsolation
</code></pre>

<p>it works,  However, if we using the command line</p>

<pre><code>vstest.console.exe dll2.dll dll1.dll /platform:x86 /UseVsixExtensions:true /inIsolation
</code></pre>

<p>it fails when it starts to execute the tests in <code>dll1.dll</code>.</p>

<p>The error message we get is:</p>

<pre><code>Failed   dll1_test1
Error Message:
   Failed to set up the execution context to run the test
</code></pre>

<p>and repeats that message for all the tests in that DLL.</p>

<p>This doesn't seem to be an issue on the 64 bit builds though.  It also doesn't occur when running all the tests in the VS IDE.</p>

<p>Does anyone know where to start looking to determine why the order matters for the 32 bit case?</p>
",https://stackoverflow.com/questions/50611042/unit-testing-fails-when-listing-dlls-in-particular-order-but-only-in-32-bit-com,"['unit-testing', 'visual-studio-2017', 'vstest', 'vstest.console.exe']",58,FALSE,1,0
Unit Testing .Net CORE 2.0 WebAPI - Mock (MOQ) HTTP POST with text stream body (not model),"<p>I am trying to unit test my HTTP POST method of my .Net CORE 2.0 API Controller which stream-reads data... Cannot use a ""model"" type approach as the incoming stream raw data.</p>

<p>Here is the basics of the controller method.</p>

<pre><code>[HttpPost()]
[Authorize(Roles = ""contributor"")]
public async Task&lt;IActionResult&gt; SubmitReport()
{
    IActionResult result = null;
    _logger.LogInformation(""POST Request"");

    var buffer = new byte[this.Request.ContentLength.Value];

    await this.Request.Body.ReadAsync(buffer, 0, buffer.Length);
    string content = System.Text.Encoding.UTF8.GetString(buffer);

    // Do something with the 'content'

    return (Accepted());  // Assuming all was OK
}
</code></pre>

<p>And here's my Unit Test... or rather as far as I can get..</p>

<pre><code>[TestMethod]
public void eFormController_SubmitReport_MockService_ExpectHttpStatusAccepted()
{
    var mockContextAccessor = new Mock&lt;IHttpContextAccessor&gt;();
    var context = new DefaultHttpContext();
    mockContextAccessor.Setup(x =&gt; x.HttpContext).Returns(context);

    var mockLogger = new Mock&lt;ILogger&lt;object&gt;&gt;();
    var ctrl = new Controllers.eFormsController();

    var result = ctrl.SubmitReport();

    Assert.IsInstanceOfType(result, typeof(Microsoft.AspNetCore.Mvc.AcceptedResult));
}
</code></pre>

<p>When I run the test as it stands, the <code>this.Request</code> property is <code>null</code> so how do I Mock a proper HTTP POST request.</p>

<p>Google has yet to yield any favourable results as they all assume a fully defined model, and not a <strong>text stream</strong></p>
",https://stackoverflow.com/questions/52949573/unit-testing-net-core-2-0-webapi-mock-moq-http-post-with-text-stream-body,"['c#', 'unit-testing', 'asp.net-core', 'moq', 'asp.net-core-2.0']",5971,TRUE,6,1
"Unit testing in React with TypeScript, Jest and Enzyme: Cannot invoke an object which is possibly &#39;undefined&#39;","<p>I'm building a React Native app with TypeScript. I'm doing my component tests using Jest and Enzyme. I'm also using React Navigation</p>

<p><a href=""https://stackoverflow.com/questions/52692824/how-to-test-a-button-click-in-react-with-typescript-jest-and-enzyme"">In my last question</a> <a href=""https://stackoverflow.com/users/10149510/brian-lives-outdoors"">Brian</a> explained to me how to correctly test the press of a button. My problem is that the buttons <code>onPress</code> prop may be undefined. Let me show you the code:</p>



<pre class=""lang-or-tag prettyprint-override""><code>export class HomeScreen extends Component&lt;Props, object&gt; {
  // ... navigationOptions and stuff

  handlePress = () =&gt; {
    this.props.navigation.navigate(""QuestionsScreen"");
  };

  render() {
    return (
      &lt;View style={styles.container}&gt;
        &lt;Button
          raised={true}
          title={strings.painButtonTitle}
          buttonStyle={styles.painButton}
          titleStyle={styles.title}
          onPress={this.handlePress}
        /&gt;
      &lt;/View&gt;
    );
  }
}
</code></pre>

<p>And here is the test I write for testing the interaction with the button:</p>

<pre class=""lang-or-tag prettyprint-override""><code>describe(""interaction"", () =&gt; {
  const props = createTestProps({});
  const wrapper = shallow&lt;HomeScreen&gt;(&lt;HomeScreen {...props} /&gt;);

  describe(""clicking the Pain Button"", () =&gt; {
    it(""should navigate to the 'QuestionsScreen'"", () =&gt; {
      wrapper.instance().handlePress = jest.fn();
      wrapper.find(Button).prop(""onPress"")({} as any);

      expect(wrapper.instance().handlePress).toHaveBeenCalledTimes(1);
    });
  });
});
</code></pre>

<p>The problem is here that my test won't run, because the linter says that <code>onPress</code> may be undefined:</p>

<pre class=""lang-or-tag prettyprint-override""><code>Cannot invoke an object which is possibly 'undefined'.
</code></pre>

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

<p>I tried wrapping my code in an if statement like this:</p>

<pre class=""lang-or-tag prettyprint-override""><code>if (typeof wrapper.find(Button).prop(""onPress"") !== undefined) {
  wrapper.find(Button).prop(""onPress"")({} as any);
}
</code></pre>

<p>But this also does not work.</p>
",https://stackoverflow.com/questions/52697779/unit-testing-in-react-with-typescript-jest-and-enzyme-cannot-invoke-an-object,"['typescript', 'unit-testing', 'react-native', 'jestjs', 'enzyme']",5489,TRUE,11,1
How do I ensure that my log4j is being called once in my unit testing,"<p>I am using <a href=""/questions/tagged/sinon"" class=""post-tag"" title=""show questions tagged &#39;sinon&#39;"" rel=""tag"">sinon</a> with <a href=""/questions/tagged/nodejs"" class=""post-tag"" title=""show questions tagged &#39;nodejs&#39;"" rel=""tag"">nodejs</a>.</p>

<p>How do I ensure that my <code>log4j</code> is being called once in my unit testing. </p>

<p>I am getting this error:</p>

<blockquote>
  <p>TypeError: Attempted to wrap undefined property info as function.</p>
</blockquote>

<p>main.js:</p>

<pre><code>let log = require('log4js').getLogger(""main"");

...
personDao.updatePerson(param,
                (updatePerson) =&gt; updatePersonCallBack(updatePersonResult));
...

let updatePersonCallBack= exports.updatePersonCallBack= (result) =&gt; {
    log.info(""SUCCESS"", result)
}
</code></pre>

<p>main.spec.js:</p>

<pre><code>it('updatePersonCallBack', (done) =&gt; {

        let getInfoSpy = sinon.spy(log, ""info"");

        let updatePersonResult= 1;

        main.updatePersonCallBack(updatePersonResult);
        should.equal(getInfoSpy.callCount, 1);

        done();
    });
</code></pre>
",https://stackoverflow.com/questions/53908638/how-do-i-ensure-that-my-log4j-is-being-called-once-in-my-unit-testing,"['javascript', 'node.js', 'unit-testing', 'sinon']",218,FALSE,1,1
"In php unit testing I&#39;m getting an illegal string error, ErrorException: Illegal string offset &#39;tableData&#39;","<p>The controller and unit testController in laravel. and getting the error of illegal string of the 'tableData'which is defined to map the array of $arrViewBoundData</p>

<pre><code> public function getGroupList()
        {
            try {
                $requiredPermissions = [
                    config('permission.group_list_view_own'),
                    config('permission.group_list_view_all'),
                ];
                if (!$this-&gt;userPermissionHelper-&gt;checkHasPermissionFor($requiredPermissions)) {
                    return view('error.permission-denied');
                }
                $arrGroup = $this-&gt;groupRepo-&gt;getGroupList(Input::get());
                return view('group.index', $arrGroup);
            } catch (\Exception $ex) {
                return view('error.error_404');
            }
        }
    public function testGetGroupListForListOfRecords()
        {
            $this-&gt;app-&gt;instance('middleware.disable', true);
            $sampleJsonFile = file_get_contents(base_path('tests\Unit\sample_outputs\group_list.json'));
            $sampleOutput = json_decode($sampleJsonFile, true);

            $sampleOutput['tableData'] = array((object) $sampleOutput['tableData']);
            $sampleOutput['langList'] = array((object) $sampleOutput['langList']);
            $this-&gt;objMockGroupRepositoryInterface-&gt;shouldReceive('getGroupList')-&gt;andReturn($sampleOutput);
            $this-&gt;app-&gt;instance(GroupRepositoryInterface::class, $this-&gt;objMockGroupRepositoryInterface);
            $response = $this-&gt;call('GET', 'test-group/group');
            $arrViewBoundData = $response-&gt;original;
            $this-&gt;assertGreaterThan(0,count($arrViewBoundData['tableData']));
        }
</code></pre>
",https://stackoverflow.com/questions/48396283/in-php-unit-testing-im-getting-an-illegal-string-error-errorexception-illegal,"['php', 'laravel', 'phpstorm']",196,FALSE,1,0
How can I mock an update of an object in an array : Unit testing Angular,"<p>I am <strong>unit test</strong>ing my <strong>redux reducers</strong>, I have tested <strong>GET</strong>, and <strong>CREATE</strong> so far however I don't know how to do the <strong>UPDATE</strong>. I can't figure out how to mock it. I have also added the code for the <strong>UPDATE</strong> in the <strong>reducer</strong> below.</p>

<p>This is what I have done so far in the test: </p>

<pre><code>describe('register reducer', () =&gt; {
    let initialState;
    beforeEach(() =&gt; {
        initialState = UsersService.getInitialUsersState();
        deepFreeze(initialState);
    })

    it('should return the initial state', () =&gt; {
        expect(usersReducer(undefined, [])).toEqual(initialState);
    });
    it('Should add a new baby object to the babies array', () =&gt; {
        // create 'mock' of initial state
        // add baby by calling reducer function
        // check that state is correct. Use deep freeze to check no mutations.
        let afterState = UsersService.getInitialUsersState();
        let baby = {
            firstname: 'Peter',
            lastname: 'Petursson',
            username: 'test baby 1',
            birthDate: new Date(2018, 0, 1),
            area: 'Copenhagen',
            rating: []
        };
        afterState.babies.push(baby);

        let newState = usersReducer(initialState, {
            type: types.UsersActions.CREATED_BABY,
            payload: baby
        });
        expect(newState.babies.length).toEqual(1);
        expect(newState).toEqual(afterState);
    });
    it('Should get the babies array', () =&gt; {
        let afterState = UsersService.getInitialUsersState();
        let babies = [{
            _id: ""5ad228ffdc32f1a42f5d3259"",
            firstname: ""Oliver"",
            lastname: ""Hultgren"",
            username: ""o@h"",
            birthDate: new Date(2018, 0, 1),
            area: ""København Ø"",
            rating: [],
            userType: ""baby"",
            dataClient: ""Julia""
        },
        {
            _id: ""5ad229d7dc32f1a42f5d325a"",
            firstname: ""Oli"",
            lastname: ""Hult"",
            username: ""o.h@dk"",
            birthDate: new Date(2018, 0, 1),
            area: ""København V"",
            rating: [],
            userType: ""baby"",
            dataClient: ""Julia"",
        }, {
            _id: ""5ad309337cbda3002a7e92e0"",
            firstname: ""Jenny"",
            lastname: ""Lopez"",
            username: ""jl@com"",
            birthDate: new Date(2018, 0, 1),
            area: ""København Ø"",
            rating: [],
            userType: ""baby"",
            dataClient: ""Julia"",
        }]
        afterState.babies = babies;
        let newState = usersReducer(initialState, {
            type: types.UsersActions.RECEIVED_BABIES,
            payload: babies

        });
        expect(newState).toEqual(afterState);
    })
</code></pre>

<p>//update comes here</p>

<pre><code>it('Should update a baby object in the babies array', () =&gt; {}}
</code></pre>

<p>This is how my actual reducer look like:</p>

<pre><code> case UsersActions.UPDATED_BABY:
            let indexBaby = state.babies.findIndex(baby =&gt; { return baby._id === action.payload._id });
            return tassign(state, { babies: [...state.babies.slice(0, indexBaby), action.payload, ...state.babies.slice(indexBaby + 1)] });
</code></pre>
",https://stackoverflow.com/questions/50586925/how-can-i-mock-an-update-of-an-object-in-an-array-unit-testing-angular,"['angular', 'unit-testing', 'mocking', 'updates']",2467,TRUE,0,1
Unit testing a function that is calling another static function in android java using Mockito,"<p>I have a scenario where I call a static function from another function. How can we write unit tests in such cases?</p>

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

<pre><code>public class TradesHelper {

public static double calculatePL(Market market, Trade trade) {
    double pl = (Helper.priceDifference(market, trade) / market.getSize()) * trade.getQuantity() * Helper.effectiveValue(market);
    return pl;
    }
}

public class Helper {
public static priceDifference(Market market, Trade trade) {
           //Do something here
      }
}
</code></pre>

<p>This is how I am trying to write unit test case:</p>

<p>I have written a unit test case for Helper class. But for TradesHelper class this is how I am trying to write:</p>

<pre><code>public class TradesHelperTest {

@Mock
Market market;

@Mock
Trade trade;

@Test
public void calculatePlFromPips_Test() {

    //Trying to return a value when priceDifference function in Helper class is called

    Helper helper1 = spy(new Helper());     
    doReturn(0.0012999999999999678).when(helper1).priceDifference(new Market(),new Trade());   

}
</code></pre>

<p>But I am getting thus error:</p>

<pre><code>org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here:

E.g. thenReturn() may be missing.
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, which is not supported
3: you are stubbing the behaviour of another mock inside before      'thenReturn' instruction if completed
</code></pre>

<p>I am new to writing unit tests. Can someone guide me on how to do it write?</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/48278839/unit-testing-a-function-that-is-calling-another-static-function-in-android-java,"['java', 'android', 'unit-testing', 'mockito']",503,TRUE,0,1
Unit testing fails on iPhone X - Failed to scroll to visible (by AX action) Button,"<p>I have a test that taps on different tab bar buttons. The test fails with below error  on iPhone X. But runs successfully on iPhone SE, iPhone 6 and 8 Plus.</p>

<p>what could be the issue?</p>

<pre><code>Failed to scroll to visible (by AX action) Button

    func testForScreenShots() {       

        let app = XCUIApplication()
        continueAfterFailure = false

        let tabBarsQuery = app.tabBars

        tabBarsQuery.buttons[""My Shelf""].tap()

}
</code></pre>

<p>Thanks Ashish</p>
",https://stackoverflow.com/questions/50454841/unit-testing-fails-on-iphone-x-failed-to-scroll-to-visible-by-ax-action-butt,"['ios', 'xcode', 'unit-testing']",1085,FALSE,0,1
unit testing an opencv c++ program that takes a picture and saves it to file,"<p>I'm new to unit testing and I'm wondering if somebody could tell me what a unit test for the code below might look like and do? The code uses the opencv library to take a picture and store it to file. Would you write 3 test cases to check if opening the camera, taking a picture and saving to file was successful?  </p>

<pre><code>#include ""opencv2/opencv.hpp""

using namespace cv;

int main(int, char**)
{
    VideoCapture cap(0); // open the default camera
    if(!cap.isOpened())  // check if we succeeded
        return -1;


        Mat frame;
        cap &gt;&gt; frame; // get a new frame from camera
        // do any processing
        imwrite(""/home/user/cpp_test/image.png"", frame);

    // the camera will be deinitialized automatically in VideoCapture destructor
    return 0;
}
</code></pre>
",https://stackoverflow.com/questions/50113400/unit-testing-an-opencv-c-program-that-takes-a-picture-and-saves-it-to-file,"['c++', 'unit-testing', 'opencv']",1867,TRUE,0,1
Does someone have an example of Unit-Testing a SOAP API with Python Zeep and Mock?,"<p>I'm building a Python app that accesses a 3rd party SOAP API with Python-zeep. I want to implement some unit-tests using mocked responses as I don't always have a live server to run my tests against.</p>

<p>I'm new to unit-testing and not quite sure where to start. I've seen examples of using mock with the requests library, but not really sure how to translate this into Zeep.</p>

<p>On one of my Models I have a method to get all DevicePools from a SOAP API. Here's an excerpt of the relevant code (I use a helper method to provide the service object as I plan on using this in many other methods).</p>

<pre><code># Get Zeep Service Object to make AXL API calls
service = get_axl_client(self)

# Get list of all DevicePools present in the cluster
resp = service.listDevicePool(searchCriteria={'name': '%'},
                              returnedTags={'name': '', 'uuid': ''})
</code></pre>

<p>I want to mock the resp object, however this is of type zeep.objects.ListDevicePoolRes (a dynamic type based on the parsing of the WSDL) and I can't just instantiate an object with static values. </p>

<p>Maybe I'm on the wrong track here and would have to go a bit deeper and actually mock some internals of the zeep library and replace the requests response before zeep parses the XML?</p>

<p>If someone had an example of something similar it would be greatly appreciated.</p>
",https://stackoverflow.com/questions/53914039/does-someone-have-an-example-of-unit-testing-a-soap-api-with-python-zeep-and-moc,"['python', 'unit-testing', 'mocking', 'zeep']",3039,TRUE,5,2
How to fetch button element in Angular 2 reactive form for Jasmine/Karma unit testing?,"<p>I am unable to get button element in Angular reactive form for unit testing. Button doesn't have 'id', so i tried to get below way but i am getting an error like this ""Failed: Failed to execute 'matches' on 'Element': '[(click)=""onAppend()""]' is not a valid selector.""  </p>

<p>This is the way i tried to fetch:</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>let btn=fixture.debugElement.query(By.css('[(click)=""onSend()""]'));
    expect(btn.nativeElement.enabled).toBe(true)</code></pre>
</div>
</div>
</p>

<p>This is my button:</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;button class=""bx--btn bx--btn--primary"" type=""button"" (click)=""onSend()""  [disabled]=""!valid || !purchaseForm.valid""&gt;Send&lt;/button&gt; </code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/51765438/how-to-fetch-button-element-in-angular-2-reactive-form-for-jasmine-karma-unit-te,"['angular', 'karma-jasmine', 'angular-reactive-forms']",145,FALSE,0,0
How to implement jacoco code coverage in Spock unit testing for generic &#39;Exception&#39; catch block?,"<p>I have a springboot rest api which performs 'Select' operation in database based on 'studentId' which is of type 'String'.
Below I have simulated the scenario with a sample student example.</p>

<p>I have written 2 unit tests ( using spock and junit mockito) to validate the functionality. ( Unit test code I have not mentioned in this question hoping that it would not be required )</p>

<p>units tests --</p>

<ol>
<li><p>Calling the api with a valid 'studentId' for which a record exists in database
This unit test validates the functionality written in try {} block (else part )</p></li>
<li><p>Calling the api with a invalid student id. There is no record in the database for this student id.
This unit test validates the functionality written in try {} block (if condition) and later goes in the catch(NoDataFoundException) block </p></li>
</ol>

<p>I have also implemented jacoco to measure the code coverage. The problem is jacoco covers the entire code and marks it as green, except for catch(Exception) block. 
The reason is pretty obvious that I have not provided any unit test to cover catch(Exception) block.
The problem is I could not think of any scenario which can cause an 'Exception'. still I would like to keep the catch(Exception) in my code so as to catch any unpredictable exceptions </p>

<p>Some people may argue that I should not have catch(Exception) and they might be right with their reasoning, but its important, at least the nature of project I am working on, it really is.</p>

<p>Did some one come across such kind of situation? What you did to cover catch(Exception) in jacoco code coverage report. Any advice, pointers would be much appreciated.</p>

<p>Below is controller class-</p>

<pre><code>@RestController
public class ApiController {

    @Autowired
    StudentInfoRepository studentInfo; // StudentInfoRepository is Interface having method 'fetchStudentDetails'. This method is provided implementation in a class named 'StudentInfoImplementation'

    @RequestMapping(value = ""/students/{studentId}"", produces = ""application/json"", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity&lt;Object&gt; getStudentInfo(@PathVariable(""studentId"") String studentId) throws Exception {

    Result&lt;StudentModelClass&gt; studentList = null;
    ResponseEntity&lt;Object&gt; response = null;
    try {
        studentList = studentInfo.fetchStudentDetails(studentId);
        //if no records are returned for given studentId then throw custom 'NoDataFoundException'
        if (studentList.isExhausted()) {
            throw new NoDataFoundException(""No record found for the requested studentId: "" + studentid);

        //if records are returned for the given studentId then return 200 response and list of records
        } else {
            response = new ResponseEntity&lt;Object&gt;(studentList.all(), HttpStatus.OK);
            return response;
        }
    } 

    catch(NoDataFoundException ex){
        throw new NoDataFoundException(ex.getMessage());
    } 

    catch(Exception ex){
        throw new Exception(ex);
    }
}
</code></pre>

<p>}</p>
",https://stackoverflow.com/questions/52308592/how-to-implement-jacoco-code-coverage-in-spock-unit-testing-for-generic-excepti,"['rest', 'api', 'junit', 'spock', 'jacoco']",1158,TRUE,0,1
Error in Unit Testing Angular code with Karma and Jasmine - Executed 0 of 0 ERROR,"<p>I'm trying to unit test my Angular code with Karma and Jasmine. After navigating to the project folder I have executed the following commands in the mentioned sequence:</p>

<p><strong>npm install --save-dev jasmine</strong> (for installing Jasmine)<br>
<strong>npm install --save-dev karma</strong> (for installing Karma)<br>
<strong>npm install --save-dev karma-jasmine</strong> (for installing Karma dependencies)<br>
<strong>karma init</strong></p>

<p>After that when I try to run <strong>karma start</strong>, I am getting the below error which says <strong>Executed 0 of 0 ERROR</strong> and nothing specific.</p>

<p>Any clue behind why I am getting this? I have also added my karma.config.js and spec-bundle.js file contents below.</p>

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

<p>My karma.config.js 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>   // Karma configuration file, see link for more information
// https://karma-runner.github.io/0.13/config/configuration-file.html

module.exports = function (config) {
config.set({
    basePath: '.',
    frameworks: ['jasmine'],
    files: [
        '../../wwwroot/dist/vendor.js',
        './boot-tests.ts'
    ],
    preprocessors: {
        './boot-tests.ts': ['webpack']
    },
    reporters: ['progress'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    //browsers: ['PhantomJS'], // use headless browswer
    browsers: [
        'Chrome',
        'Chrome_with_debugging'
    ],

    customLaunchers: {

        Chrome_with_debugging: {
            base: 'Chrome',
            //chromeDataDir: path.resolve(__dirname, '.chrome'),
            flags: ['--remote-debugging-port=9333'],
            displayName: 'Chrome with remote debugging'
        }
    },
    mime: { 'application/javascript': ['ts', 'tsx'] },
    // Which plugins to enable defaults to karma-*

    singleRun: false,
    webpack: require('../../webpack.config.js')().filter(config =&gt; config.target !== 'node'), // Test against client bundle, because tests run in a browser
    webpackMiddleware: { stats: 'errors-only' }
});
};</code></pre>
</div>
</div>
</p>

<p>My spec-bundle.js 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>/*
 * When testing with webpack and ES6, we have to do some extra
 * things to get testing to work right. Because we are gonna write tests
 * in ES6 too, we have to compile those as well. That's handled in
 * karma.conf.js with the karma-webpack plugin. This is the entry
 * file for webpack test. Just like webpack will create a bundle.js
 * file for our client, when we run test, it will compile and bundle them
 * all here! Crazy huh. So we need to do some setup
 */
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');

// RxJS
require('rxjs/Rx');

var testing = require('@angular/core/testing');
var browser = require('@angular/platform-browser-dynamic/testing');

testing.TestBed.initTestEnvironment(
  browser.BrowserDynamicTestingModule,
  browser.platformBrowserDynamicTesting()
);

/*
 * Ok, this is kinda crazy. We can use the context method on
 * require that webpack created in order to tell webpack
 * what files we actually want to require or import.
 * Below, context will be a function/object with file names as keys.
 * Using that regex we are saying look in ../Client then find
 * any file that ends with spec.ts and get its path. By passing in true
 * we say do this recursively
 */
var testContext = require.context('../ClientApp', true, /\.spec\.ts/);

/*
 * get all the files, for each file, call the context function
 * that will require the file and load it up here. Context will
 * loop and require those spec files here
 */
function requireAll(requireContext) {
  return requireContext.keys().map(requireContext);
}

// requires and returns all modules that match
var modules = requireAll(testContext);</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/49605530/error-in-unit-testing-angular-code-with-karma-and-jasmine-executed-0-of-0-erro,"['angular', 'unit-testing', 'karma-jasmine']",919,FALSE,0,0
Why the Unit testing a String field sometime failed using this generic dto testing code?,"<p>I am testing my DTOs using a generic dto testing code that I found online <a href=""https://objectpartners.com/2016/02/16/automatically-junit-test-dto-and-transfer-objects/"" rel=""nofollow noreferrer"">https://objectpartners.com/2016/02/16/automatically-junit-test-dto-and-transfer-objects/</a>. Most of the time, it works perfect. Suddenly one day, I got an test failure for just one test class. And it is occasionally occurred, which means sometime it happened, most of the time, it works fine. </p>

<pre><code>pubic class MyDtoClass implements Serializable {

    private String includeNullValue;

    public String getIncludeNullValue() {
        return includeNullValue;
    }

    public void setIncludeNullValue(String includeNullValue) {
        this.includeNullValue = includeNullValue;
    }
}
</code></pre>

<p>The test output the following error message when it failed: </p>

<pre><code>java.lang.AssertionError: includeNullValue is different expected same:&lt;&gt; was not:&lt;null&gt;
Expected :
Actual   :null
</code></pre>

<p>My test class is as below</p>

<pre><code>public class MyDtoClassTest extends DtoTest&lt;MyDtoClass&gt; {

    private static MyDtoClass myDtoClass;

    @Before
    public void setup() {
        myDtoClass = new MyDtoClass();
    }

    @Override
    protected MyDtoClass getInstance() {
        return myDtoClass;
    }
}
</code></pre>

<p>Any clue? Thanks in advance.</p>

<p><strong>UPDATE:</strong> As suggested, I directly post the DtoTest.java here as below</p>

<pre><code>public abstract class DtoTest&lt;T&gt; {

    /** A map of default mappers for common objects. */
    private static final ImmutableMap&lt;Class&lt;?&gt;, Supplier&lt;?&gt;&gt; DEFAULT_MAPPERS;

    static {
        final Builder&lt;Class&lt;?&gt;, Supplier&lt;?&gt;&gt; mapperBuilder = ImmutableMap.builder();

        /* Primitives */
        mapperBuilder.put(int.class, () -&gt; 0);
        mapperBuilder.put(double.class, () -&gt; 0.0d);
        mapperBuilder.put(float.class, () -&gt; 0.0f);
        mapperBuilder.put(long.class, () -&gt; 0l);
        mapperBuilder.put(boolean.class, () -&gt; true);
        mapperBuilder.put(short.class, () -&gt; (short) 0);
        mapperBuilder.put(byte.class, () -&gt; (byte) 0);
        mapperBuilder.put(char.class, () -&gt; (char) 0);

        mapperBuilder.put(Integer.class, () -&gt; Integer.valueOf(0));
        mapperBuilder.put(Double.class, () -&gt; Double.valueOf(0.0));
        mapperBuilder.put(Float.class, () -&gt; Float.valueOf(0.0f));
        mapperBuilder.put(Long.class, () -&gt; Long.valueOf(0));
        mapperBuilder.put(Boolean.class, () -&gt; Boolean.TRUE);
        mapperBuilder.put(Short.class, () -&gt; Short.valueOf((short) 0));
        mapperBuilder.put(Byte.class, () -&gt; Byte.valueOf((byte) 0));
        mapperBuilder.put(Character.class, () -&gt; Character.valueOf((char) 0));

        mapperBuilder.put(BigDecimal.class, () -&gt; BigDecimal.ONE);
        mapperBuilder.put(Date.class, () -&gt; new Date());

        /* Collection Types. */
        mapperBuilder.put(Set.class, () -&gt; Collections.emptySet());
        mapperBuilder.put(SortedSet.class, () -&gt; Collections.emptySortedSet());
        mapperBuilder.put(List.class, () -&gt; Collections.emptyList());
        mapperBuilder.put(Map.class, () -&gt; Collections.emptyMap());
        mapperBuilder.put(SortedMap.class, () -&gt; Collections.emptySortedMap());

        DEFAULT_MAPPERS = mapperBuilder.build();
    }

    /** The get fields to ignore and not try to test. */
    private final Set&lt;String&gt; ignoredGetFields;

    /**
     * A custom mapper. Normally used when the test class has abstract objects.
     */
    private final ImmutableMap&lt;Class&lt;?&gt;, Supplier&lt;?&gt;&gt; mappers;

    /**
     * Creates an instance of {@link DtoTest} with the default ignore fields.
     */
    protected DtoTest() {
        this(null, null);
    }

    /**
     * Creates an instance of {@link DtoTest} with ignore fields and additional custom mappers.
     *
     * @param customMappers Any custom mappers for a given class type.
     * @param ignoreFields The getters which should be ignored (e.g., ""getId"" or ""isActive"").
     */
    protected DtoTest(Map&lt;Class&lt;?&gt;, Supplier&lt;?&gt;&gt; customMappers, Set&lt;String&gt; ignoreFields) {
        this.ignoredGetFields = new HashSet&lt;&gt;();
        if (ignoreFields != null) {
            this.ignoredGetFields.addAll(ignoreFields);
        }
        this.ignoredGetFields.add(""getClass"");

        if (customMappers == null) {
            this.mappers = DEFAULT_MAPPERS;
        } else {
            final Builder&lt;Class&lt;?&gt;, Supplier&lt;?&gt;&gt; builder = ImmutableMap.builder();
            builder.putAll(customMappers);
            builder.putAll(DEFAULT_MAPPERS);
            this.mappers = builder.build();
        }
    }

    /**
     * Calls a getter and verifies the result is what is expected.
     *
     * @param fieldName The field name (used for error messages).
     * @param getter The get {@link Method}.
     * @param instance The test instance.
     * @param expected The expected result.
     *
     * @throws IllegalAccessException if this Method object is enforcing Java language access control and the underlying
     *             method is inaccessible.
     * @throws IllegalArgumentException if the method is an instance method and the specified object argument is not an
     *             instance of the class or interface declaring the underlying method (or of a subclass or implementor
     *             thereof); if the number of actual and formal parameters differ; if an unwrapping conversion for
     *             primitive arguments fails; or if, after possible unwrapping, a parameter value cannot be converted to
     *             the corresponding formal parameter type by a method invocation conversion.
     * @throws InvocationTargetException if the underlying method throws an exception.
     */
    private void callGetter(String fieldName, Method getter, T instance, Object expected)
            throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {

        final Object getResult = getter.invoke(instance);

        if (getter.getReturnType().isPrimitive()) {
            /* Calling assetEquals() here due to autoboxing of primitive to object type. */
            assertEquals(fieldName + "" is different"", expected, getResult);
        } else {
            /* This is a normal object. The object passed in should be the exactly same object we get back. */
            assertSame(fieldName + "" is different"", expected, getResult);
        }
    }

    /**
     * Creates an object for the given {@link Class}.
     *
     * @param fieldName The name of the field.
     * @param clazz The {@link Class} type to create.
     *
     * @return A new instance for the given {@link Class}.
     *
     * @throws InstantiationException If this Class represents an abstract class, an interface, an array class, a
     *             primitive type, or void; or if the class has no nullary constructor; or if the instantiation fails
     *             for some other reason.
     * @throws IllegalAccessException If the class or its nullary constructor is not accessible.
     *
     */
    private Object createObject(String fieldName, Class&lt;?&gt; clazz)
            throws InstantiationException, IllegalAccessException {

      try {      
          final Supplier&lt;?&gt; supplier = this.mappers.get(clazz);
          if (supplier != null) {
              return supplier.get();
          }

          if (clazz.isEnum()) {
              return clazz.getEnumConstants()[0];
          }

          return clazz.newInstance();        
        } catch (IllegalAccessException | InstantiationException e) {
            throw new RuntimeException(""Unable to create objects for field '"" + fieldName + ""'."", e);
        }
    }

    /**
     * Returns an instance to use to test the get and set methods.
     *
     * @return An instance to use to test the get and set methods.
     */
    protected abstract T getInstance();

    /**
     * Tests all the getters and setters. Verifies that when a set method is called, that the get method returns the
     * same thing. This will also use reflection to set the field if no setter exists (mainly used for user immutable
     * entities but Hibernate normally populates).
     *
     * @throws Exception If an expected error occurs.
     */
    @Test
    public void testGettersAndSetters() throws Exception {
        /* Sort items for consistent test runs. */
        final SortedMap&lt;String, GetterSetterPair&gt; getterSetterMapping = new TreeMap&lt;&gt;();

        final T instance = getInstance();

        for (final Method method : instance.getClass().getMethods()) {
            final String methodName = method.getName();

            if (this.ignoredGetFields.contains(methodName)) {
                continue;
            }

            String objectName;
            if (methodName.startsWith(""get"") &amp;&amp; method.getParameters().length == 0) {
                /* Found the get method. */
                objectName = methodName.substring(""get"".length());

                GetterSetterPair getterSettingPair = getterSetterMapping.get(objectName);
                if (getterSettingPair == null) {
                    getterSettingPair = new GetterSetterPair();
                    getterSetterMapping.put(objectName, getterSettingPair);
                }
                getterSettingPair.setGetter(method);
            } else if (methodName.startsWith(""set"") &amp;&amp; method.getParameters().length == 1) {
                /* Found the set method. */
                objectName = methodName.substring(""set"".length());

                GetterSetterPair getterSettingPair = getterSetterMapping.get(objectName);
                if (getterSettingPair == null) {
                    getterSettingPair = new GetterSetterPair();
                    getterSetterMapping.put(objectName, getterSettingPair);
                }
                getterSettingPair.setSetter(method);
            } else if (methodName.startsWith(""is"") &amp;&amp; method.getParameters().length == 0) {
                /* Found the is method, which really is a get method. */
                objectName = methodName.substring(""is"".length());

                GetterSetterPair getterSettingPair = getterSetterMapping.get(objectName);
                if (getterSettingPair == null) {
                    getterSettingPair = new GetterSetterPair();
                    getterSetterMapping.put(objectName, getterSettingPair);
                }
                getterSettingPair.setGetter(method);
            }
        }

        /*
         * Found all our mappings. Now call the getter and setter or set the field via reflection and call the getting
         * it doesn't have a setter.
         */
        for (final Entry&lt;String, GetterSetterPair&gt; entry : getterSetterMapping.entrySet()) {
            final GetterSetterPair pair = entry.getValue();

            final String objectName = entry.getKey();
            final String fieldName = objectName.substring(0, 1).toLowerCase() + objectName.substring(1);

            if (pair.hasGetterAndSetter()) {
                /* Create an object. */
                final Class&lt;?&gt; parameterType = pair.getSetter().getParameterTypes()[0];
                final Object newObject = createObject(fieldName, parameterType);

                pair.getSetter().invoke(instance, newObject);

                callGetter(fieldName, pair.getGetter(), instance, newObject);
            } else if (pair.getGetter() != null) {
                /*
                 * Object is immutable (no setter but Hibernate or something else sets it via reflection). Use
                 * reflection to set object and verify that same object is returned when calling the getter.
                 */
                final Object newObject = createObject(fieldName, pair.getGetter().getReturnType());
                final Field field = instance.getClass().getDeclaredField(fieldName);
                field.setAccessible(true);
                field.set(instance, newObject);

                callGetter(fieldName, pair.getGetter(), instance, newObject);
            }
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/50957696/why-the-unit-testing-a-string-field-sometime-failed-using-this-generic-dto-testi,"['java', 'unit-testing', 'junit']",374,FALSE,0,1
Should I create an interface for every class to make my code testable (unit testing),"<p>I'm trying to learn how to create valuable unit tests.
In each tutorial I saw people create interfaces for every dependency to create a mock.</p>

<p>Is it mean that I should always create an interface for every class I have in my project? I don't know is it a good or a bad idea but every time I see a rule with ""always"" I get suspicious. </p>
",https://stackoverflow.com/questions/51114228/should-i-create-an-interface-for-every-class-to-make-my-code-testable-unit-test,"['unit-testing', 'testing', 'interface']",445,TRUE,0,1
How can I decouple instantiation from implementation for unit testing if DI is not feasible?,"<p>I have the following code (simplified and details changed for this question):</p>

<pre><code>    class model_to_be_tested {
        // an array that holds a collection of thing A
        public $array_of_thing_A;

        // already doing constructor injection for the data object
        public __construct($data_object) {
         // details here
        }

        public function add_new_thing_A($has_relationship) {
          $thing_A = new Thing_A();
          $thing_A-&gt;is_thing = true;
          $thing_A-&gt;has_relationship_with_thing_B = $has_relationship;

          if ($has_relationship) {
             $thing_B = new Thing_B();
             $thing_A-&gt;relationship_with = $thing_B;
          }

          $this-&gt;array_of_thing_A[] = $thing_A;
      }
    }
</code></pre>

<p>In the above example, I have to decouple the instantiation of Thing_A and Thing_B from the add_new_thing method. However, a simple constructor injection will not do for these two classes. This is because I need fresh instances of Thing_A and Thing_B every time add_new_thing is called so that Thing_A can be added to the array_of_thing_A.</p>

<p>How can I make this function unit testable? And more specifically for me to use mocks of Thing_A and Thing_B in testing this function in PHPUnit?</p>

<p>Any suggestions with code example will be appreciated.</p>

<p>Additionally, I would like to mention that Thing_A and Thing_B are used elsewhere in the codebase that I am working with and the code using these classes will eventually need to be unit tested. Solutions that are too localized and would cause repeated code elsewhere will not be too ideal in my situation. Thank you.</p>
",https://stackoverflow.com/questions/48312364/how-can-i-decouple-instantiation-from-implementation-for-unit-testing-if-di-is-n,"['php', 'unit-testing', 'phpunit']",81,TRUE,0,2
How to mock express requests/resonce when unit testing to placate the VSCode typescript compiler,"<p>I'm building out a nodejs server using express and Typescript. Using jest I'm building unit tests for my controllers and middleware. I've noticed that the inbuilt TS compiler in VSCode isn't happy when I pass empty Request objects to my controllers when testing. </p>

<pre><code>    it('should respond with json data when promise resolved', () =&gt; {
        const mockNext = td.function();
        const mockResponse = td.object(['status', 'json']);
        const captor = td.matchers.captor();
        const resolvedPromise = () =&gt; Promise.resolve({ data: 'test' });

        return BaseResponse.json(resolvedPromise)({}, mockResponse, mockNext).then(() =&gt; {
               td.verify(mockResponse.json(captor.capture()));
               expect(captor.values.length).toBe(1);
               expect(captor.values[0]).toEqual({ data: 'test' });
        });
  });
</code></pre>

<p><a href=""https://i.stack.imgur.com/M8TNV.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/M8TNV.png"" alt=""Code snapshot""></a></p>

<p>What is the correct way to mock the request and response objects from Express to satisfy the Typescript compiler. My tests do run correctly, so I think this is just an IDE issue.</p>
",https://stackoverflow.com/questions/49201119/how-to-mock-express-requests-resonce-when-unit-testing-to-placate-the-vscode-typ,"['node.js', 'typescript', 'express', 'visual-studio-code', 'jestjs']",1478,TRUE,0,1
How to refer to conditional elements when unit testing React components using jest and enzyme,"<p>I'm trying to test a component which should show a login and subscribe button when a user is not authenticated, but should show a logout button when a user is authenticated.</p>

<p>How should I refer to these buttons when making the test? </p>

<p>All examples I found is people doing things like:</p>

<pre><code>expect(wrapper.find(Button).lenght).toBe(1); // or whatever
</code></pre>

<p>But this obviously doesn't fit my case, since I always have at least one button and they are all the same, except for its text and action. </p>

<p>So I think I need some way to refer to these buttons, so I could pass an authenticated prop and check if exactly the logout button is rendered.</p>

<p>What would be the best approach on doing that?</p>
",https://stackoverflow.com/questions/48373279/how-to-refer-to-conditional-elements-when-unit-testing-react-components-using-je,"['reactjs', 'unit-testing', 'jestjs', 'enzyme']",3567,TRUE,0,3
Angular Jasmine: Unit testing a method that is calling a service without doing actuall http call,"<p>I'm pretty new to unit tests in Jasmine and Angular, so please bear with me :)</p>

<p>I am trying to write a unit test for a method that shoud return an object of type <code>ArtworkDetail</code>, but don't want the service to do an actual http call. I heard about mocking data and mocking services, but I'm not sure how to do it myself. Do I make a mock object in my unit test file or do I create a mock service? Any pointers are appreciated!</p>

<p><strong>app.component.ts</strong></p>

<pre><code>public setArtworkDetail(id: string): void {
  this.details = undefined;

  this.artworksService.getArtworkDetail(id)
    .subscribe((detailData: ArtworkDetail) =&gt; {
      this.details = detailData;
    });
}
</code></pre>

<p><strong>app.component.spec.ts</strong></p>

<pre><code>describe('AppComponent', () =&gt; {
  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent,
        IndexComponent,
        DetailsComponent,
        NavbarComponent
      ],
      providers: [
        {provide: ArtworksService, class: MockArtworksService}
      ]
    }).compileComponents();
  }));

  it('should return an ArtworkDetail when calling setArtworkDetail()', (() =&gt; {

  ...

  }));
</code></pre>

<p><strong>artwork-detail.model.ts</strong></p>

<pre><code>export interface ArtworkDetail {
  id: string;
  title: string;
  url: string;
  year: number;
  description: string;
  artist: string;
}
</code></pre>
",https://stackoverflow.com/questions/49493773/angular-jasmine-unit-testing-a-method-that-is-calling-a-service-without-doing-a,"['angular', 'unit-testing', 'http', 'jasmine', 'mocking']",9378,TRUE,2,1
Advantages of using EF core in memory database provider for unit testing of asp.net core application,"<p>Is entity framework core in memory database provider replace moq ? What should i use for unit testing in my asp.net core application. I am using asp.net core mvc and ef core 2.0.</p>
",https://stackoverflow.com/questions/50126872/advantages-of-using-ef-core-in-memory-database-provider-for-unit-testing-of-asp,"['c#', 'unit-testing', 'asp.net-core', 'in-memory-database', 'ef-core-2.0']",688,TRUE,2,1
Unit testing Episerver - how to add a block to a content area in the test project,"<p>We would like to unit test an Episerver validator that ensures a content area doesn't have two blocks inside it: 
</p>

<pre class=""lang-cs prettyprint-override""><code>public class LandingPageValidator : IValidate
{
    public IEnumerable Validate(LandingPageDataModel instance)
    {
        if (instance.HeroBlock.Count &gt; 1)
        {
            return new ValidationError[]
            {
                new ValidationError()
                {
                    PropertyName = ""Hero Block"",
                    ErrorMessage = ""Can only have one Hero Block""
                }};
        }

        return Enumerable.Empty();
    }
}
</code></pre>

<p>The problem we are facing is: how can we programatically add a second block to a content area, while inside the test project?</p>

<p>We have tried this approach: <a href=""https://stackoverflow.com/questions/27993939/episerver-add-block-to-a-content-area-programmatically"">EpiServer - Add block to a content area programmatically</a> but that seems to work only in the main application (ContentReference.GlobalBlockFooter is null in the test project). </p>

<p>In case it helps, here is the data model. </p>

<pre class=""lang-cs prettyprint-override""><code>public class LandingPageDataModel : BasePageDataModel
{
    [Display(
        Name = ""Hero block"",
        Description = """",
        Order = 140,
        GroupName = SystemTabNames.Content)]
    [AllowedTypes(new[] { typeof(LandingPageHeroDataModel) })]
    public virtual ContentArea HeroBlock { get; set; }
}
</code></pre>

<p>And here is what we have tried: </p>

<pre class=""lang-cs prettyprint-override""><code>    [Fact]
    public void Validate_WhenHasMoreThanOneHeroBlock_ReturnsError()
    {
        // Arrange
        var validator = new LandingPageValidator();
        var model = new LandingPageDataModel { HeroBlock = new ContentArea()};
        var item = new ContentAreaItem();
        model.HeroBlock.Items.Add(item);
        var expected = new ValidationError[]
            {
                new ValidationError()
                {
                    PropertyName = ""Hero Block"",
                    ErrorMessage = ""Can only have one Hero Block""
                }};

        // Act
        var result = validator.Validate(model);

        // Assert
        Assert.Equal(expected, result);
    }
</code></pre>

<p>However, it throws a null reference exception when we try to add the ContentAreaItem to the ContentArea (using model.HeroBlock.Items.Add). The exact error is:</p>

<pre class=""lang-cs prettyprint-override""><code>System.NullReferenceException

Object reference not set to an instance of an object.
at EPiServer.Core.ContentArea.AddContentAreaItemsToFragments(IList items, Int32 startIndex)
</code></pre>
",https://stackoverflow.com/questions/49272159/unit-testing-episerver-how-to-add-a-block-to-a-content-area-in-the-test-projec,"['unit-testing', 'episerver']",675,TRUE,2,1
Doing a mocha and chai unit testing for node js that need to query from dynamodb,"<p>Hi I am new to AWS dynamdoDB and mocha chai unit testing. </p>

<p>I wanted to create a node js unit testing with mocha and chai.
In my test.js i need to get expected outcome from AWS dynamoDB. However i not sure how to do it. </p>

<p>in my test.js </p>

<pre><code>var assert = require('chai').assert;

describle('querying items from dynamodb', function(){
     it('find date in Month collection', function(){

 //not sure how should i put my inputs in here.
      });

   })
</code></pre>

<p>Do you have any articles or resources that I should read on?</p>
",https://stackoverflow.com/questions/53610127/doing-a-mocha-and-chai-unit-testing-for-node-js-that-need-to-query-from-dynamodb,"['unit-testing', 'amazon-dynamodb', 'mocha.js', 'chai']",2540,TRUE,2,1
Unit Testing React Native: NativeModules.RNViewShot is undefined. Make sure the library is linked on the native side,"<p>I keep getting this annoying warning when I run some of my unit tests on various components in my app:</p>

<pre><code>NativeModules.RNViewShot is undefined. Make sure the library is linked on the native side.
</code></pre>

<p>In my root dir, I run <code>'react-native link'</code> and I see this in the console:</p>

<pre><code>rnpm-install info Platform 'ios' module react-native-view-shot is already linked
rnpm-install info Platform 'android' module react-native-view-shot is already linked
rnpm-install info Linking assets to ios project
rnpm-install info Linking assets to android project
rnpm-install info Assets have been successfully linked to your project
</code></pre>

<p>What gives here > ?</p>

<pre><code>Platform: MacOS,
Editor: VSCode,
react: ""16.4.0"",
react-native: ""0.54.2"",
react-native-view-shot: ""^2.4.0"",
</code></pre>
",https://stackoverflow.com/questions/51363460/unit-testing-react-native-nativemodules-rnviewshot-is-undefined-make-sure-the,"['reactjs', 'react-native', 'jestjs']",1788,TRUE,5,1
Unit testing a method and getting Object reference not set to an instance of an object,"<p>I'm trying to write a unit test that calculates the total of an Order.  However, there is another method that is called from the CalculateOrder() method that I'm testing and my test keeps failing saying ""Object reference not set to an instance of an object.""</p>

<p>This is the CalculateOrder method I'm testing...</p>

<pre><code>public App_OrderForm CalculateOrder(App_OrderForm form)
{
    try
    {
        // Get the possible fees for the form group
        short? orderGroupId = form.Ref_OrderType == null
                                 ? GetOrderGroup(form.OrderTypeId)
                                 : form.Ref_OrderType.orderGroupId;

        Dictionary&lt;Ref_OrderType, List&lt;short&gt;&gt; fees = 
                           GetFeeTypeForOrderGroup((OrderGroup)orderGroupId);
</code></pre>

<p>It is the last line of code there that is creating the error.</p>

<p>This is my unit test...</p>

<pre><code>// Arrange
_mockUnitOfWork = new Mock&lt;IUnitOfWork&gt;();
_feeCalculator = new FeeCalculator(_mockUnitOfWork.Object);
App_OrderForm form = GenerateMockedForm(OrderFormType.Wholesaler);
form.Ref_OrderFormType = new Ref_OrderFormType
{
     OrderFormTypeId = 1,
     OrderGroupId = 1
};

foreach (var item in form.App_OrderFormItem)
{
    // add calculated fees
    item.App_OrderFormItemCalculatedFee = new List&lt;App_OrderFormItemCalculatedFee&gt;
    {
        new App_OrderFormItemCalculatedFee()
        {
            OrderFormItemCalculatedFeeId = 1,
            FeeTypeId = 1,
            Amount = 0.044M,
            NumberOfFees = 1
        },
    };
}

// Act
Mock&lt;IReferenceDataService&gt; rds = new Mock&lt;IReferenceDataService&gt;();
rds.Setup(x =&gt; x.GetAllPayableStatus())
  .Returns(new List&lt;Ref_Status&gt; {new Ref_Status() {StatusId = (short) Status.ReadyForPayment}});
_feeCalculator.CalculateForm(form, false);
</code></pre>

<p>Am I supposed to setup the method GetFeeTypeForOrderGroup()?  At the start of my unit test I've set up an Order Form and given the OrderGroupId a value so why doesn't the method GetFeeTypeForOrderGroup() not get run or why is it returning the error?</p>

<p>Hope that made sense,</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/51893536/unit-testing-a-method-and-getting-object-reference-not-set-to-an-instance-of-an,"['c#', 'unit-testing']",25,FALSE,0,0
Unit testing a controller using @WebMvcTest is not working when controller is dependent to request context,"<p>I am doing a unit test for my controller using <code>@WebMvcTest</code> in my unit test. My controller retrieves <code>RequestAttributes</code> data from <code>RequestContextHolder</code>: </p>

<pre><code>RequestContextHolder.currentRequestAttributes().getAttribute(name, RequestAttributes.SCOPE_REQUEST)
</code></pre>

<p>The data stored here is set in the interceptor:</p>

<pre><code>RequestAttributes reqAttr = RequestContextHolder.currentRequestAttributes();
reqAttr.setAttribute(name, value, RequestAttributes.SCOPE_REQUEST);
RequestContextHolder.setRequestAttributes(reqAttr, true);
</code></pre>

<p>In my controller unit test, the interceptor is not running so I tried to set the request attributes before running my test but I am getting this error:</p>

<blockquote>
  <p>java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.</p>
</blockquote>

<p>I have tried this answer <a href=""https://stackoverflow.com/a/9419859/5545327"">https://stackoverflow.com/a/9419859/5545327</a>. I added:</p>

<pre><code>@Mock
private RequestAttributes attrs;

@Before
public void before() {
    MockitoAnnotations.initMocks(this);
    RequestContextHolder.setRequestAttributes(attrs);
}

@Test
public void testController() {
    when(requestAttributes.getAttribute(eq(""&lt;attribute name&gt;""),
        eq(RequestAttributes.SCOPE_REQUEST))).thenReturn(&lt;mockReturn&gt;);
    // do your test...
}
</code></pre>

<p>But it is not working. The error is gone but the controller is getting <code>null</code> value from the <code>RequestContextHolder</code>. By the way I am testing my controller by doing this:</p>

<pre><code>mockMvc.perform(post(""&lt;url&gt;"").content(""&lt;post params here&gt;"")).andExpect(status().isOk());
</code></pre>

<p>where <code>mockMvc</code> is from <code>@WebMvcTest</code>.</p>

<p><strong>Note:</strong> I have a different class for integration test that is why I am using <code>@WebMvcTest</code> here instead of <code>@SpringBootTest</code></p>

<p>I am hoping you can give a descriptive answer since I am also quite new to Spring.</p>

<p>Thanks!</p>

<p>Edit:</p>

<ul>
<li>I can't simply put the data in the actual HttpRequest attribute. If I am not mistaken, the HttpRequest attributes are not automatically added as a request attribute in <code>RequestContextHolder</code>. Also, the data that I need is not from the HttpRequest but based on the HttpRequest. And I am mocking it since I know the actual request since this is my unit test.</li>
</ul>

<p>Code looks like this:</p>

<pre><code>@RunWith(SpringRunner.class)
@WebMvcTest
@OverrideAutoConfiguration(enabled = true)
@ActiveProfiles(""test"")
public abstract class BaseControllerTest {
    @Autowired
    protected MockMvc mockMvc;
}

public class ControllerTest extends BaseControllerTest {
    @Test
    public void testControllerMethod() {
        mockMvc.perform(post(""&lt;url&gt;"").content(""&lt;post params here&gt;"")).andExpect(status().isOk());
        // some more codes here
    }
}

public class Controller {
    @PostMapping
    public String controllerMethod() {
        // some more codes here
        Object myObject = RequestContextHolder.currentRequestAttributes().getAttribute(name, RequestAttributes.SCOPE_REQUEST);
        // some more codes here
    }
}
</code></pre>
",https://stackoverflow.com/questions/53955509/unit-testing-a-controller-using-webmvctest-is-not-working-when-controller-is-de,"['java', 'spring', 'unit-testing', 'spring-mvc', 'controller']",1349,FALSE,0,1
"Unit testing and multiple parameters to constructors in Asp.Net Core MVC, Passing token to every request","<p>I am trying to add one more parameter to my constructors in my Asp.Net Core MVC application, but facing some difficulties to do so. Here is what my implementation looks like. </p>

<p>Login action:</p>

<pre><code>[HttpPost, AllowAnonymous, ValidateAntiForgeryToken]
public IActionResult Login(LoginViewModel loginModel, string returnUrl = null)
{
   returnUrl = string.IsNullOrWhiteSpace(returnUrl) ? ApiConstants.Dashboard : returnUrl;
   ViewData[""ReturnUrl""] = returnUrl;
   if (!ModelState.IsValid) return View(loginModel);
   var token = Service.Login(loginModel);
   if (string.IsNullOrWhiteSpace(token)) return View(loginModel);
   TempData[""token""] = token;
   AddCookie(token);
   return RedirectToAction(""Index"", ""Dashboard"");
}

private void AddCookie(string token)
{
   HttpContext.Response.Cookies.Append(""token"", token,new CookieOptions()
   {
      Expires = DateTimeOffset.Now.AddDays(-1)
   });
}
</code></pre>

<p>Controller:</p>

<pre><code>private readonly INozzleService _nozzleService;
public NozzleController(INozzleService nozzleService)
{
  var token = HttpContext.Request.Cookies[""token""];
  _nozzleService = nozzleService;
}
</code></pre>

<p>Nozzle Service:</p>

<pre><code>private static INozzleAdapter Adapter { get; set; }
public NozzleService(INozzleAdapter adapter)
{
  Adapter = adapter;
}
</code></pre>

<p>Nozzle Adapter: </p>

<pre><code>private readonly string _token;
public NozzleAdapter(string token)
{
   _token = token;
}
</code></pre>

<p>Once I get the token in the adapter, I will be adding the token to the <code>HttpClient</code> header.</p>

<pre><code>client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(""Bearer"", _token);
</code></pre>

<p>ConfigureServices in Startup:</p>

<pre><code>public void ConfigureServices(IServiceCollection services)
{
   services.AddSingleton&lt;ITempDataProvider, CookieTempDataProvider&gt;();
   services.AddDistributedMemoryCache();
   services.AddSession();
   services.AddTransient&lt;IAccountService, AccountService&gt;();
   services.AddTransient&lt;IAccountAdapter, AccountAdapter&gt;();
   services.AddTransient&lt;INozzleService, NozzleService&gt;();
   services.AddTransient&lt;INozzleAdapter, NozzleAdapter&gt;();
   services.AddMvc();
}
</code></pre>

<p>Can you please let me know what could be the best way to achieve this in Asp.Net core 2.0 MVC application? I have read <a href=""https://stackoverflow.com/questions/32931716/asp-net-5-mvc-6-dependency-injection-with-multiple-constructors"">a post</a> saying that using multiple constructors is not a good idea in Asp.Net Core MVC application, so I don't want to use multiple constructors. </p>

<p>At the same time, I want to make sure all of my classes are unit testable with DI. What should be the best approach here? </p>

<p>Please let me know if anyone needs more information.</p>

<p><strong>Update:</strong> </p>

<p>As per Shyju's solution, I was able to implement the cookie, however, I am still in a  need to pass two parameters to one of my controllers.</p>

<pre><code>private readonly IAccountService _service;
private readonly ITokenProvider _tokenProvider;
public AccountController(IAccountService service, ITokenProvider tokenProvider)
{
  _service = service;
  _tokenProvider = tokenProvider;
}
</code></pre>

<p>So that I can, use the method AddToken as below.</p>

<pre><code>_tokenProvider.AddToken(token);
</code></pre>
",https://stackoverflow.com/questions/50427461/unit-testing-and-multiple-parameters-to-constructors-in-asp-net-core-mvc-passin,"['c#', 'unit-testing', 'asp.net-core', 'dependency-injection', 'asp.net-core-2.0']",1137,TRUE,0,1
How spy whether a function has been used or not with Jest unit testing for javascript?,"<p>When I try to set a spy on a imported function I get the following error msg <strong><em>TypeError: Cannot read property '_isMockFunction' of undefined</em></strong></p>

<p>I don't understand what it's wrong with this code</p>

<p>Imported function is like below here
export</p>

<pre><code>export
function myFn(){
    let htmlEl = document.querySelector('html');
    let el = document.querySelector('.target-el');
    if(el){
        el.addEventListener('click', myInternalFn, false);
    }

    function myInternalFn () {
        isUserLoggedIn((isIn) =&gt; {
            let logoutClassName = 'el--logout';
            if (isIn) {
                el.classList.remove(logoutClassName);
                return;
            } 
            el.classList.add(logoutClassName);
        });
    }

    function isUserLoggedIn (fn) {
        return fn(localStorage.getItem('userLoggedIn') === 'true');
    }
}

document.addEventListener('DOMContentLoaded', () =&gt; {
    myFn();
});
</code></pre>

<p>TDD:</p>

<pre><code>    import { betSlip } from ""../src/main/javascript/custom/betslip-dialog"";

    describe('Testing bet slip button (only on mobile)', function () {
         let htmlEl;
         let el;

         beforeEach(() =&gt; {
            document.body.innerHTML =
            `
            &lt;html&gt;
                &lt;div class=""target-el""&gt;&lt;/div&gt;
            &lt;/html&gt;
            `;

            myFn();
            htmlEl = document.querySelector('html');


        });

        it('When el button has been clicked for the first time', done =&gt; {
          jest.spyOn(myFn, 'myInternalFn');
          myInternalFn.click();
          expect(true).toBe(true);

          done();
        });

    });
</code></pre>
",https://stackoverflow.com/questions/48670861/how-spy-whether-a-function-has-been-used-or-not-with-jest-unit-testing-for-javas,"['javascript', 'tdd', 'jestjs', 'spyon']",477,TRUE,0,1
I want help to find all the defects in my java program by using unit testing,"<p>I want help in finding the number of defects in the below java piece by using unit testing.</p>

<p>I only found 3, but I want to make sure that I found all of them. I would really appreciate it if somebody could help me with this. Thank you.
Bellow are the comments about how this piece of code should work.</p>

<pre><code>// constructor
// Throws IllegalArgumentException if invalid value
// Exception message for invalid value: ""One or more of the parameters have invalid value""
// t parameter can only be upper case characters: E, D, A  
// n parameter must be a value between 10000 and 99999 inclusively
// p parameter must be greater than 0
// when all values are valid, assigns t to attribute type, n to attribute number and p to attribute price
</code></pre>

<p>Here is the script</p>

<pre><code>public Cars(char t, int n, int p)
{
    if (t != 'E' &amp;&amp; t != 'D' &amp;&amp; t != 'A')
        throw new NullPointerException(""One or more of the parameters have invalid value"");

    if (n &lt; 10000 || n &gt;= 99999)
        throw new IllegalArgumentException(""One parameter has invalid value"");

    if (p &lt;= 0)
        throw new IllegalArgumentException(""One or more of the parameters have invalid value"");

    type = t;
    number = n;
    price = p;
}
</code></pre>
",https://stackoverflow.com/questions/53292387/i-want-help-to-find-all-the-defects-in-my-java-program-by-using-unit-testing,"['java', 'eclipse', 'unit-testing']",129,TRUE,-1,1
I am new to unit testing and i&#39;d like to know why it is not working,"<p>I am new to MVC and to unit testing so I have been following guides etc.</p>

<p>At the moment I am looking at unit testing. I have a test which as far as I can see should work, but unfortunately does not.</p>

<pre><code>    using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using WorkingWithVisualStudio.Controllers.Home;
using WorkingWithVisualStudio.Models;
using Xunit;
namespace WorkingWithVisualStudio.Tests
{
    public class HomeControllerTests
    {
        class ModelCompleteFakeRepository : IRepository
        {
            public IEnumerable&lt;Product&gt; Products { get; } = new Product[] {
 new Product { Name = ""P1"", Price = 275M },
 new Product { Name = ""P2"", Price = 48.95M },
 new Product { Name = ""P3"", Price = 19.50M },
 new Product { Name = ""P3"", Price = 34.95M }};
            public void AddProduct(Product p)
            {
                // do nothing - not required for test
            }
        }
        [Fact]
        public void IndexActionModelIsComplete()
        {
            // Arrange
            var controller = new HomeController();
            controller.Repository = new ModelCompleteFakeRepository();

            // Act
            var model = (controller.Index() as ViewResult)?.ViewData.Model
            as IEnumerable&lt;Product&gt;;
            // Assert
            Assert.Equal(controller.Repository.Products, model,
            Comparer.Get&lt;Product&gt;((p1, p2) =&gt; p1.Name == p2.Name
            &amp;&amp; p1.Price == p2.Price));
        }
        class ModelCompleteFakeRepositoryPricesUnder50 : IRepository
        {
            public IEnumerable&lt;Product&gt; Products { get; } = new Product[] {
 new Product { Name = ""P1"", Price = 5M },
 new Product { Name = ""P2"", Price = 48.95M },
 new Product { Name = ""P3"", Price = 19.50M },
 new Product { Name = ""P3"", Price = 34.95M }};
            public void AddProduct(Product p)
            {
                // do nothing - not required for test
            }
        }
        [Fact]
        public void IndexActionModelIsCompletePricesUnder50()
        {
            // Arrange
            var controller = new HomeController();
            controller.Repository = new ModelCompleteFakeRepositoryPricesUnder50();
            // Act
            var model = (controller.Index() as ViewResult)?.ViewData.Model
            as IEnumerable&lt;Product&gt;;
            // Assert
            Assert.Equal(controller.Repository.Products, model,
            Comparer.Get&lt;Product&gt;((p1, p2) =&gt; p1.Name == p2.Name
            &amp;&amp; p1.Price == p2.Price));
        }
    }
}
</code></pre>

<p>When I run the IndexActionModelIsCompletePricesUnder50()
 I get the following:</p>

<pre><code>Message: Assert.Equal() Failure
Expected: Product[] [Product { Name = ""P1"", Price = 5 }, Product { Name = ""P2"", Price = 48.95 }, Product { Name = ""P3"", Price = 19.50 }, Product { Name = ""P3"", Price = 34.95 }]
Actual:   ValueCollection&lt;String, Product&gt; [Product { Name = ""Kayak"", Price = 275 }, Product { Name = ""Lifejacket"", Price = 48.95 }, Product { Name = ""Soccer ball"", Price = 19.50 }, Product { Name = ""Corner flag"", Price = 34.95 }]
</code></pre>

<p>My model is as follows:</p>

<pre><code>public class Product
    {
        public string Name { get; set; }
        public decimal Price { get; set; }
    }
</code></pre>

<p>My repository:</p>

<pre><code>public class SimpleRepository : IRepository
    {
        private static SimpleRepository sharedRepository = new SimpleRepository();
        private Dictionary&lt;string, Product&gt; products = new Dictionary&lt;string, Product&gt;();

        public static SimpleRepository SharedRepository =&gt; sharedRepository;

        public SimpleRepository()
        {
            var initialItems = new[]
            {
                new Product {Name = ""Kayak"", Price = 275M},
                new Product { Name = ""Lifejacket"", Price = 48.95M },
                new Product { Name = ""Soccer ball"", Price = 19.50M },
                new Product { Name = ""Corner flag"", Price = 34.95M }
            };
            foreach(var p in initialItems)
            {
                AddProduct(p);
            }
            //products.Add(""Error"", null);
        }

        public IEnumerable&lt;Product&gt; Products =&gt; products.Values;

        public void AddProduct(Product p) =&gt; products.Add(p.Name, p);
    }
</code></pre>

<p>My repository interface </p>

<pre><code>public interface IRepository
{
    IEnumerable&lt;Product&gt; Products { get; }
    void AddProduct(Product p);
}
</code></pre>

<p>My comparer:</p>

<pre><code>public class Comparer
{
    public static Comparer&lt;U&gt; Get&lt;U&gt;(Func&lt;U, U, bool&gt; func)
    {
        return new Comparer&lt;U&gt;(func);
    }
}
public class Comparer&lt;T&gt; : Comparer, IEqualityComparer&lt;T&gt;
{
    private Func&lt;T, T, bool&gt; comparisonFunction;

    public Comparer(Func&lt;T, T, bool&gt; func)
    {
        comparisonFunction = func;
    }

    public bool Equals(T x, T y)
    {
        return comparisonFunction(x, y);
    }

    public int GetHashCode(T obj)
    {
        return obj.GetHashCode();
    }
}
</code></pre>

<p>my controller:</p>

<pre><code>public class HomeController : Controller
{
    public IRepository Repository = SimpleRepository.SharedRepository;

    public IActionResult Index() =&gt; View(SimpleRepository.SharedRepository.Products);

    [HttpGet]
    public IActionResult AddProduct() =&gt; View(new Product());

    [HttpPost]
    public IActionResult AddProduct(Product p)
    {
        Repository.AddProduct(p);
        return RedirectToAction(""Index"");
    }
}
</code></pre>

<p>I am sorry if this seems like a stupid question but I have only just begun to look into unit testing. If someone could explain to me what the issue is I would definitely appreciate it. Thank you very much to those who take the time to lend a hand.</p>
",https://stackoverflow.com/questions/53501133/i-am-new-to-unit-testing-and-id-like-to-know-why-it-is-not-working,"['asp.net-mvc', 'unit-testing', 'xunit']",78,TRUE,0,2
How do I test interactions with private fields of a class with unit testing on java?,"<p><strong>I have the following class</strong>:</p>

<pre><code>public class BookProcessor {

    private Map&lt;String, Double&gt; bookToValueRecord = new HashMap&lt;&gt;();
    private Map&lt;String, Integer&gt; bookToCountRecord = new HashMap&lt;&gt;();
    private int counter = 0;

    public void processBook(Book book) {
        counter++;
        recordBook(book);
        if (counter % 5 == 0) {
            printSomeReport();
        } if (counter % 10 == 0) {
            printAnotherReport();
        }
    }

    private void printAnotherReport() {
       //just print something
    }


    private void printSomeReport() {
        //print something else here
    }

    private void recordBook(Book book) {
        bookToValueRecord.put(book.getTitle(), book.getValue());
        bookToCountRecord.put(book.getTitle(), bookToCountRecord.getOrDefault(book.getProduct(), 0)+book.getCount());
    }
}
</code></pre>

<p>My idea was to create a Test class <code>BookProcessorTest</code> with field <code>BookProcessor testee;</code> I dont know if I need to mock it or not? One of my tests will be <code>shouldProcessBook()</code>. In this test I will create a sample <code>Book</code> object, then I will call <code>testee.processBook(myBookObject)</code>, but then what should I assert or verify? Should I check if this record has been saved into <code>bookToValueRecord</code>? If yes, how, given that this is a <em>private field</em>?
Also, how to test that after saving 5 books into my <code>Map</code>, I am printing some report? Should I test that <code>printSomeReport()</code> has been called? If yes, how, given that <code>printSomeReport</code> is <em>private method</em>?</p>
",https://stackoverflow.com/questions/52015309/how-do-i-test-interactions-with-private-fields-of-a-class-with-unit-testing-on-j,"['java', 'unit-testing', 'testing', 'junit', 'mocking']",196,TRUE,0,1
Is there any way to use VS Code Debugger for Chrome inside Jasmine spec unit testing?,"<p>I'm trying to set breakpoints inside specific parts of my <em>specs</em> to have a detailed step by step view of processes not being reached by my tests.</p>

<p>I've tried using <strong>Debugger for Chrome</strong> VC Code's extension, but the debug process just doesn't seem to work.</p>

<p>The breakpoints look unavailable and the test run like they didn't exist.</p>

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

<p>Maybe is it something on my config? Am I doing something wrong? Or it just can't be done?</p>

<p>Jasmine-Karma is running on localhost:9876 and here is my 
 launch.json:</p>

<pre><code>{
  ""version"": ""0.2.0"",
  ""configurations"": [
    {
      ""type"": ""chrome"",
      ""request"": ""launch"",
      ""name"": ""Launch Chrome against localhost"",
      ""url"": ""http://localhost:9876"",
      ""webRoot"": ""${workspaceFolder}""
    }
  ]
}
</code></pre>

<p>Thank you!</p>
",https://stackoverflow.com/questions/53758987/is-there-any-way-to-use-vs-code-debugger-for-chrome-inside-jasmine-spec-unit-tes,"['angular', 'unit-testing', 'visual-studio-code', 'karma-jasmine', 'vscode-debugger']",115,FALSE,0,0
How to test child components input property values passed correctly or not in angular unit testing,"<p>I have a senario like based on JSON input component has  to dynamically render into the div/ ng template. </p>

<p>Each dynamic component will have some @input,  so will I test these @inputs passing correctly or not in unit testing.</p>

<p>This is the sample code:-
<a href=""https://i.stack.imgur.com/oFSm8.png"" rel=""nofollow noreferrer"">Sample Code Image</a></p>

<p>I was writing test case for this sample code snippet, How to check whether the input properties of the child component passed correctly or not, or at least I want to spy on these properties like how may times these properties has been calle (should we equal to ChildComponentCollection.length). is ther</p>
",https://stackoverflow.com/questions/53035408/how-to-test-child-components-input-property-values-passed-correctly-or-not-in-an,['angular'],120,FALSE,0,0
"How to check that during unit testing with ng-test, fdescribe() and fit() are never called?","<p>Simple scenario, angular, unit testing and continuous deployment.
What can happen is that a developer finishes the unit test related to a component. During development time the developer uses the functions <code>fdescribe()</code> or <code>fit()</code> just to run those specific tests.</p>

<p>In a moment of distraction the developer commits and pushes and deploy is done on production, but <code>fdescribe()</code> or <code>fit()</code> was forgotten in the code.</p>

<p>Tests are not failing, but this brings a bad scenario in, basically all the regular tests are not running, but the traffic-light says GO and all deploy is done.</p>

<p>Is it possible to check that in the all unit tests any <code>fdescribe()</code> or <code>fit()</code> are called?</p>
",https://stackoverflow.com/questions/50099789/how-to-check-that-during-unit-testing-with-ng-test-fdescribe-and-fit-are-ne,"['javascript', 'angular', 'unit-testing', 'deployment', 'describe']",276,TRUE,0,1
Angularjs1.6 unit testing ERROR: $scope is not defined and TypeError: Cannot read property &#39;setDescription&#39; of undefine,"<p>I testing my <code>angularjs 1.6.8</code> app with karma-jasmine. I have been constantly getting <code>$scope is not defined</code> and <code>TypeError: Cannot read property 'setDescription' of undefined</code></p>

<p>I have tried resolving them. did some googling. but no luck. Not sure, what I am doing wrong. </p>

<p>Below are the related codes.</p>

<p><code>app.js</code></p>

<pre><code>var app = angular.module('myApp', ['ui.router','pascalprecht.translate']);
app.config(['$stateProvider', '$urlRouterProvider','$translateProvider',function($stateProvider,$urlRouterProvider,$translateProvider){
    $urlRouterProvider.otherwise('/');

    $stateProvider
      .state('home', {
        url: '/home',
        templateUrl: 'home.html'
      })
      .state('dashboard', {
        url: '/dashboard',
        component: 'dashboardComponent'
      })
      .state('contact', {
        url: '/contact',
        component: 'contactComponent'
      })
      .state('about', {
        url: '/about',
        component: 'aboutComponent'
      })
      .state('sassSite', {
        url: '/sassSite',
        templateUrl: 'sassSite.html'
      })

      $translateProvider.preferredLanguage(navigator.language);
      $translateProvider.registerAvailableLanguageKeys(['en','fr','hi'],{
        'en-*':'en',
        'fr-*':'fr',
        'hi-*':'hi'
      });
      $translateProvider.useStaticFilesLoader({
          prefix:'i18n/',
          suffix:'.json'
      });
      $translateProvider.useSanitizeValueStrategy(null);
}]);

app.controller('mainCtrl',['$scope','$translate',function($scope, $translate){
  $scope.changeLanguage = function(lang){
    $translate.use(lang);
  }
}]);

app.service('contactService',function(){
});
</code></pre>

<p><code>karma.conf.js</code></p>

<pre><code>// Karma configuration
// Generated on Sun Feb 11 2018 13:41:44 GMT+0530 (India Standard Time)

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: [

      'src/scripts/angular.js',
      'src/scripts/angular-mocks.js',      

      'src/scripts/angular-route.js',
      'src/scripts/angular-ui-router.js',

      'src/scripts/app.js',

      'src/components/contact/contact.component.js',
      'src/components/contact/contact.service.js',
      'src/unitest.spec.js',
    ],


    // list of files / patterns 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: ['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><code>unit.spec.js</code></p>

<pre><code>describe('Controller', function() {
    // beforeEach(module('myApp'));

    beforeEach(function(){
        module('myApp');
        angular.module('ui.router',[]);


        angular.module('pascalprecht.translate',[]);



      });

    describe('contactController',function(){
        var contactController;
        beforeEach(inject(function($controller){
            contactController = $controller('contactController');
        }));
        it('should submit user details', function(){
            contactController.setDescription('nauman');
            expect(contactController.description).toBe(string);
            contactController.setDescription('ntanwir10@gmail.com');
            expect(contactController.description).toBe(string);
            contactController.setDescription('too hot bruh!');
            expect(contactController.description).toBe(string);
        });
    });
});
</code></pre>

<p><strong>UPDATE</strong></p>

<p>so I modified my <code>unit.spec.js</code> </p>

<pre><code>describe('Controller', function() {
    beforeEach(function(){
        angular.module('myApp', ['ui.router', 'stateProvider','pascalprecht.translate' ] );
      });

    describe('contactController',function(){
        var contactController;
        beforeEach(inject(function($controller){
            contactController = $controller('contactController',{$scope: $scope});
        }));
        it('should submit user details', function(){
            contactController.setDescription('nauman');
            expect(contactController.description).toBe(string);
            contactController.setDescription('ntanwir10@gmail.com');
            expect(contactController.description).toBe(string);
            contactController.setDescription('too hot bruh!');
            expect(contactController.description).toBe(string);
        });
    });
});
</code></pre>

<p>and now I getting the below errors(check screenshot):</p>

<p><a href=""https://i.stack.imgur.com/yIrnk.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/yIrnk.png"" alt=""updated screenshot""></a></p>
",https://stackoverflow.com/questions/48740097/angularjs1-6-unit-testing-error-scope-is-not-defined-and-typeerror-cannot-rea,"['angularjs', 'unit-testing', 'karma-runner', 'karma-jasmine', 'angularjs-1.6']",189,FALSE,0,1
How to simulate time delay (timeout) when mocking method calls in unit testing with proxyquire and mocha?,"<p>Using  proxyquire I'm mocking a method of module B (injected with require() in module A), when testing the method in the module A. The mock (mocking get_campaigns method of admitad.model.js module):</p>
<pre class=""lang-js prettyprint-override""><code>const admitadModelMock = {
    '../services/admitad.model': {
        get_campaigns: (limit, page) =&gt; new Promise((resolve, reject) =&gt;
            setTimeout(resolve({campaigns: testData, count: 1000}), 5000)
        ),
    },
};
</code></pre>
<p>The test:</p>
<pre class=""lang-js prettyprint-override""><code>it('shold get all campaigns from Admitad', async function () {
    this.timeout(60000);
    let err, data;
    // mock dependencie (get_campaigns() of module B will be mocked):
    let $serviceStubbed = proxyquire('../services/campaign-sync', admitadModelMock);
    // getAdmitadCampaigns() just calls get_campaigns method of module B
    [err, data] = await to($serviceStubbed.getAdmitadCampaigns(50));
    data.length.should.be.equal(50);
});
</code></pre>
<p>The problem is the test passing without expected delay of 5 seconds.</p>
<p><strong>Update.</strong></p>
<p>This is working:</p>
<pre><code>setTimeout(() =&gt; resolve({campaigns: mockedCampaigns, count: 1000}), 2000)
</code></pre>
<p>Here is my final nice approach:</p>
<pre class=""lang-js prettyprint-override""><code>// helper to wrap timeout generation
const timer = (data, time) =&gt;
    new Promise((resolve, reject) =&gt;
        setTimeout(() =&gt; resolve(data), time)
    );

// Factory function to generate mock with data we need
const blacklistedModelMockFactory =
    (onRead = [], onUpdate = 'Ok', onCreate = 'Ok', onDelete = 'Ok') =&gt; ({
        '../services/campaigns-blacklist.model': {
            read: () =&gt; timer(onRead, 2000),
            update: () =&gt; timer(onUpdate, 2000),
            create: () =&gt; timer(onCreate, 1000),
            delete: () =&gt; timer(onDelete, 1000),
        },
    });

// Test example
it('should filter Registered and Blacklisted collections', async function () {
    this.timeout(60000);
    $service.should.have.property('filterRB').a('function');
    const sourceRegistered = mockedCampaigns.slice(5, 10);
    const sourceBlacklisted = mockedCampaigns.slice(15, 18);
    let error, success;
    // mock dependencies in tested module with our expected data:
    let $serviceStubbed = proxyquire(
        '../services/campaign-sync', Object.assign(
            {},
            blacklistedModelMockFactory(sourceBlacklisted),
            registeredModelMockFactory(sourceRegistered)
        )
    );
    [error, success] = await to($serviceStubbed.filterRB(mockedCampaigns));
    expect(error).to.be.equal(null);
    success.filtered.length.should.be.equal(12);
    success.blacklisted.length.should.be.equal(3);
    success.registered.length.should.be.equal(5);
});
</code></pre>
",https://stackoverflow.com/questions/48823073/how-to-simulate-time-delay-timeout-when-mocking-method-calls-in-unit-testing-w,"['node.js', 'mocha.js', 'proxyquire']",9828,TRUE,3,1
What should I pass to controller in order to perform model unit testing in ASP.NET Core 2.0,"<p>How to perform model unit testing in .net core 2.0? I am not getting what to pass to Homecontroller class in unit testing class. This is my unit testing class where I need help</p>

<p><img src=""https://i.stack.imgur.com/UPki2.png"" alt=""enter image description here""></p>

<pre><code>using BasicUnitTesting.Models;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using BasicUnitTesting.Controllers;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;

namespace BasicUnitTestProj
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void GetEmployeeTest()
        {
            HomeController home = new HomeController(null); //What should i pass to HomeController

            var vr = home.GetEmployee() as ViewResult;

            List&lt;Employee&gt; expectedemps = new List&lt;Employee&gt;()
            {
                new Employee() {EmpID=101,EmpName=""Abhilash"",Salary=50000},
                new Employee() {EmpID=102,EmpName=""Abhishek"",Salary=60000},
                new Employee() {EmpID=103,EmpName=""Nagraj"",Salary=30000},
                new Employee() {EmpID=104,EmpName=""Sunil"",Salary=50000},
                new Employee() {EmpID=105,EmpName=""Vinay"",Salary=40000}
            };

            Assert.IsTrue(expectedemps.SequenceEqual(vr.Model as List&lt;Employee&gt;));
        }
    }
}
</code></pre>

<p>Below is my Homecontroller</p>

<pre><code>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using BasicUnitTesting.Models;

namespace BasicUnitTesting.Controllers
{
    public class HomeController : Controller
    {
        private readonly CompanyDbContext _context

        public HomeController(CompanyDbContext context)
        {
            _context = context;
        }

        public IActionResult Index()
        {
            return View(""Index"");
        }

        public IActionResult GetEmployee()
        {
            //CompanyDbContext Db = new CompanyDbContext();
            //List&lt;Employee&gt; emps = Db.Employees.ToList();
            List&lt;Employee&gt; emps = _context.Employees.ToList();
            return View(emps);
        }         
    }
}
</code></pre>

<p>My model and Context class are as follows:</p>

<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;

namespace BasicUnitTesting.Models
{
    public class Employee
    {
        [Key]
        public int EmpID { get; set; }
        public string EmpName { get; set; }
        public decimal Salary { get; set; }
    }

    public class CompanyDbContext:DbContext
    {
        public CompanyDbContext()
        {
        }

        public CompanyDbContext(DbContextOptions&lt;CompanyDbContext&gt; options) : base(options)
        {
        }

        public DbSet&lt;Employee&gt; Employees { get; set; }
    }
}
</code></pre>
",https://stackoverflow.com/questions/52090958/what-should-i-pass-to-controller-in-order-to-perform-model-unit-testing-in-asp-n,"['c#', 'unit-testing', 'asp.net-core', 'asp.net-core-2.0']",194,TRUE,1,1
Angular 5: How do I deal with the dependencies of the dependencies of a component while unit testing?,"<p>I'm new to unit testing in the context of an Angular 5 application.
And right now, I'm trying to unit test a basic component.  </p>

<p>The component is called CardComponent, and within the HTML of this component, I call the CheckboxComponent.<br>
So here's the HTML of the CardComponent:  </p>

<pre><code>&lt;div&gt;
    &lt;p&gt;Test&lt;/p&gt;
    &lt;jg-checkbox [label]=""'Test label'""&gt;&lt;/jg-checkbox&gt;
&lt;/div&gt;
</code></pre>

<p>As you can see, there's nothing complicated going on.  </p>

<p>However, the CheckboxComponent does inject a service. For the sake of this question, I'll just call it TestService.  </p>

<p>So when I unit test my CardComponent, here's my testbed:</p>

<pre><code>TestBed.configureTestingModule({
    declarations: [
        CheckboxComponent
    ]
}).compileComponents();
</code></pre>

<p>Then I run this test:  </p>

<pre><code>it('should create', () =&gt; {
    expect(component).toBeTruthy();
});
</code></pre>

<p>This is just the default test that gets created through the CLI.   </p>

<p>But now, it complains that there's no provider for the TestService. Am I really supposed to inject (and mock/spy) that as well?  </p>

<p>That seems a bit backwards because I only care about the CardComponent, I shouldn't have to care about the CheckboxComponent, right? That's the whole point of unit testing.   </p>

<p>Otherwise, since Angular has hierarchical components, I might have to go down many levels deep as my app grows. </p>

<p>This can't be right.  </p>

<p>Can someone please help with this issue? I appreciate the help!</p>
",https://stackoverflow.com/questions/49804928/angular-5-how-do-i-deal-with-the-dependencies-of-the-dependencies-of-a-componen,"['angular', 'unit-testing']",1166,TRUE,6,3
Unit testing angular4 component - test gives error when component function is called and component property is used,"<p>Below is my component's HTML:</p>

<p>list-comments.component.html</p>

<pre><code>&lt;div class=""container""&gt;

    &lt;div class=""row listCommentsContainer""&gt;
      &lt;h2&gt;Best Of Books&lt;/h2&gt;
        &lt;div class=""col-lg-8 col-sm-8"" *ngFor=""let commentData of commentsData; let i = index""&gt;
          &lt;ol style=""list-style: none;""&gt;
          &lt;li class=""listComments""&gt;

            &lt;div  style=""display: block""&gt;
            &lt;div style=""display:inline-block;""&gt;
              &lt;a class=""avatar""&gt;

                &lt;img style="""" src=""{{commentData.profile_image}}""&gt;
              &lt;/a&gt;
            &lt;/div&gt;
            &lt;a class=""commentPostByUserName""&gt;
              &lt;span class=""commentPostByUserName"" style=""""&gt;{{commentData.first_name}}&lt;/span&gt;
            &lt;/a&gt;
              &lt;div class=""commentTime""&gt;{{commentData.time_stamp}}&lt;/div&gt;
            &lt;/div&gt;
            &lt;div class=""commentTextDisplay""&gt;{{commentData.object}}&lt;/div&gt;

            &lt;br&gt;

            &lt;!-- Click Reply --&gt;
            &lt;div class=""addReplyContainer"" #commentData.id&gt;
              &lt;a  class=""addReplyLink""  (click)=""showReplyTextArea($event, commentData.id)""&gt;Reply&lt;/a&gt;
            &lt;/div&gt;

            &lt;!-- Add Reply --&gt;
            &lt;div [attr.commentId]=""commentData.id"" class=""addReplyContainer replyTextAreaContainer"" style=""display: none"" &gt;
              &lt;textarea (keyup)=""keyUpCommentTextarea($event, reply, commentData.id)"" [(ngModel)]=""reply"" style=""width:100%""
                        class=""replyText commentText addReplyTextarea form-control""&gt;&lt;/textarea&gt;
              &lt;button [attr.commentId]=""commentData.id"" disabled class=""btn btn-success addCommentBtn"" (click)=""addReply($event, commentData.target_id)""&gt;Add&lt;/button&gt;
            &lt;/div&gt;
            &lt;!-- -----Add Reply end------ --&gt;

            &lt;!-- List Replies --&gt;
            &lt;div class=""replies col-lg-8 col-sm-8"" *ngFor=""let reply of commentData.comment""&gt;
              &lt;ol style=""list-style: none;""&gt;
                &lt;li class=""listComments listReplies""&gt;

                  &lt;div  style=""display: block""&gt;
                    &lt;div style=""display:inline-block;""&gt;
                      &lt;a class=""avatar""&gt;

                        &lt;img style="""" src=""{{reply.profile_image}}""&gt;
                      &lt;/a&gt;
                    &lt;/div&gt;
                    &lt;a class=""commentPostByUserName""&gt;
                      &lt;span class=""commentPostByUserName"" style=""""&gt;{{reply.first_name}}&lt;/span&gt;
                    &lt;/a&gt;

                  &lt;/div&gt;
                  &lt;div class=""commentTextDisplay replyTextDisplay""&gt;{{reply.object}}&lt;/div&gt;
                &lt;/li&gt;
              &lt;/ol&gt;
            &lt;/div&gt;
            &lt;!-- -------list reply end-------- --&gt;

          &lt;/li&gt;
          &lt;/ol&gt;
        &lt;/div&gt;

    &lt;/div&gt;

    &lt;!-- Add Comment--&gt;
    &lt;div class=""row""&gt;
      &lt;div  class=""addCommentContainer col-lg-6 col-sm-12""&gt;

          &lt;textarea (keyup)=""keyUpCommentTextarea($event, comment)""
                    [(ngModel)]=""comment"" class=""commentText form-control""
                    placeholder=""Add Comment""&gt;
          &lt;/textarea&gt;
        &lt;button  disabled (click)=""addComment($event)"" class=""btn addCommentBtn btn-success""&gt;Add&lt;/button&gt;

      &lt;/div&gt;
    &lt;/div&gt;
  &lt;!-- Add Comment end--&gt;
&lt;/div&gt;
</code></pre>

<p>This is my spec file:</p>

<p>list-comments.component.spec.ts:</p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ListCommentsComponent } from './list-comments.component';
import {DebugElement} from ""@angular/core"";
import 'reflect-metadata';
import { Component } from  ""@angular/core"";
import {By} from ""@angular/platform-browser"";
import { FormsModule } from '@angular/forms';
import { HttpClientModule, HttpClient } from '@angular/common/http';
// require('zone.js');
// let chai = require('chai') ,
// spies = require('chai-spies');
// chai.use(spies);


describe('ListCommentsComponent', () =&gt; {
  let component: ListCommentsComponent;
  let fixture: ComponentFixture&lt;ListCommentsComponent&gt;;
  let debugElement:DebugElement;
  let htmlElement:HTMLElement;



  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [ FormsModule, HttpClientModule],
      declarations: [ ListCommentsComponent ],
     // providers:[HttpClientModule, HttpClient]
    })
    .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(ListCommentsComponent);
    component = fixture.componentInstance;

    fixture.detectChanges();


  });



  fit('should be disabled', () =&gt; {

    debugElement = fixture.debugElement.query(By.css('button.addCommentBtn'));
    htmlElement =debugElement.nativeElement;
    expect(htmlElement.getAttribute('disabled')).toEqual('disabled');
  });

});
</code></pre>

<p>In my test above I just want to check If I button has property disabled.</p>

<p>Let me know If this is not right way to check button's disabled property on page load.</p>

<p>Thanks in advance.</p>

<p><strong>*Edit</strong></p>

<p>After searching for few hours I have figure out that my problem of accessing debugElement attribute can be solved using jQuery.
So instead of using debugElement I used $ and it worked completely fine.</p>

<p>I have modified my spec file to:</p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ListCommentsComponent } from './list-comments.component';
import {DebugElement} from ""@angular/core"";
import 'reflect-metadata';
import { Component } from  ""@angular/core"";
import {By} from ""@angular/platform-browser"";
import { FormsModule } from '@angular/forms';
import { HttpClientModule, HttpClient } from '@angular/common/http';
 import * as $ from 'jquery';
// require('zone.js');
// let chai = require('chai') ,
// spies = require('chai-spies');
// chai.use(spies);


describe('ListCommentsComponent', () =&gt; {
  let component: ListCommentsComponent;
  let fixture: ComponentFixture&lt;ListCommentsComponent&gt;;
  let debugElement:DebugElement;
  let htmlElement:HTMLElement;




  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [ FormsModule, HttpClientModule],
      declarations: [ ListCommentsComponent ],
     // providers:[HttpClientModule, HttpClient]
    })
    .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(ListCommentsComponent);
    component = fixture.componentInstance;

    fixture.detectChanges();


  });



  fit('should not be disabled when we add message', () =&gt; {

    component.keyUpCommentTextarea(""hello"", null);


      let addCommentBtn = $('button.addCommentBtn').attr('disabled');

    debugElement = fixture.debugElement.query(By.css('button.addCommentBtn'));

    expect(addCommentBtn).toEqual(undefined);
  });


  fit('should  be disabled when we do not add message', () =&gt; {

    component.keyUpCommentTextarea("""", null);


    let addCommentBtn = $('button.addCommentBtn').attr('disabled');



    expect(addCommentBtn).toEqual('disabled');
  });


  fit('should match array',  () =&gt; {

    let commentsJson = {
      root_id:""1"",
      target_id: 1,
      text: ""hi"",
      comment_posted_by:""Jack"",
      comment_posted_by_image:""/../../assets/images/no-user.png"",
      profile_image:""/../../assets/images/no-user.png"",
      first_name : ""john""
    };

    component.addComment();

    expect(commentsJson).toEqual(component.commentObj);

  });



  it('should be string',  () =&gt; {

    component.addComment();
    expect(component.comment).toBe('string');

  });


});
</code></pre>

<p>In my last test I called a <em>function</em> <strong>addComment</strong> and it involves <strong>this.comment</strong> and <strong>this.commentObj</strong> properties of <strong>list-comment component</strong> when code reaches a line where this.comment is accessed I get </p>

<blockquote>
  <p>TypeError: Cannot read property 'trim' of undefined</p>
</blockquote>

<p>What is wrong with my code?</p>
",https://stackoverflow.com/questions/49788952/unit-testing-angular4-component-test-gives-error-when-component-function-is-ca,"['angular', 'jasmine', 'angular-components']",227,FALSE,0,0
Redux Saga Unit Testing with jest: How to sustain the object received by take in the test?,"<p>I'm new to Unit testing, Redux and Redux Saga. I use it with React Native. I just implemented my <code>loginFlow</code> just like the one described in the <a href=""https://redux-saga.js.org/docs/advanced/NonBlockingCalls.html"" rel=""nofollow noreferrer"">docs of Redux Saga</a>:</p>

<pre><code>function* loginFlow() {
  while (true) {
    const {user, password} = yield take('LOGIN_REQUEST')
    // fork return a Task object
    const task = yield fork(authorize, user, password)
    const action = yield take(['LOGOUT', 'LOGIN_ERROR'])
    if (action.type === 'LOGOUT')
      yield cancel(task)
    yield call(Api.clearItem, 'token')
  }
}

function* authorize(user, password) {
  try {
    const token = yield call(Api.authorize, user, password)
    yield put({type: 'LOGIN_SUCCESS', token})
    yield call(Api.storeItem, {token})
    return token
  } catch(error) {
    yield put({type: 'LOGIN_ERROR', error})
  } finally {
    if (yield cancelled()) {
      // ... put special cancellation handling code here
    }
  }
}
</code></pre>

<p>I'm now trying to write tests for this Auth flow. Unfortunately iI can't figure out how to give the test for the <code>*loginFlow</code> generator the email and the password. Here is where I'm currently at:</p>

<pre><code>describe(""login flow"", () =&gt; {
  const gen = loginFlow();
  const user = ""test@test.test"";
  const password = ""testpassword"";

  it(""should wait for a user to log in"", () =&gt; {
    expect(gen.next({ user, password }).value).toEqual(take(LOGIN_REQUEST));
  });

  it(""should fork the handling of the login request"", () =&gt; {
    const expectedYield = fork(authorize, user, password);
    expect(gen.next().value).toEqual(expectedYield);
  });
});
</code></pre>

<p>The problem is, that this throws the error: </p>

<pre><code>● login flow › should fork the handling of the login request

    TypeError: Cannot read property 'email' of undefined

      28 | export function* loginFlow() {
      29 |   while (true) {
    &gt; 30 |     const { email, password } = yield take(LOGIN_REQUEST);

         |             ^
      31 |     // fork return a task object
      32 |     const task = yield fork(authorize, email, password);
      33 |     const action = yield take([LOGOUT, LOGIN_ERROR]);
</code></pre>

<p>As you can see I tried to give these values to the yield keyword by supplying them in the next call, but it just won't work.</p>
",https://stackoverflow.com/questions/51231309/redux-saga-unit-testing-with-jest-how-to-sustain-the-object-received-by-take-in,"['unit-testing', 'redux', 'jestjs', 'redux-saga', 'redux-saga-test-plan']",2286,TRUE,0,1
"NodeJS Unit testing with Mocha, Chai and Sinon failing with results from previous test not being restored","<p>In a fairly new project assigned to me where some code along with the test cases were already written, some existing test cases have suddenly started to fail unexpectedly with the stubs not being restored correctly.</p>

<p>The beforeEach and afterEach hooks of the test suite is as follows : </p>

<pre><code>var getTokenStub, paramDescStub, getDataStub, getCaseDesiredAction;

beforeEach(function () {
    getCaseDesiredAction = sinon.stub(pgUtils, 'getCaseDesiredAction');
    getDataStub = sinon.stub(apiCall, 'getData');
    getTokenStub = sinon.stub(apiCall, 'getToken');
    paramDescStub = sinon.stub(paramDesc, 'getParameterDescriptionForCode')
});

afterEach(function () {
    pgUtils.getCaseDesiredAction.restore();
    apiCall.getData.restore();
    apiCall.getToken.restore();
    paramDesc.getParameterDescriptionForCode.restore();
});
....
</code></pre>

<p>This is followed by a few test cases which checks for errors. </p>

<p><strong>This should Pass with an error response</strong></p>

<pre><code> ....
 it('should respond with error if query fails', (function (done) {
    var req = {
        query: {caseId: '12345'},
    };
    getTokenStub.yields(200, '""Token""');
    getDataStub.yields(200, sampleDetailsResponse);
    getCaseDesiredAction.yields('error', null);
    getCaseDetails(req, res);
    res.response.errorCode.should.equal(1234);
    res.response.msg.should.equal('caseDetailsResult Failed while getting desired action: error');
    done();
}));
....
</code></pre>

<p>The problem is that even the next test case fails with the same errors as with the previous ones. For eg:- The next case too fails with the error <code>'caseDetailsResult Failed while getting desired action: error'</code> even though all the inputs for it are correct. If I comment out the test cases which check for erroneous inputs/states, the next cases work properly. </p>

<p><strong>This should Pass with a success response (But it fails with the same error from the previous test case)</strong></p>

<pre><code> it('should respond with case details', (function (done) {
    var req = {
        query: {caseId: '12345'},
        session: {
            ""authenticatedUser"": {userId: ""999999999""}
        }
    };
    getTokenStub.yields(200, '""Token""');
    getCaseDesiredAction.yields(null, [{desiredaction: 'Close'}]);
    paramDescStub.yields('TEST CODE');
    getDataStub.yields(200, sampleDetailsResponse);
    getCaseDetails(req, res);
    res.response.should.eql({
        caseDetails:
            {
             ....  
            }
        success: 'true'
    });
    done();
}));
</code></pre>

<p>I am all at sea trying to find what is going wrong here. There are other files following the same format but they are not failing. Can someone kindly help me find out the issue with this?</p>

<p>NOTE : One thing to note here is that recently we added an async.map function into the original file. </p>

<p><strong>UPDATE : Here is the complete code snippet for the spec</strong></p>

<pre><code>describe('getCaseDetails', function () {
  var res = {
      response: {},
      send: function (values) {
        this.response = values;
      }
  };

  var getCaseDesiredAction;
  var getDataStub;
  var getTokenStub, paramDescStub;

  beforeEach(function () {
      getCaseDesiredAction = sinon.stub(pgUtils, 'getCaseDesiredAction');
      getDataStub = sinon.stub(apiCall, 'getData');
      getTokenStub = sinon.stub(apiCall, 'getToken');
      paramDescStub = sinon.stub(paramDesc, 'getParameterDescriptionForCode')
  });

  afterEach(function () {
      pgUtils.getCaseDesiredAction.restore();
      apiCall.getData.restore();
      apiCall.getToken.restore();
      paramDesc.getParameterDescriptionForCode.restore();
  });

  // passes with error response invalid input
  it('should return an error if an input is missing', function (done) {
      var req = {
          query: {},
          session: {}
      };
      getCaseDetails(req, res);
      res.response.msg.should.equal(""Invalid input"");
      done();
  });

  ....

  ....
  // passes with error response 'Failed while getting desired action'
  it('should respond with error if query fails', (function (done) {
      var req = {
          query: {caseId: '12345'},
      };
      getTokenStub.yields(200, '""Token""');
      getDataStub.yields(200, sampleDetailsResponse);
      getCaseDesiredAction.yields('error', null);
      getCaseDetails(req, res);
      res.response.errorCode.should.equal(1234);
      res.response.msg.should.equal('caseDetailsResult Failed while getting desired action: error');
      done();
  }));

  ....
  ....

  it('should respond with case details', (function (done) {
      var req = {
          query: {caseId: '12345'},
          session: {
              ""authenticatedUser"": {userId: ""999999999""}
          }
      };
      getTokenStub.yields(200, '""Token""');
      getCaseDesiredAction.yields(null, [{desiredaction: 'Close'}]);
      paramDescStub.yields('TEST CODE');
      getDataStub.yields(200, sampleDetailsResponse);
      getCaseDetails(req, res);
      res.response.should.eql({
          caseDetails:
              {
               ....  
              }
          success: 'true'
      });
      done();
  }));
});
</code></pre>
",https://stackoverflow.com/questions/49661710/nodejs-unit-testing-with-mocha-chai-and-sinon-failing-with-results-from-previou,"['node.js', 'unit-testing', 'mocha.js', 'sinon', 'chai']",333,FALSE,0,1
Jest did not exit one second after the test run has completed using express,"<p>I'm using JEST for unit testing my express routes.</p>

<p>While running the <code>yarn test</code> all my test case are getting passed, but I'm getting an error </p>

<pre><code>Jest did not exit one second after the test run has completed.

This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with `--detectOpenHandles` to troubleshoot this issue.
</code></pre>

<p>I used <code>async</code> &amp; <code>done</code>, but still it throws the above error. </p>

<p>Below is my spec code. Please help</p>

<p><strong>routes.spec.ts</strong></p>

<pre><code>const request = require('supertest');
describe('Test the root path', () =&gt; {
  const app = require('./index');

  test('GET /gql/gql-communication-portal/release-notes', async (done) =&gt; {
    const response = await request(app).get('/gql/gql-communication-portal/release-notes');
    expect(response.status).toBe(200);
    done();
  });
});
</code></pre>
",https://stackoverflow.com/questions/53935108/jest-did-not-exit-one-second-after-the-test-run-has-completed-using-express,"['typescript', 'unit-testing', 'express', 'jestjs']",106692,TRUE,90,12
Access variables and lists from function,"<p>I am new to unit testing with Python. I would like to test some functions in my code. In particular I need to test if the outputs have specific dimensions or the same dimensions. </p>

<p>My Python script for unit testing looks like this:</p>

<pre><code>import unittest
from func import *

class myTests(unittest.TestCase):

def setUp(self):
    # I am not really sure whats the purpose of this function

def test_main(self):
    # check if outputs of the function ""main"" are not empty:
    self.assertTrue(main, msg = 'The main() function provides no return values!')

    # check if ""run['l_modeloutputs']"" and ""run['l_modeloutputs']"", within the main() function have the same size:
    self.assertCountEqual(self, run['l_modeloutputs'], run['l_dataoutputs'], msg=None)  
    # --&gt; Doesn't work so far!

    # check if the dimensions of ""props['k_iso']"", within the main() function are (80,40,100):

def tearDown(self):
    # I am also not sure of the purpose of this function

if _name__ == ""__main__"": 
    unittest.main()
</code></pre>

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

<pre><code>def main(param_file):
    # Load parameter file
    run, model, sequences, hydraulics, flowtrans, elements, mg = hu.model_setup(param_file)

    # some other code   
    ...   

    if 'l_modeloutputs' in run:
        if hydraulics['flag_gen'] is False:
            print('No hydraulic parameters generated. No model outputs saved')
        else:
            save_models(realdir, realname, mg, run['l_modeloutputs'], flowtrans, props['k_iso'], props['ktensors'])
</code></pre>

<p>I need to access the parameters <code>run['l_modeloutputs']</code> and <code>run['l_dataoutputs']</code> of the <code>main</code> function from <code>func.py</code>. How can I pass the dimensions of these parameters to the unit testing script?</p>
",https://stackoverflow.com/questions/48842832/access-variables-and-lists-from-function,"['python', 'python-3.x', 'unit-testing']",75,FALSE,0,1
How can i mock a LUIS api call in unit testing of Bot framework . If i calling it through Root Dialog,"<p>How can i mock a LUIS api call in unit testing of Bot framework . If i calling it through  Root Dialog. From unit testing we are directly calling RootDialog. Please help me to mock the LUIS api call in BOT code.</p>
",https://stackoverflow.com/questions/51477115/how-can-i-mock-a-luis-api-call-in-unit-testing-of-bot-framework-if-i-calling-i,['botframework'],124,FALSE,0,0
Best way to unit test an API call that hits the application when running,"<p>Right now we are working on building a custom CMS but I am running into a roadblock where I can't quite figure out the best approach with a piece of it to allow for good unit testing. </p>

<p>Our process is as follows: </p>

<p>The request comes in --> Parse the page for components --> Found component --> Hit the component API to get the component content</p>

<p>The only issue is when unit testing we hit the local URL for the app, which won't work since the app isn't fully running when running tests.</p>

<p>Component Rendering Code:</p>

<pre><code>var componentBody = await httpClient
            .GetStringAsync(""http://localhost:5001/Api/Components/"" + ComponentName + ""/View/"" + ComponentId);
ComponentStructure componentStructure = this.ParseHtml(componentBody);
</code></pre>

<p>Unit Testing Code:</p>

<pre><code>public async Task TestPageParsing()
    {
        this.pagesClient = this.clientManager.GetClient&lt;Page, PageData&gt;(""pages"");
        var pages = await this.pagesClient.GetAsync();
        this.pageParsingService.FindComponents(pages.Items[0].Data.Text);
    }
</code></pre>
",https://stackoverflow.com/questions/51731165/best-way-to-unit-test-an-api-call-that-hits-the-application-when-running,"['c#', 'unit-testing', '.net-core']",1001,TRUE,2,2
Unit Test HttpClient - Angular/Karma,"<p>I am going through some articles on unit testing and have found some pretty helpful examples. Most examples I am running across seem to be unit testing a function that does something with the Angular <code>HttpClient</code> and most look like this:</p>

<pre><code>it('should return an Observable&lt;User[]&gt;', () =&gt; {
    const dummyUsers = [
      { login: 'John' },
      { login: 'Doe' }
    ];

    service.getUsers().subscribe(users =&gt; {
      expect(users.length).toBe(2);
      expect(users).toEqual(dummyUsers);
    });

    const req = httpMock.expectOne(`${service.API_URL}/users`);
    expect(req.request.method).toBe(""GET"");
    req.flush(dummyUsers);
  });
</code></pre>

<p><a href=""https://medium.com/netscape/testing-with-the-angular-httpclient-api-648203820712"" rel=""nofollow noreferrer"">https://medium.com/netscape/testing-with-the-angular-httpclient-api-648203820712</a></p>

<p>This means that <code>.getUsers()</code> returns an observable. However, in my application, I am not returning an observable. Almost all of my <code>HttpClient</code> calls are similar to this:</p>

<pre><code>async getCurrentUser(): Promise&lt;UserInfo&gt; {
     return await this._httpClient.get(`/api/me`).toPromise();
}
</code></pre>

<p>How do you go about unit testing the function calling the HttpPost or HttpGet within Karma?</p>

<p>Attempt:</p>

<pre><code>  it('should get current user', async () =&gt; {
    const result = service.getCurrentUser();
    console.log('RESULT', result);
    const req = httpMock.expectOne(`/api/me`);
    const test = req.flush({test: 'ing'});
    console.log('REQUEST', test);

    expect('a').toEqual('a');
  });
</code></pre>
",https://stackoverflow.com/questions/51047544/unit-test-httpclient-angular-karma,"['javascript', 'angular', 'karma-jasmine']",169,TRUE,0,1
PHPUnit: how to test commands or functions that modify state?,"<p>Trying to get into Unit Testing. Since I'm also implementing CQRS, I was wondering how I would test something like this:</p>

<pre><code>class CommandHandler{
  private $repository;
  public function __construct( $repository ){
    $this-&gt;repository = $repository;
  }
  public function handle( $command ) {
    $Entity = new Entity( $command-&gt;getSomething() );
    $this-&gt;repository-&gt;add( $Entity );
  }
}
</code></pre>

<p>Taken that Unit Testing is about testing the public API of my classes, what exactly would I want to test here? That an instance of <code>Entity</code> is passed to the repository?</p>
",https://stackoverflow.com/questions/53262513/phpunit-how-to-test-commands-or-functions-that-modify-state,"['php', 'unit-testing', 'cqrs']",327,TRUE,0,1
Live Testing not working with NUnit,"<p>When I turn on Live Testing my tests show ""Excluded from live unit testing"". This only happens if I use NUnit, using MSTest works fine.</p>

<p>I have:
Visual Studio Enterprise 2017 (15.6.2)
NUnit 3.10.1</p>

<p>A brief example of code</p>

<pre><code>using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;

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

    [TestFixture]
    public class NUnitTest1
    {
        [Test]
        public void NUnitTestMethod1()
        {
        }
    }
}
</code></pre>

<p><code>TestMethod1()</code> has a green checkmark next to the beaker indicating Live Unit testing is on and covered by a test.
<code>NUnitTestMethod1()</code> has the beaker, but no checkmark and mousing over it shows ""Excluded from live unit testing"".</p>

<p>What am I missing? Outside of me adding NUnit through Nuget and adding the extra test class/method there were no other edits or changes done. I'm running on a fresh install of Visual Studio where the only other thing added is ReSharper Ultimate (2017.3.2).</p>
",https://stackoverflow.com/questions/49363880/live-testing-not-working-with-nunit,"['visual-studio', 'unit-testing', 'nunit']",1462,TRUE,5,2
mocha-webpack compile with Cannot read property &#39;babel&#39; of undefined,"<p>Webpack compilation error when unit testing. I try to modify the test file but still so, it should be webpack configuration problems, test the error component error</p>

<p>Webpack compilation error when unit testing. I try to modify the test file but still so, it should be webpack configuration problems, test the error component error
webpack.test.config.js</p>

<pre><code>const path = require('path');    
const config = {
  entry: {
    vendor: [""babel-polyfill"", ""react"", ""react-dom""],
    app: './index.js'
  },
  resolve: {
    alias: {
      'fonts': path.resolve(__dirname, 'public/fonts/'),
      '@components': path.resolve(__dirname, 'src/components/'),
      '@services': path.resolve(__dirname, 'src/services/'),
      '@routes': path.resolve(__dirname, 'src/routes/'),
      '@utils': path.resolve(__dirname, 'src/utils/'),
      '@less': path.resolve(__dirname, 'src/less/'),
      '@images': path.resolve(__dirname, 'public/images/'),
      '@public': path.resolve(__dirname, 'public/'),
    }
  },
  module: {
    rules: [{
      test: /\.js$/,
      exclude: /node_modules/,
      loader: 'babel-loader',
      query: {
        presets: ['react', 'es2015', 'stage-0']
      }
    }, {
      test: /\.less$/,
      exclude: /node_modules/,
      loader: 'style-loader!css-loader!less-loader'
    }]
  }
};

module.exports = config;
</code></pre>

<p>Agent.spec.js</p>

<pre><code>import React from 'react';
import { expect } from 'chai';
import { shallow } from 'enzyme';
import Agent from '@components/agent/index';
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

configure({ adapter: new Adapter() });

describe('&lt;Agent /&gt;', () =&gt; {
  it('Agent renderning', function () {
    let app = shallow(&lt;Agent/&gt;);
    expect(app.find('button').exists());
  });
});
</code></pre>

<p>the error</p>

<blockquote>
<pre><code> WEBPACK  Failed to compile with 1 error(s)

Error in ./test/unit/specs/Agent.spec.js

   TypeError: Cannot read property 'babel' of undefined

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ unit: `mocha-webpack --recursive test/unit/specs/*.js --webpack-config webpack.test.config.js`
npm ERR! Exit status 1
</code></pre>
</blockquote>
",https://stackoverflow.com/questions/50753903/mocha-webpack-compile-with-cannot-read-property-babel-of-undefined,"['reactjs', 'webpack', 'mocha.js', 'mocha-webpack']",213,FALSE,1,0
Spring Data QueryDslJpsRepository CrudMethodMetaData is null,"<p>I am experiencing a strange error when running in Websphere Liberty which doesn't occur in unit testing code.
Unit testing is using a <code>JpaTransactionManager</code> and WebSphere is using <code>WebSphereUowTransactionManager</code>.</p>

<p>The application code is invoking findAll on QueryDslJpaRepository.
When I step the code I can see that it somehow ends up with <code>metadata = null</code> after <code>CrudMethodMetadataPostProcessor</code> and the proxy throws NPE.</p>

<pre><code>    java.lang.NullPointerException
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.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy148.getLockModeType(Unknown Source)
at org.springframework.data.jpa.repository.support.QueryDslJpaRepository.createQuery(QueryDslJpaRepository.java:180)
</code></pre>

<p><a href=""https://gist.github.com/corneil/135dc5bd3df6f1362c52f6fdee7ed8dc"" rel=""nofollow noreferrer"">Larger Stack Trace</a></p>
",https://stackoverflow.com/questions/51024221/spring-data-querydsljpsrepository-crudmethodmetadata-is-null,['spring-data-jpa'],280,FALSE,1,0
How to unit test private methods in Typescript,"<p>When I tried to do unit testing for <strong>private methods in a Class</strong> getting error as <em>private methods are only accessible inside the class</em>. Here I added sample snippet for my class and mocha test. Kindly provide me solution to implement unit test for private methods.</p>

<p><strong>Class Name: Notification.ts</strong> </p>

<pre><code>class Notification {
 constructor() {}
 public validateTempalte() {
  return true;
 }

 private replacePlaceholder() {
  return true;
 }
}
</code></pre>

<p><strong>Unit Test:</strong></p>

<pre><code>import {Notification} from 'Notification';
import * as chai from ""chai"";

describe(""Notification"", function(){

  describe('#validateTempalte - Validate template', function() {
      it('it should return success', function() {
        const result = new Notification()
        chai.expect(result.validateTempalte()).to.be.equal(true);
      });
    });
  describe('#replacePlaceholder - Replace Placeholder', function() {
      it('it should return success', function() {
        const result = new Notification()
        // As expected getting error ""Private is only accessible within class""
        chai.expect(result.replacePlaceholder()).to.be.equal(true);
      });
    });
});
</code></pre>

<p>As a workaround, currently, I am changing access specifier of function <strong>replacePlaceholder</strong> to <strong>public</strong>. But I don't think its a valid approach. </p>
",https://stackoverflow.com/questions/48906484/how-to-unit-test-private-methods-in-typescript,"['unit-testing', 'typescript', 'mocha.js']",65962,TRUE,62,11
UIApplication applicationState must be used from main thread only,"<p>I am trying to do some unit testing for the API. Here is the actual function. </p>

<pre><code> func registerApi(path: String, player_id: Int, contest_id: Int, country_id: Int,  success: () -&gt; Void)
{
    ServiceHelper.sharedInstance.sendRequest(path: ""register-country"",
                                             params: [""api_token"": Constants.USER_INFO[""api_token""].rawValue,
                                                      ""player_id"": player_id,
                                                      ""country_id"": country_id,
                                                      ""contest_id"": contest_id],
                                             showSpinner: true,
                                             completionHandler:
        { (response, error) in

            if (error != nil)
            {
             Test to be failed
            }
            else
            {
                Test Passed

            }
    })
}
</code></pre>

<p>And, now here is the test function for unit testing. </p>

<pre><code>func testApiWorking()
{
    let controller = WorldCupChooseCountryVC()

    let expected = XCTestExpectation(description: ""Some Countries to return"")


    controller.registerApi(path: ""get-country"", player_id: 163, contest_id: 1, country_id: 1) { success in if success { expected.fulfill() }
    else{
        XCTFail()
        }
    }

    waitForExpectations(timeout: 1.0) { (_) -&gt; Void in
    }

}
</code></pre>

<p>But, whenever I try to test this I get the following error. </p>

<pre><code>[UIApplication applicationState] must be used from main thread only
</code></pre>

<p>Once, it also ran well, the test failed, but it ran. But, it is not even running now. </p>
",https://stackoverflow.com/questions/50576317/uiapplication-applicationstate-must-be-used-from-main-thread-only,"['ios', 'swift', 'uikit', 'uiapplication']",6341,TRUE,-1,2
How would I create a unit test that ensures my Header appears on the page after it is loaded and has the correct text?,"<p>I'm brand new when it comes to unit testing and I'm trying to create a unit test which isolates my Header and appears on the page after it is loaded and has the correct text. More specifically, this code:</p>

<pre><code>  static get template() {
    return `
      &lt;style include=""my-todo-style-element""&gt;&lt;/style&gt;
      // This part right here.
      &lt;h1 id=""grocery-list""&gt;Grocery List&lt;/h1&gt;
      &lt;section&gt;
        &lt;todo-input&gt;&lt;/todo-input&gt;
        &lt;ul id=""list-container""&gt;
          &lt;template is=""dom-repeat"" items=""[[list]]""&gt;
            &lt;todo-item text=""[[item.text]]"" checked=""[[item.checked]]"" index=""[[index]]"" on-remove=""removeItem"" on-toggle=""toggleItem""&gt;&lt;/todo-item&gt;
          &lt;/template&gt;
        &lt;/ul&gt;
      &lt;/section&gt;
    `
  }
</code></pre>

<p>Since I'm brand new to unit testing, I currently have this typed out in the same JS file:</p>

<pre><code>  fireEvent() {
    this.dispatchEvent(new CustomEvent('grocery-list', {detail: 
'tested!'}))
  }
}
</code></pre>

<p>With this as my test file:</p>

<pre><code>&lt;script&gt;
test('fires an event', function(done) {
  myEl.addEventListener('grocery-list', function(event) {
    assert.equal(event.detail, 'tested!');
    done();
  });
  myEl.fireEvent();
});
&lt;/script&gt;
</code></pre>
",https://stackoverflow.com/questions/53619899/how-would-i-create-a-unit-test-that-ensures-my-header-appears-on-the-page-after,"['unit-testing', 'ecmascript-6', 'polymer']",53,FALSE,2,0
TypeError: Super expression must either be null or a function,"<p>I'm very new to unit Testing in vue js. I just went through this website to learn unit testing ""<a href=""https://vue-test-utils.vuejs.org/guides/#testing-single-file-components-with-mocha-webpack"" rel=""nofollow noreferrer"">https://vue-test-utils.vuejs.org/guides/#testing-single-file-components-with-mocha-webpack</a>"". while I'm practicing the examples in ""mocha-webpack"" I got this Error</p>

<pre><code>WEBPACK  Failed to compile with 1 error(s)
Error in ./src/Counter.vue
TypeError: Super expression must either be null or a function
at /opt/htdocs/guru/unitTest_prct/node_modules/prettier/index.js:32893:5
at /opt/htdocs/guru/unitTest_prct/node_modules/prettier/index.js:32913:4
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! mdbvue@4.2.0 test: `mocha-webpack --webpack-config  webpack.config.js --require test/setup.js test/**/*.spec.js`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the mdbvue@4.2.0 test script.
npm ERR! This is probably not a problem with npm. There is likely     additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2018-09-06T10_28_47_073Z-debug.log
</code></pre>

<p>Can anyone tell me how to solve this error. This is my Counter.vue file</p>

<pre><code>&lt;template&gt;
  &lt;div&gt;
   &lt;div&gt;
     {{ count }}
     &lt;button @click=""increment""&gt;Increment&lt;/button&gt;
   &lt;/div&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
export default {
    data () {
       return {
         count: 0
       }
    },
   methods: {
      increment () {
        this.count++;
      }
    }
};
&lt;/script&gt;
</code></pre>

<p>Here is my Counter.spec.js File</p>

<pre><code>import { shallowMount } from '@vue/test-utils'
import Counter from '../src/docs/Counter.vue'
describe('Counter.vue', () =&gt; {
  it('increments count when button is clicked', () =&gt; {
    const wrapper = shallowMount(Counter)
    wrapper.find('button').trigger('click')
    expect(wrapper.find('div').text()).toMatch('1')
  })
})
</code></pre>
",https://stackoverflow.com/questions/52202399/typeerror-super-expression-must-either-be-null-or-a-function,"['javascript', 'node.js', 'vue.js']",4989,TRUE,1,2
How to test PROCEDURE in PostgreSQL with pgTAP?,"<p>Is there a best practice for unit testing a PostgreSQL 11+ <a href=""https://www.postgresql.org/docs/current/sql-createprocedure.html"" rel=""nofollow noreferrer"">PROCEDURE</a> (NOT a <a href=""https://www.postgresql.org/docs/current/sql-createfunction.html"" rel=""nofollow noreferrer"">FUNCTION</a>) using <a href=""https://pgtap.org/"" rel=""nofollow noreferrer"">pgTap</a>.</p>

<p>For example, how would one recommend unit testing a stored procedure like this:   </p>

<pre><code>CREATE OR REPLACE PROCEDURE foo.do_something(IN i_value INT)
AS
$$
BEGIN
  PERFORM foo.call_function_1(i_value);
  COMMIT;      
  PERFORM foo.call_function_2(i_value);
  COMMIT;      
  CALL foo.another_procedure(i_value);
END;
$$
LANGUAGE plpgsql;
</code></pre>

<p>This becomes difficult since pgTap unit tests run via a stored function like this:   </p>

<pre><code>SELECT * FROM runtests('foo'::NAME);
</code></pre>

<p>This executes in a transaction, making it impossible to execute stored procedures that modify transaction state by calling <code>COMMIT</code> or <code>ROLLBACK</code>.</p>
",https://stackoverflow.com/questions/53769327/how-to-test-procedure-in-postgresql-with-pgtap,"['postgresql', 'postgresql-11', 'pgtap']",2226,TRUE,0,1
Pylint says module cannot be imported,"<p>I have a Python module that performs unit testing on a module I have written. The unit test is placed in a folder called tests, and the module I am testing is one directory above. So, my unit testing file has the following header.</p>

<pre><code>import unittest
import sys
sys.path.append('../')
import table_builder
</code></pre>

<p>But when I lint this unit test code, I receive the following errors:</p>

<pre><code>No config file found, using default configuration
************* Module unittests_table_builder
E:  9, 0: Unable to import 'table_builder' (import-error)
C:  9, 0: Import ""import table_builder"" should be placed at the top of the           module (wrong-import-position)

------------------------------------------------------------------
Your code has been rated at 4.55/10 (previous run: 4.55/10, +0.00)
</code></pre>

<p>How do I fix this?</p>
",https://stackoverflow.com/questions/50477765/pylint-says-module-cannot-be-imported,"['python', 'unit-testing', 'pylint']",742,FALSE,0,1
How to test shared preference,"<p>When unit testing shared preference, is the value get refresh every test?</p>

<pre><code>public static void putString(Context context, String key, String val) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(key, val);
        editor.apply();
    }
</code></pre>
",https://stackoverflow.com/questions/52586359/how-to-test-shared-preference,['android'],301,TRUE,0,2
Moq and file/data saving in C#,"<p>Ok, I am working on some unit testing, and my understanding is (based on ""The Art of Unit Testing"" by Roy Osherove) that if you're hitting a DB or actually <em>saving</em> a file, you're integration testing, not unit testing.</p>

<p>Given that, I have the following (yes, I know this violates SRP, but it illustrates my point):</p>

<pre><code>public class PrimeChecker : IPrimeChecker
{
    public bool IsPrime(int num)
    {
        if (num &lt; 2)
        {
            return false;
        }

        if (num &gt; 2 &amp;&amp; num % 2 == 0)
        {
            return false;
        }

        if (num % 2 != 0)
        {
            for (int i = 3; (i * i) &lt;= num; i += 2)
            {
                if (num % i == 0)
                {
                    return false;
                }
            }
        }

        return true;
    }

    public bool Save()
    {
        return true;
    }
}
</code></pre>

<p>Note the the Save() method is simply a stub right now.</p>

<p>I'm trying to use Moq to simulate saving. So my test looks like this:</p>

<pre><code>[Test]
    public void Save_WhenCalled_ExecutesSave()
    {
        var mock = new Mock&lt;IPrimeChecker&gt;();

        mock.Setup(x =&gt; x.Save());

        IPrimeChecker checker = mock.Object;
        checker.Save();

        mock.Verify(x =&gt; x.Save(), Times.Once);
    }
</code></pre>

<p>So if I had a fully-functioning Save() method in my class, is this the correct way to mock functionality? Because as I previously stated, my understanding is that for unit tests, I'm not supposed to actually write a file/save to a DB.</p>

<p>If this isn't correct, what <em>should</em> I be doing?</p>
",https://stackoverflow.com/questions/48228016/moq-and-file-data-saving-in-c,"['c#', 'unit-testing', 'moq']",2868,TRUE,5,1
Jasmine/Karma - Unit test for button enable in Angular 2,"<p>I am not much aware of Jasmine/Karma unit testing, Here i am testing reactive form button. If two fields having input my button will enable, this is normal functionality of my form. while unit testing for this functionality i am getting error like ""Failed: Cannot read property 'nativeElement' of null"". If any one knows please help me.</p>

<p>Here is my form.</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;div class=""grid"" &gt;
&lt;div [formGroup]=""orderUnitForm"" &gt;
	&lt;div class=""form-group"" [hidden]=""searhPanel""&gt;
    &lt;div class=""layer-types__layer-1"" &gt;             
              &lt;div class=""bx--row""&gt;
              &lt;div class=""bx--col-md-12 bx--col-xs-12""&gt;              
		        &lt;select id=""select-menu"" class=""bx--text-input"" formControlName=""ruleSelection"" name=""ruleSelection"" (change)=""onChange($event.target.value)"" &gt;
		        	 &lt;option  selected&gt;{{defaultSearch}}&lt;/option&gt;
		        	 &lt;option  *ngFor=""let rule of rules""  [value]=""rule.id"" &gt;{{rule.name}}&lt;/option&gt;
		        &lt;/select&gt;
		   	 
		   	  &lt;/div&gt;
		   	  &lt;/div&gt;
    			
              &lt;div class=""bx--row""&gt;     
	               &lt;!-- &lt;div class=""form-group"" [ngClass]=""{'has-error': displayMessage.orderingUnit }""&gt;  --&gt;       
		              &lt;div class=""bx--col-md-2 bx--col-xs-12"" align=""right""&gt;                          
		               	&lt;label for=""orderingUnit"" class=""bx--label""&gt;Ordering Unit&lt;/label&gt;
		              &lt;/div&gt;
		              &lt;div class=""bx--col-md-10 bx--col-xs-12""&gt;
				 		&lt;input type=""text""   id=""orderingUnit"" placeholder=""Ordering Unit"" class=""bx--text-input""
				 		formControlName=""orderingUnit"" name=""orderingUnit""		 		
				 		[attr.title]=""orderingUnitTip"" [attr.data-invalid]=""displayMessage.orderingUnit ? '' : null""&gt;
				 		&lt;div class=""bx--form-requirement"" *ngIf=""displayMessage.orderingUnit"" &gt;{{ displayMessage.orderingUnit }} &lt;/div&gt;					 	 			 		
					  &lt;/div&gt;
				  
			   &lt;/div&gt;              
              &lt;div class=""bx--row""&gt;
              &lt;div class=""bx--col-md-2 bx--col-xs-12"" align=""right""&gt;
               	&lt;label for=""orderReferenceNumber"" class=""bx--label""&gt;Order Reference Number&lt;/label&gt;
              &lt;/div&gt;
              &lt;div class=""bx--col-md-10 bx--col-xs-12""&gt;
			 		&lt;input type=""text"" class="" bx--text-input"" id=""orderReferenceNumber"" placeholder=""Order Reference Number"" 
			 		formControlName=""orderReferenceNumber"" name=""orderReferenceNumber"" 
			 		[attr.title]=""orderReferenceNumberTip"" [attr.data-invalid]=""displayMessage.orderReferenceNumber ? '' : null""&gt;
				 	&lt;div class=""bx--form-requirement"" *ngIf=""displayMessage.orderReferenceNumber"" &gt;{{ displayMessage.orderReferenceNumber }} &lt;/div&gt;			
			  &lt;/div&gt;
        &lt;/div&gt;
         &lt;div class=""bx--col-md-1 bx--col-xs-4"" &gt;                
              &lt;!--  &lt;carbon-button type=""primary"" (click)=""onInclude()""&gt;Include&lt;/carbon-button&gt; --&gt;
              &lt;button class=""bx--btn bx--btn--primary"" type=""button"" id=""inc"" (click)=""onInclude()"" [disabled]=""!valid || !orderUnitForm.valid""&gt;Include&lt;/button&gt;
              &lt;/div&gt;
              &lt;/div&gt;       
&lt;/div&gt;
        </code></pre>
</div>
</div>
</p>

<p>Here is my test cases:</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('SearchPanelComponent', () =&gt; {
  let component: SearchPanelComponent;
  let fixture: ComponentFixture&lt;SearchPanelComponent&gt;;
  let includeBtn: HTMLElement;
  let orderingUnit: HTMLElement;
  let orderReferenceNumber: HTMLElement;
  let el: HTMLElement;
  let overlayContainerElement: HTMLElement;
  

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [ReactiveFormsModule, FormsModule,CarbonDatepickerModule, CarbonIconModule, StoreModule.forRoot({})],
      declarations: [ SearchPanelComponent, ModalComponent, UploadsearchcriteriaComponent, ],
      providers: [Store,StoreModule,CustomerorderService, ApiConnectorService, HttpClient, HttpHandler,ModalService]
    })
    .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(SearchPanelComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });

  it('should check include is enabled after inputs combinations', async(() =&gt; {
    includeBtn = fixture.debugElement.query(By.css('button')).nativeElement;

    fixture.whenStable().then(() =&gt; {
      var inputElement = &lt;HTMLInputElement&gt;document.getElementById('orderingUnit');
      inputElement.value = 'abc';
      inputElement.dispatchEvent(new Event('input'));
      
      var inputElement1 = &lt;HTMLInputElement&gt;document.getElementById('orderReferenceNumber');
      inputElement1.value = 'abcdef';
      inputElement1.dispatchEvent(new Event('input'));
      fixture.detectChanges();
      expect(includeBtn.getAttribute('ng-reflect-enabled')).toBe('true', 'Include button enabled should now be true');
    });
  }));
  });</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/51648249/jasmine-karma-unit-test-for-button-enable-in-angular-2,"['javascript', 'angular', 'unit-testing', 'karma-jasmine', 'angular-reactive-forms']",1651,FALSE,0,0
Jasmine doesn&#39;t recognize Angular&#39;s DomSanitizer,"<p>I am unit testing an Angular 5 app with Jasmine. I got to the point where I need to test a function that relies on the <code>DomSanitizer</code>:</p>

<pre><code>loadImage() {
  this.image = this.sanitizer.bypassSecurityTrustStyle(`url(${this.assetUrl})`);
}
</code></pre>

<p>I verified that this function works perfectly, meaning that <code>DomSanitizer</code> is already in the constructor and it's syntax is correct. </p>

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

<pre><code>it('loads the Image', () =&gt; {
    component.loadImage()
    fixture.detectChanges();
    expect(component.imageUrl).toBe('...');
  });
</code></pre>

<p>Moreover, <code>DomSanitizer</code> is part of the <code>TestBed</code> <code>providers</code>:</p>

<pre><code>beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule,
        CommonModule
      ],
      declarations: [
        MyComponent
      ],
      providers: [
        DomSanitizer
      ],
      schemas: [ NO_ERRORS_SCHEMA ]
    })
    .compileComponents();
  }));
</code></pre>

<p>Yet, Jasmine throws this error when unit-testing the function:</p>

<pre><code>ERROR: 'Unhandled Promise rejection:', '_this.sanitizer.bypassSecurityTrustStyle is not a function', '; Zone:', 'angular', '; Task:', 'Promise.then', '; Value:', TypeError: _this.sanitizer.bypassSecurityTrustStyle is not a function
</code></pre>

<p>Any ideas?</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/50631215/jasmine-doesnt-recognize-angulars-domsanitizer,"['angular', 'jasmine', 'testbed', 'angular-dom-sanitizer']",3087,TRUE,2,1
AWS-SAM-LOCAL unit test strategy,"<p>I've been looking around for aws-sam-local unit testing strategies and haven't found much.  Just looking for suggestions?</p>
",https://stackoverflow.com/questions/48506792/aws-sam-local-unit-test-strategy,['aws-sam-cli'],2872,TRUE,5,2
Example CmakeList.txt for using GoogleTest with C project,"<p>I understand googletest is for C++ Unit testing. However, I hope that I can use it for C Unit testing as well. I created a Hello world project with the following CmakeList.txt file which obviously didn't work. </p>

<p>One of the issue was /usr/bin/cc complained about C++ syntax such as ""include &lt; limits >"" not found. I guess it though it was supposed to be limits.h to be C stylistically correct.</p>

<pre><code>cmake_minimum_required(VERSION 3.10)
project(untitled C CXX)

set(CMAKE_C_STANDARD 11)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_VERBOSE_MAKEFILE 1)

include_directories(../googletest/googletest/include)

add_executable(untitled main.c)
link_libraries(untitled gtest gtest_main)
</code></pre>

<p>main.c</p>

<pre><code>#include &lt;stdio.h&gt;
#include &lt;gtest/gtest.h&gt;

int return_one()
{
    return 1;
}

TEST(test_case, test_name)
{
    ASSERT_EQ(return_one(), 1);
}
</code></pre>
",https://stackoverflow.com/questions/53220938/example-cmakelist-txt-for-using-googletest-with-c-project,"['unit-testing', 'gcc', 'cmake', 'googletest', 'clion']",40,FALSE,1,0
How to use overloading operator without the include friend?,"<p>for unit testing:</p>

<pre><code> ostream&amp; operator &lt;&lt; (ostream&amp;os,const Unit&amp;C)
 {

     os &lt;&lt; C.GetUnitName() &lt;&lt; C.GetUnitID() &lt;&lt; C.GetCredits();
     return os;
 }

 istream&amp; operator &gt;&gt; (istream&amp;input,Unit&amp;C)
 {
     string UnitName,UnitsID;
     int Crediet;
     input &gt;&gt; UnitName &gt;&gt; UnitsID&gt;&gt; Crediet;

    C.setUnitName(UnitName);
    C.setUnitID(UnitsID);
    C.setCredits(Crediet);

    return input;
}
</code></pre>

<p>text input file: Database ICT222 3</p>

<p>why I get the outfile:""0x6afd64""?</p>
",https://stackoverflow.com/questions/48862612/how-to-use-overloading-operator-without-the-include-friend,['c++'],73,TRUE,-3,1
How mock object work in Angular jasmine unit test,"<p>I am learning unit testing and Angular, so I am beginner in both.
I have referred several tutorials and articles available on unit testing http in angular.</p>

<p>I am not able to understand that what does httpMock does using HttpTestingController. We call function of actual service then why we call it mock?
What is underlying process?
Please refer some article to get better understanding.</p>

<p>Thanks in advance.</p>

<p><strong>Edit:</strong>
This is the <a href=""https://stackoverflow.com/questions/49940214/angular-httpclienttestingmodule-httpmock-giving-error-found-2-requests"">issue</a> where I stuck with httpMock.</p>
",https://stackoverflow.com/questions/49942372/how-mock-object-work-in-angular-jasmine-unit-test,"['angular', 'angular-httpclient']",20688,TRUE,4,3
Does anyone know how we can unit test IBM MQ Message Flows in an isolated way using stubs?,"<p>I am new to IBM-MQ and trying to understand how we can perform unit testing on message flows.</p>

<p>I am aware of the tools like CA Lisa to do Service Virtualization and testing at system testing level.</p>

<p>But in my case I am looking for the unit testing framework like Java Junit tests where developer can create tests and required stubs to test the IBM MQ Message flows independently.</p>

<p>Thank You in advance.</p>
",https://stackoverflow.com/questions/53222305/does-anyone-know-how-we-can-unit-test-ibm-mq-message-flows-in-an-isolated-way-us,"['ibm-mq', 'messagebroker', 'ibm-integration-bus']",6155,TRUE,1,3
Getting `attempt to index local &#39;err_msg&#39;` when using luaunit,"<p>When using luaunit for Lua unit testing, I get the following error:</p>

<p><code>./luaunit.lua:503: attempt to index local 'err_msg' (a nil value)</code></p>

<p>What could be wrong?</p>
",https://stackoverflow.com/questions/49416984/getting-attempt-to-index-local-err-msg-when-using-luaunit,"['unit-testing', 'lua']",96,TRUE,-1,1
How to test POST method in Spring boot using Mockito and JUnit,"<p>I am newbie to Unit testing using JUnit and Mockito in Spring boot framework.
I want to test this method. How to test POST Request method:</p>

<pre><code>// add Employee
@RequestMapping(method = RequestMethod.POST)
public void addEmployee(@RequestBody Employee employee){
    this.employeeService.addEmployee(employee);
}
</code></pre>

<p>Thank you in advance</p>
",https://stackoverflow.com/questions/51346781/how-to-test-post-method-in-spring-boot-using-mockito-and-junit,"['unit-testing', 'spring-boot', 'testing', 'junit', 'mockito']",53644,TRUE,13,3
How to solve &quot;Cannot read property &#39;replace&#39; of null&quot; for Karma testing with AngularJS?,"<p>I am using Karma and jasmine for the unit testing for UI. I set-up all required dependencies. when I start the debug to the test case is failing and giving </p>

<blockquote>
  <p>Cannot read property 'replace' of null</p>
</blockquote>

<p>Warning giving in the debug.js, But I am not using any debug.js file. </p>

<p>screen shot:</p>

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

<p><strong>package.js</strong></p>

<pre><code>{
  ""name"": ""test-app"",
  ""version"": ""1.0.0"",
  ""description"": ""a tool to aid"",
  ""main"": ""index.html"",
  ""private"": true,
  ""scripts"": {
    ""dev"": ""gulp dev"",
    ""prod"": ""gulp prod""
  },
  ""author"": ""kim"",
  ""license"": ""Myange Inc."",
  ""devDependencies"": {
    ""event-stream"": ""~3.3.1"",
    ""gulp"": ""^3.9.0"",
    ""gulp-angular-templatecache"": ""^1.7.0"",
    ""gulp-clean"": ""^0.3.2"",
    ""gulp-concat"": ""^2.6.0"",
    ""gulp-connect"": ""^2.2.0"",
    ""gulp-maven-deploy"": ""^1.0.1"",
    ""gulp-ng-annotate"": ""^1.0.0"",
    ""gulp-uglify"": ""^1.2.0"",
    ""gulp-util"": ""^3.0.8"",
    ""gulp-zip"": ""^4.0.0"",
    ""jasmine"": ""^3.1.0"",
    ""karma"": ""^2.0.5"",
    ""karma-chrome-launcher"": ""^2.2.0"",
    ""karma-jasmine"": ""^1.1.2"",
    ""karma-jasmine-html-reporter"": ""^1.2.0"",
    ""karma-ng-html2js-preprocessor"": ""^1.0.0"",
    ""lodash"": ""^4.0.0"",
    ""webdriver-manager"": ""10.2.5""
  },
  ""dependencies"": {
    ""angular-mocks"": ""^1.7.2""
  }
}
</code></pre>

<p><strong>UnitTestCase.js</strong></p>

<pre><code>describe('app.way-bus of test ', function() {
  // beforeEach(angular.mock.module('app'));
  var $controller, $rootScope;
  var DTOptionsBuilder, DTColumnDefBuilder, $http, $q, $compile, Notifier, $location, $sce, $filter, FRh, Rh, RhAuth, $stateParams, $state;
  beforeEach(angular.mock.module('restheart'));
  beforeEach(angular.mock.module('app.cargo-watchListMgmt', function($provide) {
    mockedFactory = {
      save: jasmine.createSpy()
    };
    Notifier = $provide.value('Notifier', mockedFactory);
  }));
  beforeEach(inject(function(_$controller_, _$rootScope_,_Rh_,_$stateParams_,_$state_,_Notifier_){
    // The injector unwraps the underscores (_) from around the parameter names when matching
    $controller = _$controller_;
    $rootScope = _$rootScope_;
    console.log($rootScope)

    Rh = _Rh_;
    //RhAuth = _RhAuth_;
    $stateParams = _$stateParams_;
    $state = _$state_;
    Notifier = _Notifier_;
  }));

  describe('call fetchData', function() {
    it('check', function() {
      var $scope = $rootScope.$new();
      console.log($scope)
      var controller = $controller('wayBusCntrl', {

        $scope: $scope,

        Rh: Rh,
        //RhAuth: RhAuth,
        $stateParams: $stateParams,
        $state: $state,
        Notifier: Notifier
      });

      expect($scope.xyz).toBe('satya')
    });
  });


});
</code></pre>

<p>So I am not able to process my unit testing because of that error(Cannot read property 'replace' of null).</p>
",https://stackoverflow.com/questions/51633607/how-to-solve-cannot-read-property-replace-of-null-for-karma-testing-with-ang,"['javascript', 'angularjs', 'unit-testing', 'karma-jasmine']",875,FALSE,1,0
"Could not load file or assembly &#39;Microsoft.CodeAnalysis.LiveUnitTesting.Runtime, version= 1.7.0.0&#39; with visual studio 2017","<p>I started live unit testing with visual studio 2017 (15.7.1). After I switch the branch and start the project, an error message comes up saying the following:</p>

<blockquote>
  <p>Could not load file or assembly 'Microsoft.CodeAnalysis.LiveUnitTesting.Runtime, version= 1.7.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependenc</p>
</blockquote>

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

<p>I tried to:<br>
 - rebuild/restart the project<br>
 - stop live unit testing<br>
but it didn't work.</p>

<p>I don't know why load 'Microsoft.CodeAnalysis.LiveUnitTesting.Runtime' from project/bin.<br>
Anyone have a suggestion? </p>
",https://stackoverflow.com/questions/50278930/could-not-load-file-or-assembly-microsoft-codeanalysis-liveunittesting-runtime,"['c#', 'asp.net-mvc', 'visual-studio', 'visual-studio-2017', 'live-unit-tests']",1473,TRUE,1,2
how to write unit test for android method and class?,"<p>how to write unit test for android method and class?</p>

<p>for example :</p>

<pre><code>public int dpToPx (Context context, int dp) {

float density = context.getResources().getDisplayMetrics().density;

return Math.round((float) dp * density);

}
</code></pre>

<p><a href=""https://developer.android.com/training/testing/unit-testing"" rel=""nofollow noreferrer"">https://developer.android.com/training/testing/unit-testing</a></p>
",https://stackoverflow.com/questions/52074848/how-to-write-unit-test-for-android-method-and-class,"['android', 'unit-testing']",83,TRUE,1,1
Is there a way to create step functions graph using CDK?,"<p>Currently step functions graph are defined in json using ASL (Amazon States Language).
There is no good way to to unit testing of the graphs being created and we have to rely on running the graph with mocked/some implementation of lambda functions on aws account.
With launch of AWS CDK, is it possible to have the step function graphs also defined in high level language and do unit testing, mocking etc?</p>
",https://stackoverflow.com/questions/53587097/is-there-a-way-to-create-step-functions-graph-using-cdk,"['aws-step-functions', 'aws-cdk']",2501,TRUE,0,1
Difference between tableView.cellForRow(at:) and tableView.dataSource?tableView(tableView:cellForRowAt:),"<p>I'm unit testing on a <code>tableView</code> whether it renders a cell.</p>

<p>And I found that <code>tableView.cellForRow(at:)</code> returns nil, while <code>tableView.dataSource?tableView(tableView:cellForRowAt:)</code> returns the right cell.</p>

<p>Here's my unit test code.</p>

<pre><code>it(""renders one option text"") {
    let indexPath = IndexPath(row: 0, section: 0)

    let cell = sut.tableView.dataSource?.tableView(sut.tableView, cellForRowAt: indexPath)

    let cell2 = sut.tableView.cellForRow(at: indexPath)

    expect(cell?.textLabel?.text).toEventually(equal(""A1""))  // test suceeded
    expect(cell2?.textLabel?.text).toEventually(equal(""A1"")) // test failed
}
</code></pre>

<p>So I'm curious about the difference of the two methods.</p>

<p>Apple's document says that <code>tableView.cellForRow(at:)</code> returns nil if the cell is not visible, so I'v understood that <code>tableView.cellForRow(at:)</code> returns nil when it's under unit testing,
but I'm not sure the <strong>time order of the two methods being called</strong> and <strong>when <code>tableView.cellForRow(at:)</code> get the right value(cell)</strong>.</p>
",https://stackoverflow.com/questions/53735018/difference-between-tableview-cellforrowat-and-tableview-datasourcetableview,"['ios', 'swift', 'unit-testing', 'uitableview']",852,TRUE,2,2
iOS app test if Localization translations have same keys,"<p>In my iOS app I have localization files such as Localizable.strings.
I want to check that they have same keys and there is no missed keys in each localization. </p>

<p>I thought about performing this in Unit Tests. </p>

<ol>
<li>Is Unit testing the right place for this? Maybe there is much easier tool for it?</li>
<li>How this Unit testing can be done? </li>
</ol>

<p>I found article on this topic in Obj-C <a href=""https://www.cocoanetics.com/2013/03/localization-unit-test/"" rel=""nofollow noreferrer"">https://www.cocoanetics.com/2013/03/localization-unit-test/</a> that is 5 years old. Maybe something else can be used?</p>
",https://stackoverflow.com/questions/50058203/ios-app-test-if-localization-translations-have-same-keys,"['ios', 'swift', 'xcode', 'shell', 'localization']",783,TRUE,6,1
Angular 6 Karma Testing API Issue,"<p>I am new to Unit testing. I have created an Angular 6 app and want to do unit testing. I am getting some errors after running <code>ng test</code>.</p>

<p><a href=""https://i.stack.imgur.com/2VYeP.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/2VYeP.png"" alt=""NotificationPageComponent Error""></a></p>

<p>Notifications Page is calling the service <code>NotificationService.getNotifications()</code> which is defined in <code>notification.service.ts</code> </p>

<p>Notification Component Test File:</p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { HttpClientModule } from '@angular/common/http';
import { NotificationsPageComponent } from './notifications-page.component';
import { RouterTestingModule } from ""@angular/router/testing"";

import { AuthService } from '../../shared/auth/auth.service';

describe('NotificationsPageComponent', () =&gt; {
  let component: NotificationsPageComponent;
  let fixture: ComponentFixture&lt;NotificationsPageComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      providers: [AuthService],
      declarations: [ NotificationsPageComponent ],
      imports: [HttpClientModule, RouterTestingModule]
    })
    .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(NotificationsPageComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>

<p><strong>notification.service.ts</strong></p>

<pre><code>import { AppConfigService } from '../services/app-config.service';
import { AuthService } from '../shared/auth/auth.service';
....
export class NotificationService {
    ....
    getNotifications() {
        return this.http.get(this.appConfig.config.api_link + '/notes?show_on_dashboard=true', { headers: this.authService.header() })
        .pipe(map(res =&gt; JSON.stringify(res)));
    }
}
</code></pre>

<p>this <code>api_link</code> is coming from <code>app-config.service.ts</code></p>

<p><strong>app-config.service.ts</strong></p>

<pre><code>import { environment } from 'environments/environment';
export class AppConfigService {
    private appConfig;
    loadAppConfig() {
        this.http.get('./environments/env_settings.json').subscribe((data) =&gt; {
            this.appConfig = data;
            console.log('Environment variables loaded from env_settings.json');
            console.log(this.appConfig);
        },
        (err) =&gt; {
            console.warn(""Error loading env_settings.json, using envrionment file instead"");
            this.appConfig = environment;
        });
    }

    get config() {
        return this.appConfig;
    }
}
</code></pre>

<p>I am getting 6 erros in Karma console and all are the same <strong>TypeError: Cannot read property 'api_link' of undefined</strong></p>

<p>Any help would be appreciated.</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/51855165/angular-6-karma-testing-api-issue,"['angular', 'unit-testing', 'karma-jasmine']",258,FALSE,0,1
How to test my devise code using rspec?,"<p>Here is my unit testing code for devise. Are there any ways to write better test code?</p>

<p>user_spec.rb:</p>

<pre><code>require 'rails_helper'

    RSpec.describe User, type: :model do

      it { should have_many(:companies) }
      it { should have_many(:jobs) }
      it do
               should validate_length_of(:encrypted_password).
                   is_at_least(6).
                   on(:create)
               end

      it { is_expected.to validate_presence_of(:email) }
      it { is_expected.to validate_presence_of(:encrypted_password) }
      it { should have_db_column(:id) }
      it { should have_db_column(:email) }
      it { should have_db_column(:encrypted_password) }
      it { should have_db_column(:confirmation_token) }
      it { should have_db_column(:confirmed_at) }
      it { should have_db_column(:confirmation_sent_at) }

      it 'is databse authenticable' do
        user = User.create(
           email: 'test@example.com', 
          password: 'password123',
          password_confirmation: 'password123'
        )
        expect(user.valid_password?('password123')).to be_truthy
      end
end
</code></pre>
",https://stackoverflow.com/questions/48779531/how-to-test-my-devise-code-using-rspec,"['ruby-on-rails', 'ruby', 'ruby-on-rails-3', 'ruby-on-rails-4', 'rubygems']",132,TRUE,0,1
spring boot application main method unit test with mockito,"<p>I'm very new to unit testing and mockito. How can write a unit test for the code below.</p>

<pre><code>@SpringBootApplication
public class MyApplication {
    public static void main(String[] argv) {
        SpringApplication.run(MyApplication.class);
    }
}
</code></pre>
",https://stackoverflow.com/questions/51793272/spring-boot-application-main-method-unit-test-with-mockito,"['unit-testing', 'spring-boot', 'mockito']",936,TRUE,-1,1
Design MVC Controller using TDD for database calls,"<p>I am new to MVC and unit testing. I need to do unit testing on my controllers but I'm afraid I may not have them setup properly.  </p>

<p>For example:</p>

<pre><code>public class MyController
{
     public ActionResult Index(int id)
     {
         var locations = new MyLocations().GetLocations();
         //linq code here that filters based on id
         return View(filteredLocations)
     }
}
</code></pre>

<p>This is a really simple example, but how would I set this up correctly so that I could use the TDD model so that when I unit test I can provide a static list of locations as the return value? </p>

<p>I am unsure on how this should be properly structured.</p>
",https://stackoverflow.com/questions/50005541/design-mvc-controller-using-tdd-for-database-calls,"['c#', 'asp.net-mvc', 'unit-testing', 'tdd']",261,TRUE,1,1
Mocking a parent FormGroup via @input in Jasmine,"<p>So I have a child component that goes something like this </p>

<pre><code>export class ChildComponent implements OnInit {

  @Input('parentForm')
  public parentForm: FormGroup;

  constructor(private fb: FormBuilder, private cd: ChangeDetectorRef) { }

  ngOnInit() {
    this.parentForm.addControl('newControl', &lt;Some Control&gt;);
  }
}
</code></pre>

<p>Next I have a barebones unit testing file that goes like this</p>

<pre><code>describe('ChildComponent', () =&gt; {
  let component: ChildComponent;
  let fixture: ComponentFixture&lt;ChildComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [ReactiveFormsModule, FormsModule],
      declarations: [ ChildComponent ],
      providers: [ FormBuilder, FormGroup ]
    })
    .compileComponents();
  }));

  beforeEach(inject([FormBuilder], (fb: FormBuilder) =&gt; {
    fixture = TestBed.createComponent(ChildComponent);
    component = fixture.componentInstance;
    component.parentForm = fb.group({});
    component.ngOnInit();
    fixture.detectChanges();
  }));

  fit('should be created', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>

<p>Previously I had an issue where parentForm was undefined so I tried to build it myself by doing injecting FormBuilder in the beforeEach by doing this <code>component.parentForm = fb.group({});</code>. However now the issue is that karma/jasmine cannot find FormBuilder </p>

<p><code>Cannot find name 'FormBuilder'.</code></p>

<p>All I am trying to do is try to get or mock the parentForm for when I create an instance of the component during my unit testing, and I need it because I am calling ngOnInit during the for each as it as a new control.</p>

<p>Any ideas. Thank you</p>
",https://stackoverflow.com/questions/49162404/mocking-a-parent-formgroup-via-input-in-jasmine,"['unit-testing', 'karma-jasmine', 'angular-reactive-forms', 'formbuilder', 'angular4-forms']",20794,TRUE,14,1
Test coverage overridden by other test,"<p>I am unit testing spring batch application.</p>

<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={Reader.class, Writer.class, Job.class, Step.class})
public class MyTest {

@Autowired
private JobLauncherTestUtils jobLauncherTestUtils;

@Test
public void Test1(){
    //some mocking
    jobLauncherTestUtils.launchJob();
    //assertion etc. 
}

//This test is overridding code coverage of the first test. 
@Test
public void Test2(){
    //some mocking
    jobLauncherTestUtils.launchJob();
    //assertion etc. 
}
}
</code></pre>

<p>Why is this happening, anyone has any idea? What could be the reason?  </p>
",https://stackoverflow.com/questions/52826990/test-coverage-overridden-by-other-test,"['spring', 'spring-batch', 'spring-test']",160,FALSE,1,0
FakeItEasy: Mocking MessageBox,"<p>I need to avoid(mock) unit testing of line of code displaying messagebox using FakeItEasy framework.</p>

<p>Code is here,</p>

<pre><code>public class XYZ
{
    public static int nValue = 0;

    public void AddInetegers(int i)
    {

        int j = i * 100;
        int k = j * 30 / 100;

        MessageBox.Show(""Value Here {0}"",  k.ToString());

        nValue = k;
    }
}
</code></pre>
",https://stackoverflow.com/questions/49671838/fakeiteasy-mocking-messagebox,"['unit-testing', 'mocking', 'fakeiteasy']",85,TRUE,0,1
Does PhantomJs supports constant(const) and let?,"<p>I am using PhantomJs for unit testing angularJs app.</p>

<p>So my question is , Does PhantomJs supports constant(const) and let?</p>
",https://stackoverflow.com/questions/48699385/does-phantomjs-supports-constantconst-and-let,"['javascript', 'phantomjs']",991,TRUE,1,1
QUnit testing strategy for object with init function that could throw,"<p>I am using <a href=""https://github.com/simula-innovation/qunit/tree/gas/gas"" rel=""nofollow noreferrer""><code>QUnit</code></a> for Google Apps Script, and am attempting unit-testing on my code base, namely on this custom spreadsheet helper function I wrote:  </p>

<pre><code>function DataStoreHelper() {
  this.argNames = arguments;    // TODO: check type of arguments
  this.argIndices = new Array(this.argNames.length);
  /* takes an array of column names and assigns the indices where they can be found, to this.argIndices
   */
  this.sortColumns = function (columnNames) { 
    // for each argument name ...
    for (var j in this.argNames)
    {
        var k = 0; 
      // ... sift thru the column names ...
      for (k in columnNames) {
          // ... to find the column name that contains the argument name ...
        if (columnNames[k].toLowerCase().indexOf(this.argNames[j]) !== -1) break;
        else if (k == columnNames.length - 1) k = -1;

      }
      // if we found it, we write it to this.argIndices
      if (k &gt; -1) this.argIndices[j] = k;
      // otherwise, we have spreadsheet error.
      else throw new Error('Spreadsheet is missing column for constructor argument: ' + this.argNames[j]);
      Logger.log('this.argNames[%s] == %s\tthis.argIndices[%s] == %s\n',
        j, 
        this.argNames[j],
        j,
        this.argIndices[j])
    }
  }
}
// static const strings
DataStoreHelper.POTHOLE_NUMBER  = 'number';
DataStoreHelper.LATITUDE        = 'latitude';
DataStoreHelper.LONGITUDE       = 'longitude';
DataStoreHelper.ADDRESS         = 'address';
DataStoreHelper.SURFACE_AREA    = 'area';
DataStoreHelper.BAGS            = 'bags';
DataStoreHelper.SNAPPED_TO_ROAD = 'snappedtoroad';
DataStoreHelper.FILLED          = 'filled';
DataStoreHelper.IMAGE_URL       = 'imageurl';
</code></pre>

<p>Note, the <code>sortColumns</code> throws exception iff it's looking for keyword in the spreadsheet columns that doesn't exist. </p>

<p>I begin writing my unit-testing code: </p>

<pre><code>function testDataStoreHelper() {
    // construct some DataStoreHelpers....
    /* NOTE: these should be mocks, as we are trying to test behaviour. Find out how to create mock objects */
    var customDataHelper  = new DataStoreHelper(DataStoreHelper.ADDRESS,
            DataStoreHelper.LATITUDE,
            DataStoreHelper.LONGITUDE,
            DataStoreHelper.FILLED,
            'statechange');
    var testData = {};
    module('testing PotholeDataHelper', {
        setup: function() { 
            // test setup logic goes here....
            testData = tests.DUMMY_DATA;
            testData.noLatLng = [testData.dataRow[0],
                 testData.dataRow[4]   
            ];
            // invoke helper setup here, using testData ... 
            customDataHelper.sortColumns(testData.titleRow);
        }
    })
    test(""attempting to map a keyword in a spreadsheet that doesn't have a corresponding column"", function(assert) { 
        assert.ok(customDataHelper.argIndices.filter(function(value) { return value === -1; }).length,
            ""Somehow, there's one or more mapped keywords that shouldn't be in the spreadsheet"");
    })
}
</code></pre>

<p>As expected for this naive approach, the test(s) fail because exception was thrown in the <code>setup</code> callback. How best to test code like this, where the initialization function could throw?</p>
",https://stackoverflow.com/questions/49162378/qunit-testing-strategy-for-object-with-init-function-that-could-throw,"['google-apps-script', 'qunit']",165,FALSE,0,0
How to configure Jest testing framework for use in Nuxt.js?,"<p>The recommended <a href=""https://github.com/nuxt/create-nuxt-app"" rel=""noreferrer"">Nuxt.js starter template</a> does not suggest any tool for unit tests.</p>

<p>How can we set and use <a href=""https://jestjs.io/"" rel=""noreferrer"">Jest</a> for unit testing in Nuxt.js?</p>
",https://stackoverflow.com/questions/52877541/how-to-configure-jest-testing-framework-for-use-in-nuxt-js,"['javascript', 'unit-testing', 'jestjs', 'nuxt.js']",4543,TRUE,5,1
Angular - Testing Routerguard,"<p>I'm currently struggling on unit testing my <code>canActivate()</code> method from my Routerguard Service. The Service looks as follows:</p>

<pre><code>import {Injectable} from '@angular/core';
import {ActivatedRouteSnapshot, CanActivate, Router} from '@angular/router';
import {AuthService} from '../../auth/auth.service';
import {Observable, of} from 'rxjs';
import {NotificationService} from '../../../../shared/services/notification.service';
import {concatMap, map, take, tap} from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class ProfileGuard implements CanActivate {

  constructor(private auth: AuthService, private router: Router,
              private notification: NotificationService) {
  }

  canActivate(next: ActivatedRouteSnapshot): Observable&lt;boolean&gt; {
    // checks for user if not - page not found
    return this.auth.getUserEntity(next.params.uid).pipe(concatMap(user =&gt; {
      if (user) {
        // checks for permission if not - redirect to user overview
          return this.auth.currentUser.pipe(
            take(1),
            map(current =&gt; this.auth.canEditProfile(current, next.params)),
            tap(canEdit =&gt; {
              if (!canEdit) {
                this.router.navigate([`/profile/${next.params.uid}`]).then(() =&gt;
                  this.notification.danger('Access denied. Must have permission to edit profile.'));
              }
            })
          );
      } else {
        this.router.navigate(['/page-not-found']);
        return of(false);
      }
    }));
  }
}
</code></pre>

<p>It actually looks more complicated than it is:
The first observer checks if there is a user in the db with the params value as unique identifier. The second observer checks then for the permission to edit this user. Now on the unit testing part of things:</p>

<pre><code>describe('RouterGuardService', () =&gt; {

  const routerStub: Router = jasmine.createSpyObj('Router', ['navigate']);
  const authStub: AuthService = jasmine.createSpyObj('AuthService', ['getUserEntity', 'currentUser', 'canEditProfile']);
  const notificationStub: NotificationService = jasmine.createSpyObj('NotificationService', ['danger']);

  function createInputRoute(url: string): ActivatedRouteSnapshot {
    const route: ActivatedRouteSnapshot = new ActivatedRouteSnapshot();
    const urlSegs: UrlSegment[] = [];
    urlSegs.push(new UrlSegment(url, {}));
    route.url = urlSegs;
    route.params = {
      uid: url.replace('/profile/', '')
        .replace('/edit', '')
    };
    return route;
  }

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      providers: [
        {provide: AuthService, useValue: authStub},
        {provide: Router, useValue: routerStub},
        {provide: NotificationService, useValue: notificationStub},
        ProfileGuard]
    });
  });

 it('should redirect to user overview - if has not permission', inject([ProfileGuard], (service: ProfileGuard) =&gt; {
  (&lt;jasmine.Spy&gt;authStub.canEditProfile).and.returnValue(false);
  authStub.currentUser = of(&lt;any&gt;{uid: 'jdkffdjjfdkls', role: Role.USER});
  (&lt;jasmine.Spy&gt;authStub.getUserEntity).and.returnValue(of({uid: 'jdkffdjjfdkls', role: Role.USER}));

  const spy = (&lt;jasmine.Spy&gt;routerStub.navigate).and.stub();
  const notifySpy = (&lt;jasmine.Spy&gt;notificationStub.danger).and.stub();

  const url: ActivatedRouteSnapshot = createInputRoute('/profile/BBB/edit');
  service.canActivate(url).subscribe(res =&gt; {
    console.log(res);
    expect(spy).toHaveBeenCalledWith(['/BBB']);
    expect(notifySpy).toHaveBeenCalledWith('Access denied. Must have permission to edit profile.');
    expect(res).toBe(false);
  }, err =&gt; console.log(err));
}));
});
</code></pre>

<p>But my test does not check my expect methods instead it console logs the error. Can maybe anyone help me on this? </p>
",https://stackoverflow.com/questions/52164199/angular-testing-routerguard,"['angular', 'jasmine', 'karma-jasmine', 'angular-routing', 'angular-test']",433,TRUE,3,1
How to decide whether one class is a cohesive part vs dependency of another class (In terms of unit testing)?,"<p>I'm working on a project that was not designed with unit testing in mind.</p>
<p>Since inside of <code>StartWorking()</code> method I create a new instance of <code>WorkYear</code> and call <code>year.RecalculateAllTime()</code>, is <code>WorkYear</code> class considered to be an external dependency (in terms of unit testing)?</p>
<p>Or since the <code>Employee</code> bound to <code>WorkYear</code> by composition relationship + <code>Employee</code> is meant to perform actions on WorkYears, are the <code>Employee</code> and <code>WorkYear</code> form a cohesive entity where both classes aren't considered as dependencies of one another?</p>
<p>In other words, should <code>StartWorking(...)</code> method be tested in isolation from <code>WorkYear</code> class?</p>
<pre><code>public abstract class Employee
{
    private List&lt;WorkYear&gt; _workYears;
    private readonly IntervalCalculator _intervalCalculator;
    // Other fields...

    protected Employee(IntervalCalculator intervalCalculator)
    {
        _intervalCalculator = intervalCalculator;
        WorkYears = new List&lt;WorkYear&gt;();
    }

    public IEnumerable&lt;WorkYear&gt; WorkYears
    {
        get =&gt; _workYears.AsReadOnly();
        private set =&gt; _workYears = value.ToList();
    }
    // Other properties...
    

    public void StartWorking(DateTime joinedCompany)
    {
        List&lt;PayPeriodInterval&gt; allIntervals = _intervalCalculator.GenerateIntervalsFor(joinedCompany.Date.Year);

        PayPeriodInterval currentInterval = allIntervals.Find(i =&gt; i.StartDate &lt;= joinedCompany &amp;&amp; joinedCompany &lt;= i.EndDate);
        
        PayPeriod firstPeriod = CalculateFirstPeriod(joinedCompany, currentInterval);

        // There is a possibility that employee worked during this year and returned during
        // the same exact year or even month. That is why we are trying to find this year in database:
        WorkYear year = WorkYears.FirstOrDefault(y =&gt; y.CurrentYear == joinedCompany.Year);

        if (year == null)
        {
            // Create new year with current and future periods.
            year = new WorkYear(joinedCompany.Year, this, new List&lt;PayPeriod&gt; {firstPeriod});

            AddYear(year);
        }
        else
        {
            // There is a possibility that employee left and got back during the same period.
            // That is why we should try to find this period so that we don't override it with new one:
            PayPeriod existingPeriod = year.GetPeriodByDate(joinedCompany);

            if (existingPeriod != null)
            {
                var oldCurrentPeriodWorktime = new TimeSpan(existingPeriod.WorktimeHours, existingPeriod.WorktimeMinutes, 0);

                firstPeriod = CalculateFirstPeriod(joinedCompany, currentInterval, oldCurrentPeriodWorktime);
            }

            year.PayPeriods.Add(firstPeriod);
        }

        List&lt;PayPeriodInterval&gt; futureIntervals = allIntervals.FindAll(i =&gt; currentInterval.EndDate &lt; i.StartDate);

        List&lt;PayPeriod&gt; futurePeriods = NewPeriods(futureIntervals);

        year.PayPeriods.AddRange(futurePeriods);

        year.RecalculateAllTime();
    }

    public abstract List&lt;PayPeriod&gt; NewPeriods(List&lt;PayPeriodInterval&gt; intervals);

    public void AddYear(WorkYear workYear) =&gt; _workYears.Add(workYear);

    protected abstract PayPeriod CalculateFirstPeriod(DateTime firstDayAtWork, PayPeriodInterval firstPeriodInerval, TimeSpan initialTime = default);

    // Other methods...

}

public class WorkYear
{
    public WorkYear(int currentYear, Employee employee, List&lt;PayPeriod&gt; periods)
    {
        Employee = employee;
        EmployeeId = employee.Id;
        CurrentYear = currentYear;
        PayPeriods = periods ?? new List&lt;PayPeriod&gt;();

        foreach (PayPeriod period in PayPeriods)
        {
            period.WorkYear = this;
            period.WorkYearId = Id;
        }
    }

    public int EmployeeId { get; }
    public int CurrentYear { get; }
    public Employee Employee { get; }
    public List&lt;PayPeriod&gt; PayPeriods { get; set; }
    
    // Other roperties...


    public void RecalculateAllTime()
    {
        //Implementation Logic
    }
}
</code></pre>
",https://stackoverflow.com/questions/51525564/how-to-decide-whether-one-class-is-a-cohesive-part-vs-dependency-of-another-clas,"['c#', 'unit-testing', 'dependency-injection', 'refactoring', 'decoupling']",51,TRUE,1,1
Is the @SpringBootTest test class correct?,"<p>Is this the correct essence of unit testing? I think i don't understand what should I test. ConverterContext is a strategy class</p>

<pre><code>@SpringBootTest
@ExtendWith(SpringExtension.class)
class ConverterContextTest {

    @Autowired
    private final ConverterContext converterContext;
    @Autowired
    private final ConverterRegisterUserDto created;

    @Autowired
    ConverterContextTest(ConverterContext converterContext, ConverterRegisterUserDto created) {
        this.converterContext = converterContext;
        this.created = created;
    }

    @Test
    void converterContextGivesCorrectConverter(){
        ConverterRegisterUserDto returned = converterContext.getConverter(ConverterRegisterUserDto.class);
        assertEquals(returned, created);
    }

    @Test
    void converterContextGivesIncorrectConverter(){
        ConverterShowUserDto returned = converterContext.getConverter(ConverterShowUserDto.class);
        assertNotEquals(returned, created);
    }
}
</code></pre>
",https://stackoverflow.com/questions/51774996/is-the-springboottest-test-class-correct,"['java', 'spring', 'unit-testing', 'spring-boot', 'junit']",638,TRUE,1,3
Mocha error: undefined is not a constructor (evaluating),"<p>I have this line of code in my unit testing function with Mocha + Chai:</p>

<pre><code>const result = &lt;div&gt;Hello&lt;/div&gt;
getHelloDiv().should.be.equal.to(result)
</code></pre>

<p>But when I run Mocha, I get:</p>

<pre><code>undefined is not a constructor (evaluating 'getHelloDiv().should.be.equal.to(result)')
</code></pre>
",https://stackoverflow.com/questions/49133122/mocha-error-undefined-is-not-a-constructor-evaluating,"['javascript', 'mocha.js', 'chai']",288,TRUE,0,1
How to stub constant functions when using ES Modules with sinon.js?,"<p>With ES Modules, we define some exported functions as <code>const</code> and it is often a standard practice. However, during unit testing, these const functions can't be stubbed out which seems problematic from a unit testing perspective. For example,</p>

<pre><code>import * as fs from 'fs';

import { bindNodeCallback } from 'rxjs';
import { map } from 'rxjs/operators';

// readFile :: string, string =&gt; Observable&lt;string&gt;
export const readFile$ = bindNodeCallback(fs.readFile);

// readJson :: string =&gt; Observable&lt;any&gt;
export function readJson(fileName) {
    return readFile$(fileName, 'utf-8')
        .pipe(map((rawFile) =&gt; JSON.parse(rawFile)));
}
</code></pre>

<p>Now to unit test readJson, I would typically want to stub <code>readFile$</code> function. Unfortunately, following Sinon code doesn't work:</p>

<pre><code>// Setup data - stubs / mocks
const stub = sinon.stub(myFs, 'readFile$').returns(json$);
</code></pre>

<p>Since Sinon is simply changing reference <code>myFs.readFile$</code>, original <code>const</code> still points to the original function which is in turn called by <code>readJson</code> function.</p>

<p><strong>Any suggestion - how can I really stub/mock constant function within the same module?</strong></p>
",https://stackoverflow.com/questions/50460750/how-to-stub-constant-functions-when-using-es-modules-with-sinon-js,"['javascript', 'unit-testing', 'sinon']",5734,TRUE,4,2
Does librdkafka c++ library have a mock server or broker?,"<p>Does librdkafka c++ library have a mock server for unit testing that doesn't require you to spin up a kafka server? If it does not, then is there a lightweight kafka server that is simple and easy to use with it?</p>

<p>Do the examples and unit testing in the librdkafka library require a kafka server stood up to run? If not what is it using? I see it lists localhost:9092, does it spin up its own mock broker when starting?</p>

<p>Thank you!</p>
",https://stackoverflow.com/questions/49056070/does-librdkafka-c-library-have-a-mock-server-or-broker,"['c++', 'unit-testing', 'apache-kafka']",876,TRUE,0,2
"mocha, chai testing for post in nodejs","<p>I am new to unit testing in node.js with sequelize.js. I followed <a href=""https://www.codementor.io/mirko0/how-to-use-sequelize-with-node-and-express-i24l67cuz"" rel=""nofollow noreferrer"">this tutorial to implement the api.</a> It is working fine and I need to test it for unit testing.
First I tried to test post operation for User class. Following code is to be tested using mocha.</p>

<pre><code>// create a user
app.post('/api/users', (req, res) =&gt; {
User.create(req.body)
    .then(user =&gt; res.json(user))
})
</code></pre>

<p>My attempt is as below. </p>

<pre><code>var index = require('../index');
describe('POST testing on user', function () {
 it('should add a row', function (done) {
    index.post('/api/users').send({ 'name': 'he' })
        .end(function (err, res) {
            chai.expect(res.status).to.equal(200);
            done();
        })
 });
});
</code></pre>

<p>Then it will give this error saying index.post is not a function. Where should I get wrong and how can I correct it to execute the test case.</p>
",https://stackoverflow.com/questions/53828625/mocha-chai-testing-for-post-in-nodejs,"['node.js', 'mocha.js', 'sequelize.js', 'chai']",827,TRUE,0,1
Cannot use dotcover with VS2017 (tests are inconclusive),"<p>I am able to run and debug my unit tests using ReSharper but when I try to use dotcover all tests show as inconclusive.</p>

<p>I'm using Visual Studio Enterprise 2017 (v15.9.4) with ReSharper Ultimate 2018.3, and sll the projects in my solution use .NET Framework 4.7.2.</p>

<p>My unit test project uses NUnit and has the following nuget packages installed:</p>

<pre><code>&lt;?xml version=""1.0"" encoding=""utf-8""?&gt;
&lt;packages&gt;
  &lt;package id=""Faker.Net"" version=""1.1.1"" targetFramework=""net472"" /&gt;
  &lt;package id=""FluentAssertions"" version=""5.5.3"" targetFramework=""net472"" /&gt;
  &lt;package id=""Microsoft.AspNet.Razor"" version=""3.2.7"" targetFramework=""net472"" /&gt;
  &lt;package id=""Microsoft.CodeCoverage"" version=""15.9.0"" targetFramework=""net472"" /&gt;
  &lt;package id=""Microsoft.NET.Test.Sdk"" version=""15.9.0"" targetFramework=""net472"" /&gt;
  &lt;package id=""NBuilder"" version=""6.0.0"" targetFramework=""net472"" /&gt;
  &lt;package id=""NUnit"" version=""3.11.0"" targetFramework=""net472"" /&gt;
  &lt;package id=""NUnit3TestAdapter"" version=""3.12.0"" targetFramework=""net472"" /&gt;
  &lt;package id=""RazorEngine"" version=""3.10.0"" targetFramework=""net472"" /&gt;
&lt;/packages&gt;
</code></pre>

<p>These are some of my settings related to tests:</p>

<p><strong>Unit Testing (General)</strong></p>

<p><a href=""https://i.stack.imgur.com/3t8c3.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/3t8c3.png"" alt=""Unit Testing (General) settings""></a></p>

<p><strong>Unit Testing (Test Runner)</strong></p>

<p><a href=""https://i.stack.imgur.com/dZFWx.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/dZFWx.png"" alt=""Test Runner settings""></a></p>

<p>Dotcover (General)</p>

<p><a href=""https://i.stack.imgur.com/F0GXz.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/F0GXz.png"" alt=""Dotcover (General) settings""></a></p>

<p>What I am missing here?</p>
",https://stackoverflow.com/questions/53916632/cannot-use-dotcover-with-vs2017-tests-are-inconclusive,"['unit-testing', 'visual-studio-2017', 'nunit', 'resharper', 'dotcover']",265,FALSE,0,0
Does Shouldly have a statement like Assert.Fail()?,"<p>Most unit testing frameworks have a method like <a href=""https://msdn.microsoft.com/en-us/library/ms243700.aspx"" rel=""nofollow noreferrer"">Fail</a>, which unconditionally throws an assertion exception.</p>

<p>Does Shouldly have this kind of instruction?</p>
",https://stackoverflow.com/questions/48782452/does-shouldly-have-a-statement-like-assert-fail,"['unit-testing', 'shouldly']",458,FALSE,0,0
Configure Mocha unit tests after creating project using @vue/cli 3,"<p>Created a project using vue/cli version 3.2.1.</p>

<p>Trying to configuring Mocha unit testing in vue/cli 3, but no success.</p>

<p>Any help appreciated</p>
",https://stackoverflow.com/questions/53607064/configure-mocha-unit-tests-after-creating-project-using-vue-cli-3,"['vue.js', 'mocha.js', 'vue-cli-3', 'vue-test-utils']",131,FALSE,2,0
Any dataprovider available for specflow,"<p>Looking for data provider as external file like CSV/Excel, similar to MsTest Unit testing framework. Anybody tried or Any implementation available?</p>
",https://stackoverflow.com/questions/53887791/any-dataprovider-available-for-specflow,"['mstest', 'specflow']",103,TRUE,-1,1
What is a reporting framework?,"<p>Reading on <a href=""https://docs.python.org/3/library/unittest.html"" rel=""nofollow noreferrer"">unittest</a> and it says:</p>

<blockquote>
  <p>The unittest unit testing framework was originally inspired by JUnit and has a similar flavor as major unit testing frameworks in other languages. It supports test automation, sharing of setup and shutdown code for tests, aggregation of tests into collections, and independence of the tests from the <strong>reporting framework</strong>.</p>
</blockquote>

<p><em>(emphasis is mine)</em></p>

<p>I of course googled 'What is a reporting framework' expecting a SO question and didn't see one.  So, SO, what is a reporting framework in this context?</p>
",https://stackoverflow.com/questions/49640451/what-is-a-reporting-framework,"['python', 'unit-testing', 'python-unittest']",163,TRUE,1,1
How to avoid &quot;TypeError: Cannot set property&quot; error with jest and babel v7?,"<p>I have a project to be upgraded from babel v6 to babel v7. To make it work is not hard, but I met some problems in unit testing code.</p>

<p>For working code <strong><em>foo.js</em></strong> like below.</p>

<pre><code>import foo from './bar';
export {foo};
</code></pre>

<p>When I try to mock it in unit testing code.</p>

<pre><code>import * as Foo 'path/to/foo.js';
Foo.foo = jest.fn().mockReturnValue('whatever');
</code></pre>

<p>It fails with error:</p>

<pre><code>TypeError: Cannot set property foo of #&lt;Object&gt; which has only a getter
</code></pre>

<p>It turns out that babel v7 do transpilation different from v6. It compiles <strong><em>foo.js</em></strong> into:</p>

<pre><code>""use strict"";

Object.defineProperty(exports, ""__esModule"", {
  value: true
});
Object.defineProperty(exports, ""foo"", {
  enumerable: true,
  get: function get() {
    return _bar.default;
  }
});
</code></pre>

<p>Since <strong><em>foo</em></strong> is defined as a getter-only property of <strong><em>exports</em></strong>, it cannot manipulate the exported <strong><em>foo</em></strong> any more.</p>

<p>For the time being, I just change <strong><em>foo.js</em></strong> to avoid such transpilation. I'm wondering whether this is any babel config to disable such transpilation. Any ideas?</p>
",https://stackoverflow.com/questions/51256801/how-to-avoid-typeerror-cannot-set-property-error-with-jest-and-babel-v7,"['jestjs', 'babeljs']",6044,TRUE,10,2
Mockito: Is it bad practice to spy on a method within the system under test which relies on a HTTP request?,"<p>From reading around, it appears generally bad practice and a sign of code smell when you have to spy on a method that is used by the current method you're unit testing.</p>

<p>For example, I have this method that I'm unit testing:</p>

<pre><code>public MyResponseObject doStuff(MyRequestObject obj) {
    WebTarget tar = getServiceClient().target(obj.toString());
    Response res = tar.path(someURI).request().post(somejson);
    if(response.getStatus() == 200) {
        String jsonResp = response.readEntity(String.class);
        return convertToObj(jsonResp);
    }
}
</code></pre>

<p>One way I'm attempting to solve the above is by </p>

<ol>
<li>Extracting the first two lines (WebTarget, Response) to its own method that returns a Response object.</li>
<li>Creating a mock of Response and stubbing readEntity to return 200 and readEntity to return ""OK""</li>
</ol>

<p>Here's the result:</p>

<pre><code>public MyResponseObject doStuff(MyRequestObject obj) {
    Response res = sendRequest(obj.toString());
    if(response.getStatus() == 200) {
        String jsonResp = response.readEntity(String.class);
        return convertToObj(jsonResp);
    }
}

//extracted method
public Response sendRequest(String json){
    WebTarget tar = getServiceClient().target(someUrl);
    return res = tar.path(someURI).request().post(somejson);
}

//My unit test

//sut is the system under test, setup elsewhere
public void testDoStuff() {
    MyRequestObject request = ...;
    Response respMock = mock(Response.class);
    when(respMock.getStatus()).thenReturn(200);
    when(respoMock.readEntity()).thenReturn(""OK"");
    MyClass spy = spy(sut);
    Mockito.doReturn(respMock).when(spy).sendRequest(requestString);
    MyResponseObject  response = spy.doStuff(request);

    assertEquals(response.toString(),expectedResp);
}
</code></pre>

<p>If I do not stub this out, it attempts to do a real HTTP request and returns an invalid URL error because I'm not supplying a real one - I believe this is what I want because I want my unit tests to be independent of some external system.</p>

<p>Is there a better way I should be going about my unit testing?</p>
",https://stackoverflow.com/questions/53671685/mockito-is-it-bad-practice-to-spy-on-a-method-within-the-system-under-test-whic,"['java', 'unit-testing', 'testing', 'mockito']",2729,TRUE,0,2
Best things to unit test in EpiServer CMS,"<p>I know off the bat this a loaded question and there are probably tons of ideas, but I'm having a tough time online finding examples of the things that are typical to unit test in EPIServer. </p>

<p>I think a good start is if anyone had experience doing unit testing and TDD in a test environment, that will probably get us somewhere.  I'm not familiar with CMS sort of unit testing with blocks and page types etc.. so I'm trying to get some guidance.  </p>

<p>Thank you</p>
",https://stackoverflow.com/questions/51833012/best-things-to-unit-test-in-episerver-cms,"['unit-testing', 'content-management-system', 'tdd', 'episerver']",714,TRUE,0,1
Unit tests for 64 bit division,"<p>I am tasked with unit testing the 64 bit division function (which we have coded in assembler for PPC, not that that should matter).</p>

<p>So far, I have:</p>

<ul>
<li>max value div max value</li>
<li>max value div min value</li>
<li>max value div minus max value</li>
<li>max value div zer0</li>
<li>zero div max value</li>
<li>6 div 2</li>
<li>6 div -2</li>
<li>-6 div 2</li>
<li>-6 div -2</li>
<li>1 div 1</li>
<li>11 div 4</li>
</ul>

<p>What am I missing to give a thorough unit testing of this new code?</p>
",https://stackoverflow.com/questions/53814379/unit-tests-for-64-bit-division,"['unit-testing', '64-bit', 'integer-division']",214,FALSE,0,1
How can we mock cassandra session using golang?,"<p>Q : Is there any way to mock casssandra session using go without actually connecting to any keyspace/schema/DB. Can we mock cassandra for unit testing?</p>
",https://stackoverflow.com/questions/51031167/how-can-we-mock-cassandra-session-using-golang,"['go', 'cassandra', 'gocql']",3011,TRUE,2,2
Karma + Jasmine: Cannot read property &#39;getComponentFromError&#39;,"<p>I am following this tutorial: <a href=""https://angular.io/guide/testing#component-test-scenarios"" rel=""noreferrer"">https://angular.io/guide/testing#component-test-scenarios</a> for karma+jasmine unit testing. Here my code:</p>

<pre><code>import { AppComponent } from ""./app.component"";
import { ComponentFixture, TestBed } from ""@angular/core/testing"";

describe('AppComponent', () =&gt; {

let component: AppComponent;
let fixture:   ComponentFixture&lt;AppComponent&gt;;
let h1:        HTMLElement;

beforeEach(() =&gt; {
  TestBed.configureTestingModule({
    declarations: [ AppComponent ],
  });
  fixture = TestBed.createComponent(AppComponent);
  component = fixture.componentInstance; 
  h1 = fixture.nativeElement.querySelector('h1');
});

it('should display original title', () =&gt; {
    expect(h1.textContent).toContain(""Ciao"");
  });

});
</code></pre>

<p>When I run the test I get the following exception:</p>

<pre><code> TypeError: Cannot read property 'getComponentFromError' of null
    at TestBed._initIfNeeded (D:/Users/apwzp/AppData/Local/Temp/karma-typescript-bundle-11944DDd01l2f5Y0P.js:1020:52)
    at TestBed.createComponent (D:/Users/apwzp/AppData/Local/Temp/karma-typescript-bundle-11944DDd01l2f5Y0P.js:1174:14)
    at Function.TestBed.createComponent (D:/Users/apwzp/AppData/Local/Temp/karma-typescript-bundle-11944DDd01l2f5Y0P.js:876:29)
    at UserContext.&lt;anonymous&gt; (assets/app/app.component.spec.ts:14:20 &lt;- assets/app/app.component.spec.js:13:37)
    at ZoneDelegate.invoke (node_modules/zone.js/dist/zone.js:388:26)
    at ProxyZoneSpec.onInvoke (node_modules/zone.js/dist/proxy.js:79:39)
    at ZoneDelegate.invoke (node_modules/zone.js/dist/zone.js:387:32)
    at Zone.run (node_modules/zone.js/dist/zone.js:138:43)
    at UserContext.&lt;anonymous&gt; (node_modules/zone.js/dist/jasmine-patch.js:106:34)
</code></pre>

<p>Does anyone know how to solve it?</p>
",https://stackoverflow.com/questions/49068013/karma-jasmine-cannot-read-property-getcomponentfromerror,"['angular', 'unit-testing', 'jasmine', 'karma-runner', 'zone.js']",19677,TRUE,12,3
Unit test DateTime logic,"<pre><code>public bool IsBoundaryDate(DateTime deleteDate)
{
    var isBoundaryDate = false; 

    var daysList = new List&lt;int&gt;{1};

    foreach(var boundary in daysList )
    {
        var daysLeft = (deleteDate - DateTime.UtcNow).Days;

        if (daysLeft == boundary)
        {
            isBoundaryDate = true;
            break;
        }
    }

    return isBoundaryDate;
}
</code></pre>

<p>So while doing unit testing, my code looks like this:</p>

<pre><code>public void IsBoundaryDate_ReturnFalse_WhenDateIsNotInBoundaryDays()
{
    var boundaryDaysFake = new List&lt;int&gt;
    {
        1
    };

    var deleteDate = DateTime.UtcNow.AddDays(1).AddMinutes(1);
    var sut = new BoundaryDateChecker(boundaryDaysFake);

    Assert.IsTrue(sut.IsBoundaryDate(deleteDate));
}
</code></pre>

<p>How I can avoid hardcoding <code>AddMinutes(1)</code>, because hardcoding seems like a bad idea for a test method</p>
",https://stackoverflow.com/questions/50258875/unit-test-datetime-logic,"['c#', 'unit-testing']",66,FALSE,1,0
SpringBoot Junit Testing RestControllers,"<p>I need to know if testing only restControllers in spring boot application is enough in unit testing or better to test all the classes independently?.  </p>
",https://stackoverflow.com/questions/51751215/springboot-junit-testing-restcontrollers,"['spring', 'testing', 'junit', 'spring-restcontroller']",887,TRUE,0,2
Failed: Can&#39;t resolve all parameters for DecoratorFactory: (?),"<p>I'm facing the below exception when I run <code>ng test</code> for unit testing
<code>Failed: Can't resolve all parameters for DecoratorFactory: (?)</code></p>

<p>Facing the exception in the below <code>specs.ts</code> file. I'm using ngx-bootstrap components in my UI</p>

<pre><code>describe('DirectoryComponent', () =&gt; {
    let component: DirectoryComponent;
    let fixture: ComponentFixture&lt;DirectoryComponent&gt;;

    beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
            declarations: [ DirectoryComponent ],
            imports: [ FormsModule,TypeaheadModule,BsDatepickerModule, CarouselModule, RouterTestingModule,ModalModule.forRoot() ],
            providers:[GlobalService, ServerService , OtherservicesService,MyModalsService,Pipe],
        }).compileComponents();
    }));

    beforeEach(() =&gt; {
        fixture = TestBed.createComponent(DirectoryComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should create', () =&gt; {
        expect(component).toBeTruthy();
    });
});
</code></pre>
",https://stackoverflow.com/questions/51040129/failed-cant-resolve-all-parameters-for-decoratorfactory,"['angular', 'typescript', 'karma-jasmine']",105,FALSE,1,0
Writing an unit test for a service,"<p>Trying PHP unit testing. I have read the <a href=""https://phpunit.readthedocs.io/en/7.4/index.html"" rel=""nofollow noreferrer"">PHPUnit documentation</a> and watched <a href=""https://www.youtube.com/watch?v=URSWYvyc42M"" rel=""nofollow noreferrer"">Sandi Metz' video about unit testing</a>, but I have difficulties to apply all this in a real world scenario.</p>

<p>I decided to unit test my <code>CallReceiver</code> class which takes some parameters and passes the entity to a repository for saving:</p>

<pre><code>final class CallReceiver {

   private $CallRepository;

   public function __construct( CallRepository $CallRepository ) {

    $this-&gt;CallRepository = $CallRepository;
   }

   public function receive( string $uuid, string $Destination, string $Caller ) : void {

    $Call = Call::receive(
        CallId::createValidated( $uuid ),
        DestinationNumber::createValidated( $Destination ),
        $Caller
    );

    $this-&gt;CallRepository-&gt;save( $Call );
   }

}
</code></pre>

<p>According to Sandi, I would have to test that the <code>Call</code> entity gets sent to <code>CallRepository</code> (outgoing command). So I suppose I will have to mock both <code>Call</code> and <code>CallRepository</code>:</p>

<pre><code>public function testReceive() {

    $CallRepository = $this-&gt;getMockBuilder(CallRepository::class)
        -&gt;setMethods(['save'])
        -&gt;getMock();

    $Call = $this-&gt;createMock(Call::class);

    $CallRepository-&gt;expects($this-&gt;once())
        -&gt;method('save')
        -&gt;with($this-&gt;equalTo($Call));

    $CallReceiver = new CallReceiver( $CallRepository );

    $CallReceiver-&gt;receive( '123', '456', '789' );

}
</code></pre>

<p>But that doesn't really work. How would I write a meaningful test for the <code>CallReveiver::receive</code> method?</p>
",https://stackoverflow.com/questions/53630207/writing-an-unit-test-for-a-service,"['php', 'unit-testing', 'service', 'phpunit', 'repository']",42,FALSE,0,0
How to implement unit test program using golang?,"<p>I saw many blogs where they write how to do unit testing but I will understand theory portion and not understand how to implement the test case can anyone will tell me that how will I implement the first test case for more understanding with the unit testing. Here I'm implementing the small program for average:-</p>

<p><strong>Folder structure is:-</strong></p>

<pre><code>main.go
average(Folder)----&gt; math_test.go
</code></pre>

<p>code in the both file is:-</p>

<p><strong>main.go</strong></p>

<pre><code> package main

 import ""fmt""
 import ""testcases/average""

 func main() {
    xs := []float64{1,2,3,4}
    avg := m.Average(xs)
    fmt.Println(avg) 
 }
</code></pre>

<p><strong>math_test.go</strong></p>

<pre><code>package math

import ""testing""

func TestAverage(t *testing.T) {
  var v float64
  v = Average([]float64{1,2})
  if v != 1.5 {
    t.Error(""Expected 1.5, got "", v)
  }
 }
</code></pre>

<blockquote>
  <p>ERROR:-  go build testcases/average: no non-test Go files in /home/iron/go/src/testcases/average</p>
</blockquote>

<p>Helping me I'm very thankful to you.</p>
",https://stackoverflow.com/questions/51413947/how-to-implement-unit-test-program-using-golang,"['unit-testing', 'testing', 'go']",655,TRUE,0,2
What is the proper way to test types?,"<p>I am using Jest for unit-testing and I want to test if the variable is an Object. Is there a better way to do it?</p>

<pre><code>it('should throw an Error if options is not an Object', () =&gt; {
  const error = 'Options should be an Object.'

  expect(() =&gt; new Foo([])).toThrow(error)
  expect(() =&gt; new Foo(123)).toThrow(error)
  expect(() =&gt; new Foo('')).toThrow(error)
  expect(() =&gt; new Foo(true)).toThrow(error)
  expect(() =&gt; new Foo(NaN)).toThrow(error)
  expect(() =&gt; new Foo(null)).toThrow(error)
  expect(() =&gt; new Foo(() =&gt; {})).toThrow(error)
})
</code></pre>
",https://stackoverflow.com/questions/51688679/what-is-the-proper-way-to-test-types,"['javascript', 'unit-testing', 'testing', 'ecmascript-6', 'jestjs']",31,TRUE,0,1
Testing Google Apps Script web app with QUnit,"<p>I have a Google Apps Script web app, that previously worked, but when I tried to add some code to the ""server-side"", it broke the app. I wish to go back in and do some unit testing and possibly a bit of regression testing (even though my manual regression testing just failed), on the different functions and modules of this app. </p>

<p>I stumbled upon <a href=""https://github.com/simula-innovation/qunit/tree/gas/gas"" rel=""nofollow noreferrer"">this library for GAS unit testing</a> and a <a href=""http://www.tothenew.com/blog/how-to-test-google-apps-script-using-qunit/"" rel=""nofollow noreferrer"">tutorial for using the library</a>. Problem is that, to actually see the results of the test, you must implement a <code>function doGet(e)</code> for testing. </p>

<p>This app I'm trying to unit-test, being a web app, already has that function. Its implementation is as follows: </p>

<pre><code>function doGet(e) {
  return HtmlService.createTemplateFromFile(
    'potholeMap'
  ).evaluate()
   .setTitle('Pothole Map')
   .setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
</code></pre>

<p>When I bring in the QUnit library dependency, and refactor it to allow QUnit testing, such as below: </p>

<pre><code>function doGet(e) {
    var TESTING = true; 
    if (TESTING)
    {
        QUnit.urlParams(e.parameter);
        QUnit.load(function test() {});
        return QUnit.getHtml();
    }

    return HtmlService.createTemplateFromFile(
        'potholeMap'
    ).evaluate()
        .setTitle('Pothole Map')
        .setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
</code></pre>

<p>I get this error when I try to run it: <code>Authorization is required to perform that action.</code> How do I fix this so that I can do unit testing in the project, as well as run it as web app?</p>
",https://stackoverflow.com/questions/49054019/testing-google-apps-script-web-app-with-qunit,"['google-apps-script', 'testing', 'web-applications', 'qunit']",933,TRUE,0,2
io.objectbox.exception.DbDetachedException: Cannot resolve relation for detached entities,"<p>While unit testing the class that is working with ObjectBox database I got this error: </p>

<blockquote>
  <p>io.objectbox.exception.DbDetachedException: Cannot resolve relation for detached entities</p>
</blockquote>

<p>I have implemented all the necessary data into my Entity class for unit testing on macOs. So the entity relation with a to-one and a to-many relation pointing to itself.</p>

<pre><code>@Entity
data class Category(
    @Id var id: Long? = 0,
    var title: String?,
    @JvmField var parent: ToOne&lt;Category&gt;? = null,
    @JvmField @Backlink(to = ""parent"") var subCategories: ToMany&lt;Category&gt;? = null){

    constructor(): this(id = 0, title =  """", parent = null, subCategories = null)
    constructor(title: String): this(id = 0, title = title, parent = null, subCategories = null)

    // normally transformer would add field, but need to manually for local unit tests
    @JvmField @Transient var __boxStore: BoxStore? = null

    init{
        if(parent == null) parent = ToOne(this, Category_.parent)
        if(subCategories == null) subCategories = ToMany(this, Category_.subCategories)
    }
}
</code></pre>

<p>Unit test is very simple:</p>

<pre><code>public class CategoryModelDataMapperTest {

    private CategoryModelDataMapper categoryModelDataMapper = new CategoryModelDataMapper();

    @Before
    public void setUp() throws Exception {
        categoryModelDataMapper = new CategoryModelDataMapper();
    }

    @Test
    public void testShouldTransformDomainModelWithoutParentToEntityCorrectly() throws Exception{
        final Category category = new Category(10L, ""Bar"", null, null);
        final CategoryModel categoryModel = categoryModelDataMapper.transform(category);

        assertEquals((Long) 10L, categoryModel.getId());
        assertEquals(""Bar"", categoryModel.getTitle());
        assertNull(categoryModel.getParent());
        assertNotNull(categoryModel.getSubCategories());
        assertTrue(categoryModel.getSubCategories().isEmpty());
    }
}
</code></pre>

<p>And actual class that I am testing is normal mapper:</p>

<pre><code>class CategoryModelDataMapper: BaseMapper&lt;Category, CategoryModel&gt;{

    override fun transform(from: Category): CategoryModel {
        val toModel = CategoryModel()
        toModel.id = from.id
        toModel.title = from.title

        toModel.parent = from.parent?.target?.let { transform(it) }

        from.subCategories?.let {
            it.forEach{ toModel.subCategories?.add( transform(it)) }
        }

        return toModel
    }

    override fun transform(fromList: MutableList&lt;Category&gt;): MutableList&lt;CategoryModel&gt; {
        val toList = ArrayList&lt;CategoryModel&gt;(fromList.size)
        return fromList.mapTo(toList) { transform(it) }
    }
}
</code></pre>

<p>I have some other tests that are testing the <code>parent</code> and <code>subCategories</code> in more detail, but I got the same error in all of the tests. 
Before it was working fine, but that something went wrong.</p>
",https://stackoverflow.com/questions/49358532/io-objectbox-exception-dbdetachedexception-cannot-resolve-relation-for-detached,['objectbox'],771,TRUE,3,1
Injecting service in angular directive unit test,"<p>I'm trying to first fix the basic unit test that cli wrote for me. I'm new to unit testing so here's the code</p>

<pre><code>import { MyDirective } from './my.directive';

describe('MyDirective', () =&gt; {
  it('should create an instance', () =&gt; {
    const directive = new MyDirective(); // it throws error here
    expect(directive).toBeTruthy();
  });
});
</code></pre>

<p>I need to inject ElementRef inside MyDirective</p>
",https://stackoverflow.com/questions/52965567/injecting-service-in-angular-directive-unit-test,"['angular', 'unit-testing', 'dependency-injection', 'karma-jasmine', 'angular-directive']",1716,TRUE,3,1
Unit Test IActionResult with TempData,"<p>I was just wondering how can you do unit testing with TempData without using MOQ or doing anything complex? Really appreciate your help</p>

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

<pre><code>public IActionResult ProjectsList(string selectedOrg)
    {

        TempData[""model""] = selectedOrg;
        return View(""Index"");

    }
</code></pre>
",https://stackoverflow.com/questions/53020178/unit-test-iactionresult-with-tempdata,"['unit-testing', 'model-view-controller', 'asp.net-core']",60,FALSE,0,1
How do I unit test with a subscribe in Angular5?,"<pre><code>import { Component, Input, OnInit } from '@angular/core';
import {DataplansDetails} from '../../models/dataplans-details';
import * as _ from ""lodash"";

@Component({
  selector: 'jsonform',
  templateUrl: './jsonform.component.html',
  styleUrls: ['./jsonform.component.scss']

})
export class JsonformComponent implements OnInit {
  @Input() dataplanDetails: any;
  public layout: any = [];
  public schema: any = {};

  ngOnInit() {
    this.dataplanDetails.subscribe(res =&gt; {
      const fileSchema = JSON.parse(res.details.submissionFileSchema)

      const formLayout = fileSchema[""layout""]
      this.schema = {
        type: ""object"",
        properties: fileSchema[""properties""]
      }

      const schemaKeys = Object.keys(this.schema[""properties""])
</code></pre>

<p>This is my component. It has a <code>subscribe</code> that I'm having trouble unit testing. My test includes:</p>

<pre><code>fdescribe('JsonformComponent', () =&gt; {
  let component: JsonformComponent;
  let fixture: ComponentFixture&lt;JsonformComponent&gt;;
  const mockObservable = new Subject();

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA],
      providers: [
        {provide: Store, useClass: StoreStub}
      ],
      imports: [],
      declarations: [JsonformComponent]
    }).compileComponents();
  }));

  beforeEach(async(() =&gt; {
    fixture = TestBed.createComponent(JsonformComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    component['dataplanDetals'] = mockObservable
  }));

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });

  fit('should not set layout if there are no properties', () =&gt; {
    mockObservable.next({test: 'data'})


    component.parseSchema('{""layout"": [], ""properties"": {}}')
    // component.properties = false
    expect(component.schema).toEqual({})
    expect(component.layout).toEqual([])
  })

  // it('should set the layout to have the keys', () =&gt; {
  //   component.properties = {}
  // })
});
</code></pre>

<p>I'm getting an error: <code>Failed: undefined is not an object (evaluating 'this.dataplanDetails.subscribe')</code></p>

<p>How do I trigger the subscribe from the test?</p>
",https://stackoverflow.com/questions/49736769/how-do-i-unit-test-with-a-subscribe-in-angular5,"['angular', 'unit-testing', 'observable']",517,TRUE,2,2
prevent component scan for unit test,"<p>I have a class as following</p>

<pre><code>@ComponentScan(basePackages = { ""com.abc.def"" })
@Configuration
public class ClassUnderTest(){

    @Bean
    public void createSomeBean()
    {
    }   
}
</code></pre>

<p>I am unit testing this class using </p>

<pre><code>@RunWith(SpringRunner.class)
@ContextConfiguration(classes = ClassUnderTest.class)
public class someUnitTest()
{}
</code></pre>

<p>How do I prevent component scan from happening when creating a test context from ClassUnderTest</p>
",https://stackoverflow.com/questions/52418941/prevent-component-scan-for-unit-test,"['spring', 'spring-boot', 'spring-test']",353,FALSE,1,1
How to write unit test,"<p>I need to write some unit tests on this source code. </p>

<pre><code>public class PagedCollection&lt;T&gt; : ReadOnlyCollection&lt;T&gt;, IPagedCollection&lt;T&gt;
{
    public int CurrentPage { get; }
    public int TotalPages { get; }
    public int PageSize { get; }
    public int TotalCount { get; }
    public bool HasPrevious =&gt; CurrentPage &gt; 1;
    public bool HasNext =&gt; CurrentPage &lt; TotalPages;

    public PagedCollection(ICollection&lt;T&gt; items, int count, int pageNumber, int pageSize) : base(items.ToList())
    {
        EnsureArg.IsGte(count, 0, nameof(count));
        EnsureArg.IsGt(pageNumber, 0, nameof(pageNumber));
        EnsureArg.IsGt(pageSize, 0, nameof(pageSize));

        TotalCount = count;
        CurrentPage = pageNumber;
        PageSize = pageSize;
        TotalPages = (int)Math.Ceiling(count / (double)pageSize);
    }
}
</code></pre>

<p>And I have 1 more question about unit testing: what is difference between mock and stub?</p>
",https://stackoverflow.com/questions/51271601/how-to-write-unit-test,"['c#', 'unit-testing']",109,FALSE,0,0
React and Jest: How to mock implementation of member function,"<p>I'm doing some api fetching in my component. When doing unit testing, I'd like to mock the implementation of certain member functions:</p>

<pre><code>//component.js
class Foo extends Component {
  prepareData() {
    getSthFromApi().then(getMoreFromApi).then(val=&gt;this.setState({val}));
  }
  componentDidMount() {
    this.prepareData();
  }
}
//test.js
//What should this be?
Foo.prepareData = jest.fn().mockImplementation(() =&gt; {
  this.setState({val:1});
})
const comp = shallow(&lt;Foo /&gt;);
</code></pre>

<p>How should I do it?</p>
",https://stackoverflow.com/questions/51561080/react-and-jest-how-to-mock-implementation-of-member-function,"['reactjs', 'jestjs', 'enzyme']",2117,TRUE,0,2
Jenkins integration with JestJS,"<p>I had to fix my previous question. How can we integrate Jenkins with Jest for unit testing</p>

<p>And  what is the best JavaScript Testing framework for beginners </p>
",https://stackoverflow.com/questions/53377101/jenkins-integration-with-jestjs,"['javascript', 'unit-testing', 'jenkins', 'frameworks', 'jestjs']",92,FALSE,0,0
How can I unit test a function that uses promises and event emitters in Node.js?,"<p>My question is about unit testing with promises and event emitters in Node.js. I am using the jasmine framework if that matters. </p>

<p>The code below uses the https module of Node.js to send a request to an API. The API will return JSON. The JSON from the API is the ""rawData"" variable in the code below.</p>

<p>I want to unit test that the function returns JSON (and not a JavaScript object).</p>

<p>I have unsuccessfully tried several approaches to unit testing that aspect of this function:</p>

<p>1) I tried spying on the Promise constructor so that it would return a fake function which would simply return a JSON string.</p>

<p>2) I have tried spying on the .on('eventType', callback) function of EventEmitters in Node.js to fake a function that returns JSON.</p>

<p>My question is: are either of the two approaches above possible and/or recommend for accomplishing my goal? Is there a different approach to isolating the http request and emitting of events from my unit test objective? Do I need to rewrite this function to facilitate easier unit testing? </p>

<pre><code> const https = require('https');

 function getJSON() {
  return new Promise((resolve, reject) =&gt; {
    const request = https.get(someConfig);
    request.on('response', resolve);
  })
  .then(msg =&gt; {
    return new Promise((resolve, reject) =&gt; {
      let rawData = '';
      msg.on('data', chunk =&gt; { rawData += chunk });
      msg.on('end', () =&gt; {
        resolve(rawData);
      });
    });
  })
  .then(json =&gt; {
    JSON.parse(json);
    return json;
  })
}
</code></pre>
",https://stackoverflow.com/questions/49622026/how-can-i-unit-test-a-function-that-uses-promises-and-event-emitters-in-node-js,"['javascript', 'node.js', 'unit-testing', 'promise', 'eventemitter']",1654,TRUE,3,3
Stubbing a function in Golang,"<p>There's a function that keeps coming up in the code that I'm responsible for unit-testing (that hasn't even been tested yet), defined as follows: </p>

<pre><code>//Get Retreives an error with the given access code.
func Get(code AccessCode) *ErrorSt {
    if err, ok := Errors[code]; ok {
        err.Stack = utilityCore.GetCleanStack(logger.Instance.GetProjectNames())
        return &amp;err
    }
    err := NewError(string(ACPanic), fmt.Sprintf(""Error '%s' can't be retreived."", code), ESSystem, SError)
    return err
}
</code></pre>

<p>It is invoked by a couple of the methods that I have tried to test thus far. My instinct is to either stub or <a href=""https://godoc.org/github.com/nyarly/spies"" rel=""nofollow noreferrer"">spy on</a> the function, but this fails. </p>

<p>This function is used in many places throughout my employer's APIs, thus I cannot change it (if I do, it will break a lot of things). Is there any way to do true unit testing and test-double it out?</p>

<p>My spy attempt: </p>

<pre><code>type ErrorSpy struct {
    spies.Spy
}

func (spy *ErrorSpy) Get(code AccessCode) *ErrorSt {
    res := spy.Called(code)

    return res.Get(0).(*ErrorSt)
}
</code></pre>
",https://stackoverflow.com/questions/51935136/stubbing-a-function-in-golang,"['unit-testing', 'go']",1275,TRUE,2,1
Running jest with bootstrap-vue,"<p>I've been working with vuejs and <a href=""https://bootstrap-vue.js.org/"" rel=""noreferrer"">bootstrap-vue</a> lately.
Decided to add unit testing to my project.</p>
<p>I'm not realy familiar with unit testing so I'm trying anything I could find to understand how it works.</p>
<p><em><strong>Login.specs.js</strong></em></p>
<pre><code>import { shallowMount, mount } from '@vue/test-utils'
import Login from '@/components/auth/Login.vue'

describe('Login.vue', () =&gt; {
  it('is a Vue instance', () =&gt; {
   const wrapper = mount(Login, {
    mocks: {
     $t: () =&gt; 'Connexion' // i18N
    }
   })
  const h2 = wrapper.find('h2')
  expect(h2.text()).toBe('Connexion')
 })
})
</code></pre>
<p><em><strong>Login.vue</strong></em></p>
<pre><code>&lt;b-row align-h=&quot;center&quot;&gt;
 &lt;b-col class=&quot;text-center&quot;&gt;
  &lt;h2&gt;{{ $t('login.connection') }}&lt;/h2&gt;
 &lt;/b-col&gt;
&lt;/b-row&gt;
</code></pre>
<p>Everything seems ok with the test.
But I got these wannings and could find a way to actualy fix it.</p>
<blockquote>
<p>[Vue warn]: Unknown custom element:  - did you register the component correctly? For recursive components, make sure to provide the &quot;name&quot; option.</p>
<p>[Vue warn]: Unknown custom element:  - did you register the component correctly? For recursive components, make sure to provide the &quot;name&quot; option.</p>
</blockquote>
<p>So I looked around and it seems like I need to add these child components to the father.</p>
<p>Here is the <a href=""https://bootstrap-vue.js.org/docs/components/layout"" rel=""noreferrer"">documentation</a> for these components.</p>
<p>I'm also adding my config files (There're the same as the vue-cli 3 generates them)</p>
<p><em><strong>jest.congif.js</strong></em></p>
<pre><code>module.exports = {
  moduleFileExtensions: [
  'js',
  'jsx',
  'json',
  'vue'
 ],
 transform: {
  '^.+\\.vue$': 'vue-jest',
  '.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$': 'jest- transform-stub',
  '^.+\\.jsx?$': 'babel-jest'
 },
 moduleNameMapper: {
  '^@/(.*)$': '&lt;rootDir&gt;/src/$1'
 },
 snapshotSerializers: [
  'jest-serializer-vue'
 ],
 testPathIgnorePatterns: [ //I've added this one, not sure if usefull
  '&lt;rootDir&gt;/node_modules'
 ],
 testMatch: [
  '**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__tests__/*.(js|jsx|ts|tsx)'
 ]
}
</code></pre>
",https://stackoverflow.com/questions/51536537/running-jest-with-bootstrap-vue,"['javascript', 'vuejs2', 'jestjs', 'vue-cli', 'bootstrap-vue']",10279,TRUE,19,5
Disable joblib.memory caching globally during unittest,"<p>I use the <code>joblib.Memory</code> module to cache some functions within several modules. The cache is initialized within modules and classes separately.</p>

<p>Module1:</p>

<pre><code>memory = Memory(location='/cache/')
@memory.cache
def heavy_function(...)
    .....
</code></pre>

<p>Module2:</p>

<pre><code>memory = Memory(location='/cache/')
@memory.cache
def heavy_function2(...)
    .....
</code></pre>

<p>Module3:</p>

<pre><code>import Module1
import Module2

def heavy_function3(...)
    Module1.heavy_function1(...)
    Module1.heavy_function1(...)
    .....
</code></pre>

<p>Now I have a unit testing script and I want to disable the usage of the cache globally during the unit testing to make sure everything is correctly computed.
Is this possible without manually disabling it for each module via
<code>Module1.memory.cachedir=None</code> or without deleting the cachedir?</p>

<p>My current solution just patches each memory call manually</p>

<p>unittest1:</p>

<pre><code>from joblib import Memory
import Module1
Module1.memory = Memory(location=None)
...
unittest.run()
</code></pre>

<p>unittest3:</p>

<pre><code>from joblib import Memory
import Module1 # need to import module 1 just to disable its memory
import Module2 # need to import module 2 just to disable its memory
import Modul3
Module1.memory = Memory(location=None)
Module2.memory = Memory(location=None)
...
unittest.run()
</code></pre>

<p>The more modules I create, the more manual patching up of the Memory I need. I thought there might be a better solution. One work-around is proposed by me below.</p>
",https://stackoverflow.com/questions/53318600/disable-joblib-memory-caching-globally-during-unittest,"['python', 'unit-testing', 'caching', 'joblib']",749,TRUE,5,3
How do you define functional testing with two popular and seemingly contradictory explanations?,"<p>I've been researching the definition of functional testing and can't come across a concrete explanation and would appreciate some additional info to help reconcile this.</p>

<p>The two main ideas I have come across are:</p>

<ol>
<li>Functional Testing as a Testing Type and is comprised of the following Testing Levels: Unit Testing, Integration Testing, System Testing and Acceptance Testing.</li>
</ol>

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

<ol start=""2"">
<li>Functional Testing as a separate level from Unit Testing and Integration Testing (sometimes a subset of System Testing other times precedes it) that tests the product end-to-end with a Black-box approach. Purpose is to verify all functional specifications defined.</li>
</ol>

<p><a href=""https://i.stack.imgur.com/NIMIM.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/NIMIM.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/48614190/how-do-you-define-functional-testing-with-two-popular-and-seemingly-contradictor,"['unit-testing', 'testing', 'functional-testing', 'system-testing']",1375,TRUE,1,2
Jasmine unit test for the following function in my angularjs controller. I am using TS with angularJS,"<pre><code> public getTxFilterData(): any {
        this.txRejectsService.showLoader = true;
        var momentObj: moment.MomentStatic = moment;
        this.$http({
            url: txRejectsReadApi,
            method: ""GET"",
            params: {
                startDate: momentObj(this.selectedStartDate).format(""MM/DD/YYYY""),
                endDate: momentObj(this.selectedEndDate).format(""MM/DD/YYYY""),
                sourceSystem: this.selectedSourceSystem.Name || '',
                eventType: this.selectedEventType.Id || ''
            }
        }).then((response) =&gt; {
            var localTxData = this.convertUTCDateTimeToLocal(response.data);
            this.populateGridData(localTxData);
            this.txRowSelected = false;
            this.txRejectsService.showLoader = false;
        }, (error) =&gt; {
             this.notificationService.error({
                 message: ""Failed to load data. Try again.""
             });
            this.txRejectsService.showLoader = false;
            this.$log.error(`error ${error}`);
            this.$log.info(error);
        })
    }
</code></pre>

<p>I want to specifically test the .then() block and error() block of the $http inside the function. I am new to unit testing using Jasmine, apology for any errors.</p>
",https://stackoverflow.com/questions/53007722/jasmine-unit-test-for-the-following-function-in-my-angularjs-controller-i-am-us,"['angularjs', 'unit-testing', 'jasmine', 'karma-jasmine', 'angular-services']",16,FALSE,0,0
How to see the output of Python&#39;s hypothesis library,"<p>When using the <a href=""https://hypothesis.readthedocs.io/en/latest/index.html"" rel=""noreferrer"">hypothesis</a> library and performing unit testing, how can I see what instances the library is trying on my code?</p>

<p>Example</p>

<pre><code>from hypothesis import given
import hypothesis.strategies as st

@given(st.integers())
def silly_example(some_number):
    assert some_number &gt; 0
</code></pre>

<p>The question is: how do I print / see the <code>some_number</code> variable, generated by the library?</p>
",https://stackoverflow.com/questions/53072398/how-to-see-the-output-of-pythons-hypothesis-library,"['python', 'python-hypothesis']",1840,TRUE,7,4
Mock a provider class to return response and handle promise - Unit Testing with Jasmine and Karma with Ionic 3,"<p>Am a newbie in Unit Testing. I started to write Unit Testing for my Ionic 3 Application using Karma and Jasmine. I followed blogs to get the configurations set and successfully tested the initialisation of App component. I also use <a href=""https://www.npmjs.com/package/ionic-mocks"" rel=""nofollow noreferrer"">ionic-mock</a> to have the mocks.</p>

<p>My first page has a http service call which invokes a provider. Below is the call.</p>

<pre><code>this.portalList.getListInformation().then(data =&gt; {
   this.infolist = data;
});
</code></pre>

<p>And in provider :</p>

<pre><code>return new Promise((resolve,reject) =&gt; {
  this.http.get(url).subscribe(
    data =&gt; {
      const response: any = data;
      resolve(response);
    },
    (error) =&gt; {
      reject(error);
    })
});
</code></pre>

<p>And my .spec.ts is here.</p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By }           from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { Portal } from './portal';
import { IonicModule, Platform, NavController, NavParams} from 'ionic-angular/index';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { PortalList } from '../../providers/PortalList/PortalList';
import { HttpClient, HttpHandler } from '@angular/common/http';

import {
  PlatformMock,
  AppsMock,
  NavParamsMock,
  NavMock,
  PortalListMock
} from '../../../test-config/mocks-ionic';

describe(' Portal Page', () =&gt; {
  let de: DebugElement;
  let comp: Portal;
  let fixture: ComponentFixture&lt;Portal&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [Portal],
      imports: [
        IonicModule.forRoot(Portal)
      ],
      providers: [
        Config,HttpClient, HttpHandler
        { provide: App, useClass: AppsMock},
        { provide: Platform, useClass: PlatformMock},
        { provide: NavParams, useClass: NavParamsMock},
        { provide: NavController, useClass: NavMock},
        { provide: PortalList, useClass: PortalListMock}
      ]
    });
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(Portal);
    comp = fixture.componentInstance;
    de = fixture.debugElement.query(By.css('label'));
  });

  it('should create component', () =&gt; expect(comp).toBeDefined());

});
</code></pre>

<p>I provided the Mock for the provider. </p>

<pre><code>export class PortalListMock {
  public infoList = [{name: ""MAC"", region: ""West""}];

  public _getPortal(): any { return {} };
  public getListInformation() { return this.infoList; }

  return;
}
</code></pre>

<p>On executing <code>**npm test**</code>, it gives error like <code>**this.portalList.getListInformation().then is not a function**</code>.</p>

<p>How to mock the promise of the provider http request. or how to overcome from this issue.</p>
",https://stackoverflow.com/questions/52762975/mock-a-provider-class-to-return-response-and-handle-promise-unit-testing-with,"['angular', 'unit-testing', 'ionic3', 'karma-jasmine', 'jasmine2.0']",1052,TRUE,0,1
What is `-m` stands for in `python -m unittest`?,"<p>What is <code>-m</code> stands for in <code>python -m unittest</code>? The unittest unit testing framework has other command line options like <code>-v -b -c -t</code> but wondering what does <code>-m</code> stands for? Is it part of unittest or other python command line option?</p>
",https://stackoverflow.com/questions/48482919/what-is-m-stands-for-in-python-m-unittest,"['python', 'python-unittest']",1718,TRUE,3,1
Automapper mocking,"<p>I am using Automapper and Unity DI in my webapi. How can I write Automapper so that i can mock it for my unit testing? I am using Automapper 7.0</p>

<pre><code>public class AutomapperConfiguraiton: Profile
{           
 public static void Configure()
 {
  Mapper.Initialize(cfg =&gt;{cfg.CreateMap&lt;A,B&gt;();});
 }
}

public class Registries
{
  public static UnityContainer GetContainer()
  {
    var container = new UnityContainer();
    container.RegisterType&lt;IABC, ABC&gt;();
  }
}
</code></pre>

<p>Webapiconfig.cs</p>

<pre><code>public static class WebApiConfig
{
 public static void Register(HttpConfiguration config)
 {
  AutomapperConfiguration.Configure();
  var container = Registries.GetContainer();
}
}
</code></pre>
",https://stackoverflow.com/questions/52918807/automapper-mocking,"['unit-testing', 'unity-game-engine', 'asp.net-web-api', 'automapper', 'moq']",146,TRUE,1,1
how to cover this.service in jasmine of my angularjs service,"<p>How to cover the highlighted code </p>

<pre><code>genericFunctionsService.getConfigDetails().then((config) =&gt; {

        let navigationURL = genericFunctionsService.replacePlaceHolders(config.data.navigationUrl, {
            '{edition}': editionObject.editionCode,
            '{language}': editionObject.editionLanguage
        });
         *this.getNavigationItemsFromService(navigationURL).then(( navigationData ) =&gt; {
            let tempNavItem = this.filterNavigationItems(navigationData.data, editionObject);
            deferred.resolve(tempNavItem);
        }).catch(function(error) {
            deferred.reject(error);
        });*
    });
    return deferred.promise;
}
</code></pre>

<hr>

<pre><code>this.getNavigationItemsFromService(navigationURL)
  .then(( navigationData ) =&gt; {
    let tempNavItem = this.filterNavigationItems(navigationData.data, editionObject);
    deferred.resolve(tempNavItem); 
}).catch(function(error) {
    deferred.reject(error); 
}); 
</code></pre>

<p>After dot then it is showing me orange color which is not covered, i am not able to cover this with my unit testing </p>
",https://stackoverflow.com/questions/53119494/how-to-cover-this-service-in-jasmine-of-my-angularjs-service,"['angularjs', 'jasmine']",38,FALSE,-1,1
Node Js Unite Testing Framework,"<p>I am working on Node Js web application and I want to unit test my application. Can anyone know about unit testing framework in Node Js which developer mostly used...</p>
",https://stackoverflow.com/questions/53848377/node-js-unite-testing-framework,['node.js'],261,TRUE,-3,2
Test Unit Jasmine e Karma Angular,"<p>I'm doing unit testing on angle 6, I'm having trouble testing this branch, I use it to observe how big the screen is to decide how many columns I'll display</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>@Component({
  selector: 'app-rdesp-waiting-approval',
  templateUrl: './rdesp-waiting-approval.component.html',
  styleUrls: ['./rdesp-waiting-approval.component.scss'],
  animations: fuseAnimations

})
export class RdespWaitingForApproval implements OnInit  {
constructor(
    @Inject(ToastrService) private toaster: ToastrService,
    private _profileService: ProfileService,
    private _service: ApprovalsService,
    public dialog: MatDialog,
    private route: ActivatedRoute,
    public _matDialog: MatDialog,
    private _approvalsService: ApprovalsService,
    private  media: ObservableMedia
) {
   this.watcher = media.subscribe((change: MediaChange) =&gt; {
      this.activeMediaQuery = change ? `'${change.mqAlias}' = (${change.mediaQuery})` : '';
          if ( change.mqAlias == 'xs') {      
           this.displayedColumns = ['job' ,'name', 'totalValue'];
          }else{
            this.displayedColumns = ['internalId','DateOfPublication', 'alias', 'job', 'name','totalValue'];
      }
    });

  
  }
}
 </code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/53926713/test-unit-jasmine-e-karma-angular,"['angular', 'unit-testing', 'testing', 'angular6', 'karma-jasmine']",82,FALSE,-1,1
using In memory database for laravel 5.5,"<p>I intend to use in memory database for unit testing in laravel...
I added this lines to <strong>phpunit.xml</strong>,</p>

<pre><code>&lt;php&gt;
        &lt;env name=""APP_ENV"" value=""testing""/&gt;
        &lt;env name=""CACHE_DRIVER"" value=""array""/&gt;
        &lt;env name=""SESSION_DRIVER"" value=""array""/&gt;
        &lt;env name=""QUEUE_DRIVER"" value=""sync""/&gt;
        &lt;env name=""DB_CONNECTION"" value=""sqlite"" /&gt;
        &lt;env name=""DB_DATABASE"" value="":memory:"" /&gt;
&lt;/php&gt;
</code></pre>

<p>And this is my BookTest.php file inside \tests\Feature\BookTest.php directory,</p>

<pre><code>&lt;?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\DatabaseMigrations;

class BookTest extends TestCase
{
    use DatabaseMigrations;

    public function test_books_can_be_created()
    {        
        $user = factory(\App\User::class)-&gt;create();

        $book = $user-&gt;books()-&gt;create([
            'name' =&gt; 'The hobbit',
            'price' =&gt; 10
        ]);

        $found_book = $book-&gt;find(1);

        $this-&gt;assertEquals($found_book-&gt;name, 'The hobbit');
        $this-&gt;assertEquals($found_book-&gt;price, 10);


    }
}
</code></pre>

<p>But when we tried to add <strong>vendor\bin\phpunit</strong> I get,</p>

<blockquote>
  <p>1) Tests\Feature\BookTest::test_books_can_be_created
  Illuminate\Database\QueryException: SQLSTATE[HY000]: General error: 1 no such table: books (SQL: insert into ""books"" (""name"",
  ""price"", ""user_id"", ""updated_at"", ""created_at"") values (The hobbit,
  10, 1, 2018-03-23 08:52:26, 2018-03-23 08:52:26))</p>
</blockquote>

<p>it would be great help if you can help me on <strong>how to use in memory database in laravel unit testing</strong>.</p>
",https://stackoverflow.com/questions/49445727/using-in-memory-database-for-laravel-5-5,['laravel-5'],6076,TRUE,3,1
How to unit test flask Log in?,"<p>Hi i am trying to test my application using unit testing but my code isnt working.</p>

<pre><code>def test_login(self):
    tester = app.test_client(self)
    response = tester.post('/login', data=dict(username=""test"", 
    password=""test""), 
    follow_redirects=True)
    self.assertIn(b'Welcome to Website', response.data)
</code></pre>

<p>This gives me an error ""self.assertIn(b'Welcome to Website', response.data) not found in b'

<p>Any advice? </p>
",https://stackoverflow.com/questions/53840480/how-to-unit-test-flask-log-in,"['python', 'html', 'web', 'flask', 'authentication']",96,FALSE,1,0
unite testing in .net core 2.0 with Dependency Injection,"<p>I have controller with DI approach.want to test each action of controller using unit testing.
**Controller **</p>

<pre><code>  public SearchController(ILookupSearch lookupSearch, IFullSearch fullSearch, IEmpUow uow, ILogger&lt;SearchController&gt; logger, TelemetryClient telemetryClient, IHostingEnvironment hostingEnvironment, IOptions&lt;ConnectionStringsConfig&gt; connectionString, IOptions&lt;AppSettingsConfig&gt; options)
    {
        this.LookupSearch = lookupSearch;
        this.FullSearch = fullSearch;
        this.EmpUow = uow;
        this.logger = logger;
        this.hostingEnvironment = hostingEnvironment;
        this.connectionString = connectionString.Value;
        this.appSettings = options.Value;
        this.telemetryClient = telemetryClient;
    }


    [Route(""Test"")]
        [ActionName(""Test"")]
        [HttpGet]
        public IActionResult Test()
        {
if(this.appsettings.enableDummyData){
            return this.SearchEmpData(new EmpIdQueryField() { Country = ""Sweden"", EMPID = 441150 });
           }
        }
</code></pre>

<p>call goes to controller but all dependencies values in constructor are null.</p>

<p>Unit test case </p>

<pre><code>   public async void Test1()
    {

        //Arrange

        Mock&lt;IHostingEnvironment&gt; hostingEnvironment = new Mock&lt;IHostingEnvironment&gt;();
        TelemetryClient telemetryClient = new TelemetryClient();
        Mock&lt;ILogger&lt;SearchController&gt;&gt; logger = new Mock&lt;ILogger&lt;SearchController&gt;&gt;();
        Mock&lt;AppSettingsConfig&gt; appSettings = new Mock&lt;AppSettingsConfig&gt;();

        Mock&lt;IOptions&lt;ConnectionStringsConfig&gt;&gt; connectionString = new Mock&lt;IOptions&lt;ConnectionStringsConfig&gt;&gt;();
        Mock&lt;IOptions&lt;AppSettingsConfig&gt;&gt; options = new Mock&lt;IOptions&lt;AppSettingsConfig&gt;&gt;();

        Mock&lt;ILookupSearch&gt; lookupSearch = new Mock&lt;ILookupSearch&gt;();
        Mock&lt;IFullSearch&gt; fullSearch = new Mock&lt;IFullSearch&gt;();
        Mock&lt;IOneSoeUow&gt; EmpUow = new Mock&lt;IEmpUow&gt;();

        //Act
        SearchController search = new SearchController(lookupSearch.Object, fullSearch.Object, oneSoeUow.Object, logger.Object, telemetryClient, hostingEnvironment.Object, connectionString.Object, options.Object);
        search.Test();
</code></pre>
",https://stackoverflow.com/questions/50442127/unite-testing-in-net-core-2-0-with-dependency-injection,"['asp.net-mvc', 'unit-testing', '.net-core', 'moq', 'xunit']",258,TRUE,0,1
NoClassDefFoundError: org/apache/hadoop/mapred/MRVersion when using spark-testing-base,"<p>when using spark-testing-base for unit testing 
I am getting the following error</p>

<pre><code>java.lang.NoClassDefFoundError: org/apache/hadoop/mapred/MRVersion
at org.apache.hadoop.hive.shims.Hadoop23Shims.isMR2(Hadoop23Shims.java:852)
at org.apache.hadoop.hive.shims.Hadoop23Shims.getHadoopConfNames(Hadoop23Shims.java:923)
at org.apache.hadoop.hive.conf.HiveConf$ConfVars.&lt;clinit&gt;(HiveConf.java:358)
at com.holdenkarau.spark.testing.DataFrameSuiteBaseLike$class.newTemporaryConfiguration$1(DataFrameSuiteBase.scala:63)
</code></pre>

<p>I am using the following dependencies. This is working from intellj however when I execute sbt test it fails</p>

<pre><code> libraryDependencies ++= Seq(
  ""org.scalaj"" %% ""scalaj-http"" % ""2.3.0"",
  ""org.apache.spark"" %% ""spark-core"" % ""1.6.0-cdh5.8.4"" % ""provided"",
  ""org.apache.spark"" %% ""spark-hive"" % ""1.6.0-cdh5.8.4"" % ""provided"",
  ""org.apache.spark"" %% ""spark-sql"" % ""1.6.0-cdh5.8.4"" % ""provided"",
  ""com.holdenkarau"" %% ""spark-testing-base"" % ""1.6.0_0.8.0"" % Test,
  ""org.scalatest"" %% ""scalatest"" % ""2.2.6"" % ""test"",
  ""org.mockito"" % ""mockito-core"" % ""2.8.9"" % ""test"",
  ""org.flywaydb"" % ""flyway-core"" % ""5.0.2"" % ""test""
)

libraryDependencies ++= Seq(
  ""org.apache.hive"" % ""hive-jdbc"" % ""1.1.0-cdh5.8.4"" % ""provided"",
  ""org.apache.hive"" % ""hive-exec"" % ""1.1.0-cdh5.8.4"" % ""provided"",
  ""org.apache.hive"" % ""hive-metastore"" % ""1.1.0-cdh5.8.4"" % ""provided"",
  ""org.apache.hive"" % ""hive-shims"" % ""1.1.0-cdh5.8.4"" % ""provided"",
  ""org.apache.hive.shims"" % ""hive-shims-common"" % ""1.1.0-cdh5.8.4"" % ""provided"",
  ""org.apache.hadoop"" % ""hadoop-common"" % ""2.6.0-cdh5.8.4"" % ""provided"",
  ""org.apache.hadoop"" % ""hadoop-hdfs"" % ""2.6.0-cdh5.8.4"" % ""provided"",
  ""org.apache.hadoop"" % ""hadoop-mapreduce-client-core"" % ""2.6.0-cdh5.8.4"" % ""provided"",
  ""org.apache.hadoop"" % ""hadoop-mapreduce-client-common"" % ""2.6.0-cdh5.8.4"" % ""provided"",
  ""org.apache.hadoop"" % ""hadoop-mapreduce-client-jobclient"" % ""2.6.0-cdh5.8.4"" % ""provided"",
  ""org.apache.hadoop"" % ""hadoop-yarn-api"" % ""2.6.0-cdh5.8.4"" % ""provided"",
  ""org.apache.hadoop"" % ""hadoop-yarn-common"" % ""2.6.0-cdh5.8.4"" % ""provided"",
  ""org.apache.hadoop"" % ""hadoop-yarn-client"" % ""2.6.0-cdh5.8.4"" % ""provided"",
  ""org.spark-project.akka"" %% ""akka-actor"" % ""2.2.3-shaded-protobuf"" % ""provided""
  )
</code></pre>
",https://stackoverflow.com/questions/48443337/noclassdeffounderror-org-apache-hadoop-mapred-mrversion-when-using-spark-testin,"['unit-testing', 'apache-spark']",2156,TRUE,2,1
Sequelize doesn&#39;t save included objects,"<p>If I do this unit testing, </p>

<pre><code>  test('it saves included instances', async() =&gt; {
    /* Get ""water"" composition */
    const compositions = await _compositions.findAll(
        {include: [{model: _elements, where: {name: 'water'}}, _atoms]});

    /**
     * compositions[0] -&gt; Hydrogren
     * compositions[1] -&gt; Oxygen
     */
    let hydrogen = compositions[0].get('atom');
    /* rename ""Hydrogen"" to ""My super Hydrogen"" */
    hydrogen.name = 'My super Hydrogen';

    /* save the composition */
    compositions[0].save();

    /* Get a fresh Hydrogen Instance from the database */
    hydrogen = await _atoms.find({where: {symbol: 'H'}});
    expect(hydrogen.name)
        .to.equal('My super Hydrogen', 'wrong, the value is still Hydrogen');
  });
</code></pre>

<p>I would expect the value to be equal to the value previously saved from the related object.</p>

<p>The property <code>atom</code> of a <code>composition</code> is a foreign key :</p>

<pre><code>compositionModel.belongsTo(await getAtomModel(), {foreignKey: 'atom_id'});
</code></pre>
",https://stackoverflow.com/questions/49943896/sequelize-doesnt-save-included-objects,"['javascript', 'database', 'typescript', 'sequelize.js']",53,TRUE,0,1
How to stub mysql query using some mock data and mocha in node js,"<p>My requirement is to use stubbing in unit testing script to bypass some actual mysql query using a mock data. I'm using mocha testing framework and chai. I don't know how to use mock data to bypass the mysql query. </p>

<p>I tried with some testing variable and if the variable is true i'm just bypassing the mysql query with predefined mock data. But that's not a proper proceedure. So can you please explain me how to use sinon stub to overcome mysql using mock data. </p>

<pre><code>let query_response = await sequelize.query(""select * from `"" + table_name + ""` where email='"" + data.user + ""' and name = '"" + name + ""' "" + pre_name + "";"", {
            type: sequelize.QueryTypes.SELECT
        });
</code></pre>

<p>In unit testing i need to bypass this query and give response using some mock data. The response should be like this, </p>

<pre><code>[ { id: '3',
    xyz_id: 'Z1455264',
    vir_id: '264_3',
    name: 'XYZ',
    pre_name: 'abc',
    value: 1 },
  { id: '32',
    xyz_id: 'Z1455dd264',
    vir_id: '26s4_3',
    name: 'XYZQ',
    pre_name: 'abdc',
    value: 1 }];
</code></pre>
",https://stackoverflow.com/questions/50809809/how-to-stub-mysql-query-using-some-mock-data-and-mocha-in-node-js,"['mysql', 'node.js', 'unit-testing', 'mocha.js', 'stub']",3020,TRUE,2,1
JUnit - Test array results,"<p>How can I compare an array to make sure the expected value is the same as the actual value using Junit Unit Testing in <code>@Test</code></p>

<p>Here's what I have so far:</p>

<p>@Before  </p>

<pre><code>public void initialize() throws Exception{
    bob = new Student(18, ""Bob Maher"", new String []{""COSC 222"",""COSC 311"", ""MATH 200"", ""MATH 220""});
    bill = new Student(19, ""Bill Cosby"", new String []{""COSC 222"", ""COSC 404"", ""ENGL 112""});
    ben = new Student(24, ""Ben Mckenny"", new String []{""COSC 222"", ""COSC 111"", ""MATH 200"", ""PHYS 101""});
}

@Test

public void testGetClasses() throws Exception {
    //TODO: test that the classes array returned is correct
    ArrayList&lt;Student&gt; list = new ArrayList&lt;&gt;(Arrays.asList(bob, bill, ben));

    ArrayList&lt;Student&gt; results = Arrays.asList(bob,bill.ben))

    assertTrue(list.containsAll(results) &amp;&amp; results.containsAll(list));
}
</code></pre>
",https://stackoverflow.com/questions/52334435/junit-test-array-results,"['java', 'junit']",363,TRUE,0,1
Is it possible to test a method in an Activity class?,"<p>Everybody recommended to follow MVP or MVVM pattern to maintain code readability and testability. Now I am having doubts. Now I am learning unit testing and I'm writing the code in a formal way. Not using any patterns. Now my question, can I test my code like the following?</p>

<p>My main activity:</p>

<pre><code>public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); 
    }

    public boolean testMethod(int value){
       return value== 5?true:false;
    }
}
</code></pre>

<p>My unit test class:</p>

<pre><code>@RunWith(MockitoJUnitRunner.class)
public class ExampleUnitTest {
 MainActivity mainActivity = new MainActivity();
@Test
    public void testMethod(){
        boolean result = mainActivity.testMethod(5);
        assertEquals(true,result);
    }
}
</code></pre>

<p>While running the test I did not receive any errors or issues. So is this the right way to test like this? Or what will happen if I follow this method? I am also starting to migrate my code to the MVP pattern, but I want to clear my doubts. Please let me know the reason why I should not follow the formal coding for unit testing.</p>
",https://stackoverflow.com/questions/53077207/is-it-possible-to-test-a-method-in-an-activity-class,"['android', 'unit-testing', 'junit', 'android-testing']",4081,TRUE,9,1
Any alternative for Microsoft Fakes in .NET Core?,"<p>I am looking for an alternative to Microsoft Fakes in .NET Core. I know it is no longer supported in .NET Core. I just do not understand why not, I think it was a good solution in certain situations.</p>

<p>My problem is that I want to mock DateTime.Now. Previously you could do this with the following code:</p>

<pre><code>System.Fakes.ShimDateTime.NowGet = () =&gt; 
{ 
   return new DateTime(2000, 1, 1); 
};
</code></pre>

<p>It is described in the Microsoft documentation, see the link for more information: <a href=""https://learn.microsoft.com/en-us/visualstudio/test/using-shims-to-isolate-your-application-from-other-assemblies-for-unit-testing?view=vs-2017"" rel=""noreferrer"">https://learn.microsoft.com/en-us/visualstudio/test/using-shims-to-isolate-your-application-from-other-assemblies-for-unit-testing?view=vs-2017</a></p>

<p>For now I solved it by creating a wrapper for DateTime, which looks like this:</p>

<pre><code>/// &lt;summary&gt;
/// Used for getting DateTime.Now(), time is changeable for unit testing
/// &lt;/summary&gt;
public static class SystemTime
{
   /// &lt;summary&gt; 
   /// Normally this is a pass-through to DateTime.Now, but it can be 
   /// overridden with SetDateTime( .. ) for testing or debugging.
   /// &lt;/summary&gt;
   public static Func&lt;DateTime&gt; Now = () =&gt; DateTime.Now;

   /// &lt;summary&gt; 
   /// Set time to return when SystemTime.Now() is called.
   /// &lt;/summary&gt;
   public static void SetDateTime(DateTime dateTimeNow)
   {
      Now = () =&gt;  dateTimeNow;
   }

   /// &lt;summary&gt; 
   /// Resets SystemTime.Now() to return DateTime.Now.
   /// &lt;/summary&gt;
   public static void ResetDateTime()
   {
       Now = () =&gt; DateTime.Now;
   }
}
</code></pre>

<p>I owe this solution to the next StackOverflow post:
<a href=""https://stackoverflow.com/questions/2425721/unit-testing-datetime-now"">Unit Testing: DateTime.Now</a></p>

<p>But I am not satisfied with this solution yet, because I feel I have to adjust my implementation for my testing. I do not think this is desirable.</p>

<p>I hope someone can help me with this, thanks in advance for the effort.</p>
",https://stackoverflow.com/questions/52497439/any-alternative-for-microsoft-fakes-in-net-core,"['c#', '.net-core', 'microsoft-fakes']",11110,TRUE,23,3
How to mock AsyncStorage in jest?,"<p>I am using jest for unit testing of a react-native app. I have used AsyncStorage in one of my component. </p>

<pre class=""lang-js prettyprint-override""><code>componentWillMount() {
    this.setState({ avatarSource: null });
    AsyncStorage.getItem('UserDetails', (err, result) =&gt; {
      var objData = JSON.parse(result);
      this.setState({ userdetail: objData });
      axios.get(SERVER_URL + '/image/' + objData.userId + '.jpg' + '?$' + Math.random())
          .then(response =&gt; {
              var obj = { uri: response.config.url };
              this.setState({ avatarSource: obj });
      });
    });
}
</code></pre>

<p>How do I mock the 'result' from AsyncStorage in my test file?</p>
",https://stackoverflow.com/questions/50713005/how-to-mock-asyncstorage-in-jest,"['unit-testing', 'react-native', 'jestjs', 'enzyme', 'asyncstorage']",814,FALSE,1,1
How to debug Mockery\Exception\InvalidCountException?,"<p>I've got this line in my unit testing files:</p>

<pre><code>$this-&gt;object-&gt;drupal-&gt;shouldReceive('drupalSetMessage')-&gt;once();
</code></pre>

<p>but I've got the errors like:</p>

<pre><code>$ ./tests/phpunit -c tests/phpunit.xml

...

There was 1 error:

1) SessionTest::testFoo
Mockery\Exception\InvalidCountException: Method drupalSetMessage(&lt;Any Arguments&gt;) from Mockery_1_Drupal_Util_Drupal should be called
 exactly 1 times but called 0 times.

tests/vendor/mockery/mockery/library/Mockery/CountValidator/Exact.php:38
tests/vendor/mockery/mockery/library/Mockery/Expectation.php:309
tests/vendor/mockery/mockery/library/Mockery/ExpectationDirector.php:119
tests/vendor/mockery/mockery/library/Mockery/Container.php:301
tests/vendor/mockery/mockery/library/Mockery/Container.php:286
tests/vendor/mockery/mockery/library/Mockery.php:165
</code></pre>

<p>How can I debug to see with what parameters the method has been called during the test?</p>
",https://stackoverflow.com/questions/48929029/how-to-debug-mockery-exception-invalidcountexception,"['php', 'exception', 'mockery']",561,FALSE,0,1
How can I tell if whether my PowerShell module function was called by C# application or from the command line?,"<p>How can I tell if whether my PowerShell module function was called by my .NET / C# application (production) or from the command line (unit testing)?  I'm running PowerShell v5, .NET 4.5.x .</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/48776608/how-can-i-tell-if-whether-my-powershell-module-function-was-called-by-c-applica,['powershell'],32,TRUE,1,1
how to unit test an arrow function in angular 5,"<p>here is the ts file i need to test, the uncovered code in Karma is only the below line</p>

<pre><code>(value =&gt; {
      this.value = ++this.value;
    });
</code></pre>

<p>I am new to angular and completely new to unit testing, please help</p>

<pre><code>import { Component, OnInit, Input, OnDestroy } from '@angular/core';
import { ToolHandlerService } from '../shared/services/toolhandler.service';
import { ISubscription } from 'rxjs/Subscription';

@Component({
  selector: 'basic-graphicresults',
  templateUrl: './graphicresults.component.html',
  styleUrls: ['./graphicresults.component.scss']
})
export class GraphicResultsComponent implements OnInit, OnDestroy {

  @Input() value: number;
  private replaceResultsSubscription: ISubscription;

  constructor(private toolHandlerService: ToolHandlerService) {
  }

  ngOnInit() {
    this.value=4;
    this.replaceResultsSubscription = this.toolHandlerService.onReplaceResults$.subscribe(value =&gt; {
      this.value = ++this.value;
    });
  }

  ngOnDestroy() {
    this.replaceResultsSubscription.unsubscribe();
  }
}
</code></pre>
",https://stackoverflow.com/questions/50928189/how-to-unit-test-an-arrow-function-in-angular-5,"['angular', 'unit-testing', 'visual-studio-code', 'karma-jasmine']",2017,TRUE,0,1
Corda Unit Test: Passing List&lt;StateAndRef&lt;State&gt;&gt;,"<p>In corda, I am writing unit test where i need to pass List> for testing. I was passing from api through CordaRPCOps, How can I do same in unit testing ....Plz help</p>
",https://stackoverflow.com/questions/52380675/corda-unit-test-passing-liststateandrefstate,['corda'],50,FALSE,-1,1
Can you unit test s3 writes?,"<p>Unit testing a method that verifies a particular s3 bucket exists is simple because the unit test would not change the state of s3. However, unit testing a method that writes to an s3 bucket is more problematic because it actually changes the state of s3 every time the unit test is run. For example, a method that uses <code>rdd.saveAsTextFile(path)</code>.</p>

<p>Can a unit test be written for a method that writes to s3 that still allows you to verify that the file got written?</p>

<p>Note: I thought about using a mock object, but wasn't sure how this might be implemented.</p>

<p>Edit: I should probably note that I am using Scala</p>
",https://stackoverflow.com/questions/48572666/can-you-unit-test-s3-writes,"['scala', 'unit-testing', 'testing', 'amazon-s3', 'junit']",3611,TRUE,1,3
Faking authentication during development,"<p>In my current asp.net MVC core application we use OpenId Connect to authenticate with our corporation's identity provider.
However during local development we cannot reach the the provider.
Also we would like to easily change claim values for development and unit testing purposes.</p>

<p>I tried swapping my service binding for IHttpContextAccessor to a DevelopmentHttpContextAccessor that fills up the HttpContext's Identity with the desired claims.
This is a bit of a roundabout way and it also doesn't work as the claims are emptied when I check them in my Service.</p>

<p>What is the standard way of handling this during development and unit testing? What am I missing?</p>
",https://stackoverflow.com/questions/50530543/faking-authentication-during-development,"['.net-core', 'asp.net-core-mvc', 'asp.net-identity', 'openid-connect']",76,TRUE,1,1
Java monthly scheduler,"<p>I have small scheduling requirement to
configure batch Jobs with monthly interval.</p>

<p>Say, If the Job start time is Jan 5th 2017 and the interval is 1 Month, It will run Job on the following dates. </p>

<blockquote>
  <p>Jan 5th, Feb 5th, March 5th, ....</p>
</blockquote>

<p>When the app goes down for a while and when it comes up, I am calculating the next run time as follows.</p>

<p>For Monthly Job,</p>

<pre><code>(ChronoUnit.MONTHS.between(jobStTime, currentTime) + 1;
</code></pre>

<p>It will return the number of runs so far,</p>

<p>For ex, </p>

<blockquote>
  <p><code>(ChronoUnit.MONTHS.between(""Jan 5th 2017"", ""Jan 20th 2018"") + 1;</code>
  will return 13.</p>
</blockquote>

<p>Now, the next run will be calculated as follows.</p>

<p><code>jobStTime.plusMonths(13);</code> </p>

<p>For ex,</p>

<blockquote>
  <p>""Jan 5th 2017"".plusMonths(13) will return Feb 5th 2018.</p>
</blockquote>

<p>Hope, there is no flaw in the logic.</p>

<p>Now, the problem is with Unit testing.</p>

<p>I have a unit testing as follows to test the monthly Job.</p>

<p>Date jobDate = currentDate.minusMonths(2);
Date currentDate = currentDate.minusHour(1);</p>

<p>Say, </p>

<p><strong>Test Case 1:-</strong></p>

<p>the Unit testing is running on ""Jan 20th 2018 10 AM  -> currentDate.</p>

<p>The Job date will be ""November 20th 2017 10 AM"" and the <strong>currentDate for testing will be Jan 20th 2018 9 AM.</strong></p>

<p>So, now the skip calculation will be,</p>

<blockquote>
  <p>(ChronoUnit.MONTHS.between(""November 20th 2017 10AM"", ""Jan 20th 2018
  9AM"") + 1;   --> 2</p>
</blockquote>

<p>This is fine and the next run will be,</p>

<blockquote>
  <p>""November 20th 2017 10AM"".plusMonths(2) -> ""Jan 20th 2017 10AM""</p>
</blockquote>

<p><strong>Test Case 2:-</strong>  This is what problematic.</p>

<p>the Unit testing is running on ""Jan 31st 2018 10 AM  -> currentDate.</p>

<p>The Job date will be ""November 30th 2017 10 AM"" and the <strong>currentDate for testing will be Jan 31st 2018 9 AM.</strong></p>

<p>So, now the skip calculation will be,</p>

<blockquote>
  <p>(ChronoUnit.MONTHS.between(""November 30th 2017 10AM"", ""Jan 31st 2018
  9AM"") + 1;   --> 3</p>
</blockquote>

<p>The next run will be,</p>

<blockquote>
  <p>""November 30th 2017 10AM"".plusMonths(3) -> ""March 30th 2017 10AM""</p>
</blockquote>

<p>So, unit tests are failing when it runs on 31st of the month.</p>

<p>Is there any solution apart from handling 31st in the unit testing code?</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/48551242/java-monthly-scheduler,"['java', 'datetime', 'junit']",192,FALSE,0,0
Moq does not contain a definition for ReturnAsync?,"<p>I am trying to mock some API calls to a third-party service for unit testing purposes. I really just want this mocked function to return the same <code>RestEase.Response&lt;...&gt;</code> each time.</p>

<pre><code>// Setup
var VeracrossMock = new Mock&lt;IVeracrossAPI&gt;(MockBehavior.Strict);
Func&lt;List&lt;VeracrossStudent&gt;&gt; func = () =&gt; new List&lt;VeracrossStudent&gt;() { new VeracrossStudent() { First_name = ""Bob"", Last_name = ""Lob"" } };
RestEase.Response&lt;List&lt;VeracrossStudent&gt;&gt; resp = new RestEase.Response&lt;List&lt;VeracrossStudent&gt;&gt;("""", new HttpResponseMessage(HttpStatusCode.OK), func);

// Problem is on the line below
VeracrossMock.Setup(api =&gt; api.GetStudentsAsync(1, null, CancellationToken.None)).ReturnsAsync&lt;RestEase.Response&lt;List&lt;VeracrossStudent&gt;&gt;&gt;(resp);
</code></pre>

<p>It gives me a red underline and then claims the <code>ReturnsAsync</code> doesn't exist, or at least not with the arguments that I've given it.</p>

<pre><code>Error CS1929 'ISetup&lt;IVeracrossAPI, Task&lt;Response&lt;List&lt;VeracrossStudent&gt;&gt;&gt;&gt;' does not contain a definition for 'ReturnsAsync' and the best extension method overload 'SequenceExtensions.ReturnsAsync&lt;Response&lt;List&lt;VeracrossStudent&gt;&gt;&gt;(ISetupSequentialResult&lt;Task&lt;Response&lt;List&lt;VeracrossStudent&gt;&gt;&gt;&gt;, Response&lt;List&lt;VeracrossStudent&gt;&gt;)' requires a receiver of type 'ISetupSequentialResult&lt;Task&lt;Response&lt;List&lt;VeracrossStudent&gt;&gt;&gt;&gt;'
</code></pre>

<p>How am I supposed to be using <code>ReturnsAsync</code>? Clueless as to how to mock this.</p>
",https://stackoverflow.com/questions/50990487/moq-does-not-contain-a-definition-for-returnasync,"['c#', '.net', 'unit-testing', 'moq']",21255,TRUE,27,5
Vue-cli 3 how to integrate karma?,"<p>What problem does this feature solve?
karma Unit Testing</p>

<p>What does the proposed API look like?
Vue-cli 3 integration karma</p>

<p>Karma can't get the mode defined in vue-cli 3</p>

<p>Below is my karma.conf.js </p>

<pre><code>const path = require('path')
const webpackConfig = require(path.join(process.cwd(), '/node_modules/@vue/cli-service/webpack.config.js'))

module.exports = function(config) {
  config.set({

    basePath: '',

    frameworks: ['mocha', 'chai'],

    files: [
      'test/*.test.js'
    ],

    exclude: [
      'node_modules'
    ],

    preprocessors: {
      'test/*.test.js': ['webpack', 'sourcemap']
    },

    webpack: {
      ...webpackConfig,
      mode: 'production'
    },

    reporters: ['progress'],

    port: 9876,

    colors: true,

    logLevel: config.LOG_INFO,

    autoWatch: true,

    browsers: ['Chrome'],

    singleRun: false,

    concurrency: Infinity
  })
}
</code></pre>
",https://stackoverflow.com/questions/51868649/vue-cli-3-how-to-integrate-karma,"['vue.js', 'vue-cli', 'karma-mocha']",629,FALSE,2,0
Node.js Express.js: mock request object for unit-test purpose,"<p>I have a method that check if request query string has some params:</p>

<pre><code>checkMandatoryQueryParams (mandatoryQueryParams: String[],  req: Request): void {
    let result = true;
    mandatoryQueryParams.forEach((element, idx) =&gt; {
        if (!req.query.hasOwnProperty(element)) {
            result = false;
        }
    });
    return result;
}
</code></pre>

<p>in unit-testing i need to mock the request for test it, eg:</p>

<pre><code>describe('Utils', () =&gt; {

    it('checkMandatoryQueryParams', () =&gt; {
        const req: Request = new Request(); // pseudo-code
        req.query = ""?foo=test&amp;bar=test"";   // pseudo-code
        expect( checkMandatoryQueryParams(['foo', 'bar'], req) ).toEqual(true);
    });
});
</code></pre>

<p>how can i mock the express request?</p>
",https://stackoverflow.com/questions/50215305/node-js-express-js-mock-request-object-for-unit-test-purpose,"['unit-testing', 'typescript', 'express']",3335,TRUE,0,1
AndroidX : No instrumentation registered! Must run under a registering instrumentation,"<p>I'm trying to run a local unit test that depends on the context, and was following this guide: <a href=""https://developer.android.com/training/testing/unit-testing/local-unit-tests#kotlin"" rel=""noreferrer"">https://developer.android.com/training/testing/unit-testing/local-unit-tests#kotlin</a>  and I set up my project like this (following this link : <a href=""https://developer.android.com/training/testing/set-up-project"" rel=""noreferrer"">https://developer.android.com/training/testing/set-up-project</a> ):</p>

<p><strong>build.gradle(app)</strong></p>

<pre><code>android {
compileSdkVersion 28
buildToolsVersion '27.0.3'
defaultConfig {
    minSdkVersion 21
    targetSdkVersion 27
    versionCode 76
    versionName ""2.6.0""
    testInstrumentationRunner ""androidx.test.runner.AndroidJUnitRunner""
    multiDexEnabled true

useLibrary 'android.test.runner'
    useLibrary 'android.test.base'
    useLibrary 'android.test.mock'

}
testOptions {
    unitTests.returnDefaultValues = true
    unitTests.all {
        // All the usual Gradle options.
        testLogging {
            events ""passed"", ""skipped"", ""failed"", ""standardOut"", ""standardError""
            outputs.upToDateWhen { false }
            showStandardStreams = true
        }
    }
    unitTests.includeAndroidResources = true

}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')

androidTestImplementation(""androidx.test.espresso:espresso-core:$espressoVersion"", {
    exclude group: 'com.android.support', module: 'support-annotations'
})
// Espresso UI Testing dependencies
implementation ""androidx.test.espresso:espresso-idling-resource:$espressoVersion""
androidTestImplementation ""androidx.test.espresso:espresso-contrib:$espressoVersion""
androidTestImplementation ""androidx.test.espresso:espresso-intents:$espressoVersion""

testImplementation 'androidx.test:core:1.0.0'

// AndroidJUnitRunner and JUnit Rules
androidTestImplementation 'androidx.test:runner:1.1.0'
androidTestImplementation 'androidx.test:rules:1.1.0'
// Espresso Assertions
androidTestImplementation 'androidx.test.ext:junit:1.0.0'
androidTestImplementation 'androidx.test.ext:truth:1.0.0'
androidTestImplementation 'com.google.truth:truth:0.42'
    implementation 'androidx.multidex:multidex:2.0.0'
}
</code></pre>

<p>My espresso_version is <strong>espressoVersion = '3.1.0'</strong></p>

<p>My test that is located in <strong><em>module-name/src/test/java/</em></strong> looks like this:</p>

<pre><code>    import android.content.Context
import androidx.test.core.app.ApplicationProvider
import com.instacart.library.truetime.TrueTime
import edu.mira.aula.shared.extensions.android.trueDateNow
import edu.mira.aula.shared.network.ConnectivityHelper
import kotlinx.coroutines.experimental.runBlocking
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import java.util.*
import java.util.concurrent.CountDownLatch

class TimeExtensionsUnitTest {
private lateinit var instrumentationCtx: Context

@Before
fun setup() {
    instrumentationCtx = ApplicationProvider.getApplicationContext&lt;Context&gt;()
}
 @Test
fun testTrueTimeValueReturnsIfInitialized() {
    if (ConnectivityHelper.isOnline(instrumentationCtx)) {
        runBlocking {
            val countDownLatch = CountDownLatch(1)
            TrueTime.build()
                    .withSharedPreferencesCache(instrumentationCtx)
                    .withConnectionTimeout(10000)
                    .initialize()
            countDownLatch.countDown()

            try {
                countDownLatch.await()
                val dateFromTrueTime = trueDateNow()
                val normalDate = Date()
                Assert.assertNotEquals(dateFromTrueTime, normalDate)
            } catch (e: InterruptedException) {
            }
        }
    }
}
</code></pre>

<p>Everytime I run it, it gives me: </p>

<pre><code>java.lang.IllegalStateException: No instrumentation registered! Must run under a registering instrumentation.
 at androidx.test.platform.app.InstrumentationRegistry.getInstrumentation(InstrumentationRegistry.java:45)
  at androidx.test.core.app.ApplicationProvider.getApplicationContext(ApplicationProvider.java:41)
</code></pre>

<p>If I run it as a Instrumental Test(changing the package) it runs without errors.
But I thought that this guide was exactly to be able to run unit test using Android Framework classes such as Context.
I even tried run that <code>class UnitTestSample</code> but the same error occurs.</p>

<p>I also removed all android.support dependencies from my project</p>

<p>Any ideas on how to solve it?</p>
",https://stackoverflow.com/questions/53595837/androidx-no-instrumentation-registered-must-run-under-a-registering-instrumen,"['android', 'unit-testing', 'android-espresso', 'android-instrumentation']",66204,TRUE,85,13
Test Rest API involving DB calls using Mockito,"<p>I need to do some unit testing for my application's APIs which are REST based. </p>

<p>Now for example if the API is as below</p>

<pre><code> @RequestMapping(value = ""/todo/{id}"", method = RequestMethod.GET)
public ResponseEntity&lt;ToDo&gt; getToDoById(@PathVariable(""id"") long id) throws ToDoException{
    //Makes DB call
    ToDo toDo = toDoService.getToDoById(id);
 }
</code></pre>

<p>The above API does a DB call to get the ID from the database.</p>

<p>Now when I do </p>

<pre><code> mockMvc.perform(MockMvcRequestBuilders.get(""/todo/3"")
 .accept(MediaType.APPLICATION_JSON)
</code></pre>

<p>It is going to hit database.</p>

<p>Now this way mocking is becoming more of Integeration testing hitting the endpoint. Is this the right way to do or else </p>

<ol>
<li><p>what is the right way of using Mockito for unit testing with hitting external entities like DB or webservice</p></li>
<li><p>How to mock the database and how do I get the DB data if mocked.</p></li>
</ol>
",https://stackoverflow.com/questions/48991145/test-rest-api-involving-db-calls-using-mockito,"['java', 'rest', 'mockito']",2252,TRUE,0,1
"Angular Testing, dynamically change ActivatedRoute params for different test cases","<p>Component:</p>

<pre><code>@Component({
  selector: 'app-test',
  templateUrl: './test.component.html'
})
export class TestComponent implements OnInit {
  useCase: string;

  constructor(
    private route: ActivatedRoute,
  ) {}

  ngOnInit() {
    this.route.queryParams.subscribe(p =&gt; {
      if (p) {
        this.useCase = p.u;
      }
    });
  }
}
</code></pre>

<p>Test Spec</p>

<pre><code>describe('TestComponent', () =&gt; {
  let component: TestComponent;
  let fixture: ComponentFixture&lt;TestComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [
        AppModule
      ],
      providers: [
        { provide: ActivatedRoute, useValue: ??? }
      ]
    })
      .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(TestComponent);
    component = fixture.componentInstance;
  });

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
    expect(component.useCase).toBeFalsy();
  });

  it('should set useCase variable with query string value', () =&gt; {
    fixture.detectChanges();
    // Set different route.queryParams here...
    expect(component.useCase).toBe('success');
  });
});
</code></pre>

<p>Using Angular 6, Karma and Jasmine for unit testing.</p>

<p>I know we can set <code>ActivatedRoute</code> to an object that will be used through out this testing, as such:</p>

<pre><code>providers: [
  { provide: ActivatedRoute, useValue: {
    queryParams: Observable.of({id: 123})
  } }
]
</code></pre>

<p>But this will set the values for all the test cases. Is there a way to dynamically change the <code>ActivatedRoute</code> in each different test case?</p>
",https://stackoverflow.com/questions/51941392/angular-testing-dynamically-change-activatedroute-params-for-different-test-cas,"['typescript', 'unit-testing', 'jasmine', 'karma-jasmine', 'angular-test']",12170,TRUE,18,4
Async over Task.WhenAll() does not work in Unit Test,"<p>I'm unit testing some async MVC .netcore code that is working when it's running, but hitting an ObjectDisposedexception during unit testing.<br>
Background: I have another method similar to this one that performs a single async action, returns a task, and also works while running AND when I unit test it like this.
So far no matter how I refactor this I'm getting: 'Cannot access a disposed object. Object name: 'System.Net.Http.StreamContent'' when trying to unit test.</p>

<p>The method:</p>

<pre><code>public async Task&lt;IEnumerable&lt;Foo&gt;&gt; GetFoos() {
var idList = GetFooIds();
var tasks = Enumerable.Range(0, idList.Count)
                  .Select(i =&gt; GetFooById(idList[i]));

var fooResults = await Task.WhenAll(tasks);

var foos = new HashSet&lt;Foo&gt;();
foos.UnionWith(fooResults.SelectMany(x =&gt; x));

return foos;
}
</code></pre>

<p>The unit test approach that works w/ the single Async task, but not here:</p>

<pre><code>[TestMethod]
public void CanGetFoos() {
    ...
    var result = service.GetFoos().Result;
    Assert.AreEqual(2, result.Count());
}
</code></pre>

<p>And I doubt the inner method is a factor, but here it is:</p>

<pre><code>private async Task&lt;List&lt;Foo&gt;&gt; GetFooById(string id)
{
    var nextPageExists = true;
    var fooList = new List&lt;Foo&gt;();
    var pageNumber = 1;
    while (nextPageExists)
    using (var response =
        await Client.GetAsync(GetFooUri(id, pageNumber++))
    {
        var content = await response.Content.ReadAsStringAsync();

        var fooResponse =
            JsonConvert.DeserializeObject&lt;Foo&gt;(content);
        fooList.AddRange(fooResponse.Objects);
        if (!Convert.ToBoolean(fooList.More))
            nextPageExists = false;
    })

    return fooList;
}
</code></pre>
",https://stackoverflow.com/questions/48425640/async-over-task-whenall-does-not-work-in-unit-test,"['asp.net-core', 'async-await']",495,FALSE,0,0
RouterTestingModule not providing provider for Location,"<p>I am unit-testing a <code>Component</code> which uses two other components. The other components are created when button is clicked</p>

<p>.html</p>

<pre><code>    &lt;div id=""homepage-top-div"" class=""homepage-component-css-grid-container""&gt;  ...
        &lt;button id=""get-question-list-button"" [routerLink]=""questionListRouterLink"" class=""btn content-div__button--blue css-grid-item-button-div btn-sm""&gt;See Questions&lt;/button&gt;
      &lt;/div&gt;
      &lt;div id=""practice-component-top-div"" class=""css-grid-container-div common-styles-div--white""&gt; &lt;!-- 4 rows, 1 column--&gt;
...
        &lt;button id=""new-question-button"" [routerLink]=""newQuestionRouterLink""  class=""btn content-div__button--blue css-grid-item-button-div btn-sm""&gt;Create a Question&lt;/button&gt;
      &lt;/div&gt;
    &lt;/div&gt;
</code></pre>

<p>.ts</p>

<pre><code>export class HomepageContentComponentComponent implements OnInit {

  public questionListRouterLink=""/practice-question-list"";
  public newQuestionRouterLink=""/new-practice-question"";


  constructor() {

  }

  ngOnInit() {
  }

}
</code></pre>

<p>I created a spec but I get the following error when I run it - <code>Error: StaticInjectorError[Location]: 
  NullInjectorError: No provider for Location!</code></p>

<p>The spec is</p>

<pre><code>import {async, ComponentFixture, fakeAsync, TestBed, tick} from '@angular/core/testing';
import { HomepageContentComponentComponent } from './homepage-content-component.component';
import {RouterTestingModule} from ""@angular/router/testing"";
import {AppRoutingModule} from ""../app-routing.module"";
import {Router} from ""@angular/router"";
import {routes} from '../app-routing.module';
import {NewPracticeQuestionComponent} from ""../new-practice-question/new-practice-question.component"";
import {PraticeQuestionListComponent} from ""../pratice-question-list/pratice-question-list.component"";
import {NgModule} from ""@angular/core"";
import {AppModule} from ""../app.module"";

fdescribe('HomepageContentComponentComponent', () =&gt; {
  let component: HomepageContentComponentComponent;
  let fixture: ComponentFixture&lt;HomepageContentComponentComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports:[
        AppModule,
        AppRoutingModule,
        RouterTestingModule.withRoutes(routes) //&lt;-- I SUPPOSE THIS STEP SHOULD PROVIDE ROUTERTESTINGMODULE WITH PROVIDERS FOR LOCATION BUT IT SEEMS IT ISN'T
      ],
      declarations: [ HomepageContentComponentComponent,
                  NewPracticeQuestionComponent,
        PraticeQuestionListComponent]
    })
    .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(HomepageContentComponentComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });

  it('should navigate to New Questions Component when New Question button is clicked',fakeAsync(()=&gt;{
    let router:Router;
    let location:Location;
    router = TestBed.get(Router);
    location = TestBed.get(Location);
    console.log('initial router is ',router);
    console.log('initial location is ',location);
    router.initialNavigation();
    router.navigate(['new-practice-question']);
    tick();
    console.log('new router is ',router);
    console.log('new location is ',location);

    expect(location.pathname).toBe('/new-practice-question');
  }));
});
</code></pre>
",https://stackoverflow.com/questions/53813263/routertestingmodule-not-providing-provider-for-location,"['angular', 'angular6', 'angular-routing', 'angular-test']",5152,TRUE,4,2
Regex is failing for Range values in Laravel PHP Unit Testing,"<p>I tried to make a regex with below condition:</p>

<pre><code>-90 &lt; latitude &lt; 90

-180 &lt; longitude &lt; 180

Should have 6 decimal points.
</code></pre>

<p>and my regex for both as follows:</p>

<pre><code>Latitude : /^-?(0|[0-9]|[1-8][0-9]|90)\.{1}\d{6}$/

Longitude : /^-?(0|[0-9]|[1-9][0-9]|1[0-7][0-9]|180)\.{1}\d{6}$/
</code></pre>

<p>Maximum test passed through this. But when I try this in Php Unit</p>

<pre><code>Latitude : 10.000000 , Longitude: 10.000000 // Got Failed

Latitude : 0.000001 , Longitude: 0.000001 // Got Failed

Latitude : 0.000000 , Longitude: 0.000000 // Got Failed
</code></pre>

<p>I want to include these 3 options also. I am using this regex in larval 5.6 (PHP).</p>

<p>Also when I do like this it's start working in unit test.</p>

<pre><code>Latitude : ""10.000000"" , Longitude: ""10.000000"" // Got Succeed

Latitude : ""0.000001"" , Longitude: ""0.000001"" // Got Succeed

Latitude : ""0.000000"" , Longitude: ""0.000000"" // Got Succeed
</code></pre>

<p>If I am trying through Postman it's working for both cases. But while doing in Laravel PHP unit testing it's not working.</p>

<p>My Validation Rules is :</p>

<pre><code>public static $fieldValidations = [
        'serial'    =&gt; 'required|unique:panels|size:16|alpha_num',
        'latitude'  =&gt; array('required','numeric','between:-90,90','regex:/^-?(0|[0-9]|[1-8][0-9]|90)\.{1}\d{6}$/'),
        'longitude'  =&gt; array('required','numeric','between:-180,180','regex:/^-?(0|[0-9]|[1-9][0-9]|1[0-7][0-9]|180)\.{1}\d{6}$/'),
    ];
</code></pre>

<p>My Php Unit Testing Code is </p>

<pre><code>public function testStoreFailureLatitudeLongitudeAllZeroDecimalCase()
    {
        $response = $this-&gt;json('POST', '/api/panels', [
            'serial'    =&gt; 'AAAABBBBCCCC1234',
            'longitude' =&gt; 10.000000,
            'latitude'  =&gt; -20.000000
        ]);

        $response-&gt;assertStatus(201);
    }

    public function testStoreFailurePrecisionFloatDecimalValueCase()
    {
        $response = $this-&gt;json('POST', '/api/panels', [
            'serial'    =&gt; 'AAAABBBBCCCC1234',
            'longitude' =&gt; 0.000001,
            'latitude'  =&gt; 0.000001
        ]);

        $response-&gt;assertStatus(201);
    }

    public function testStoreFailurePrecisionFloatDecimalValuewithZeroCase()
    {
        $response = $this-&gt;json('POST', '/api/panels', [
            'serial'    =&gt; 'AAAABBBBCCCC1234',
            'longitude' =&gt; 0.000000,
            'latitude'  =&gt; 0.000000
        ]);

        $response-&gt;assertStatus(201);
    }
</code></pre>

<p>These are the 3 cases where it got failed and with same values through postman it works.</p>

<p>Any help ?</p>
",https://stackoverflow.com/questions/52243875/regex-is-failing-for-range-values-in-laravel-php-unit-testing,"['php', 'laravel', 'phpunit']",267,FALSE,0,2
error --&gt;The pipe &#39;filter&#39; could not be found while using angular4,"<p>I am doing unit-testing in angular4 -node.js deployed project.And while testing i found this error -</p>

<pre><code>Template parse errors:
The pipe 'filter' could not be found (""
  &lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr *ngFor=""let[ERROR -&gt;] dat of result | filter:filterdata| 
paginate: { itemsPerPage: 5, currentPage: p };let i = index ""&gt;
</code></pre>

<p>so i added these two modules to my module.ts and spec.ts files --></p>

<pre><code>import { PipesModule } from '../../pipes/pipes.module';
import { Pipe, PipeTransform } from '@angular/core';

@NgModule({
 imports: [PipesModule
 ],
</code></pre>

<p>And for this particular module import --></p>

<pre><code>import { PipesModule } from '../../pipes/pipes.module';
</code></pre>

<p>Error -->Cannot find module '../../pipes/pipes.module'.</p>

<p>Please help resolve the issue</p>
",https://stackoverflow.com/questions/50075567/error-the-pipe-filter-could-not-be-found-while-using-angular4,['angular'],31932,TRUE,9,6
Failed: Unexpected directive &#39;NewPracticeQuestionComponent&#39; imported by the module &#39;DynamicTestModule&#39;. Please add a @NgModule annotation,"<p>I am unit-testing a commponent which uses two other components. The other components are created when button is clicked</p>

<p><code>.html</code></p>

<pre><code>    &lt;div id=""homepage-top-div"" class=""homepage-component-css-grid-container""&gt;  ...
        &lt;button id=""get-question-list-button"" [routerLink]=""questionListRouterLink"" class=""btn content-div__button--blue css-grid-item-button-div btn-sm""&gt;See Questions&lt;/button&gt;
      &lt;/div&gt;
      &lt;div id=""practice-component-top-div"" class=""css-grid-container-div common-styles-div--white""&gt; &lt;!-- 4 rows, 1 column--&gt;
...
        &lt;button id=""new-question-button"" [routerLink]=""newQuestionRouterLink""  class=""btn content-div__button--blue css-grid-item-button-div btn-sm""&gt;Create a Question&lt;/button&gt;
      &lt;/div&gt;
    &lt;/div&gt;
</code></pre>

<p><code>.ts</code></p>

<pre><code>export class HomepageContentComponentComponent implements OnInit {

  public questionListRouterLink=""/practice-question-list"";
  public newQuestionRouterLink=""/new-practice-question"";


  constructor() {

  }

  ngOnInit() {
  }

}
</code></pre>

<p>I created a <code>spec</code> but I get the following error when I run it - <code>Failed: Unexpected directive 'NewPracticeQuestionComponent' imported by the module 'DynamicTestModule'. Please add a @NgModule annotation.</code></p>

<p>The spec is </p>

<pre><code>import {async, ComponentFixture, fakeAsync, TestBed, tick} from '@angular/core/testing';
import { HomepageContentComponentComponent } from './homepage-content-component.component';
import {RouterTestingModule} from ""@angular/router/testing"";
import {AppRoutingModule} from ""../app-routing.module"";
import {Router} from ""@angular/router"";
import {routes} from '../app-routing.module';
import {NewPracticeQuestionComponent} from ""../new-practice-question/new-practice-question.component"";
import {PraticeQuestionListComponent} from ""../pratice-question-list/pratice-question-list.component"";
import {NgModule} from ""@angular/core"";
import {AppModule} from ""../app.module"";

fdescribe('HomepageContentComponentComponent', () =&gt; {
  let component: HomepageContentComponentComponent;
  let fixture: ComponentFixture&lt;HomepageContentComponentComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports:[
        AppModule,
        AppRoutingModule,
        RouterTestingModule.withRoutes(routes),
        NewPracticeQuestionComponent,
        PraticeQuestionListComponent
      ],
      declarations: [ HomepageContentComponentComponent,
      ]
    })
    .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(HomepageContentComponentComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });

  it('should navigate to New Questions Component when New Question button is clicked',fakeAsync(()=&gt;{
    let router:Router;
    let location:Location;
    router = TestBed.get(Router);
    location = TestBed.get(Location);
    console.log('initial router is ',router);
    console.log('initial location is ',location);
    router.initialNavigation();
    router.navigate(['new-practice-question']);
    tick();
    console.log('new router is ',router);
    console.log('new location is ',location);

    expect(location.pathname).toBe('/new-practice-question');
  }));
});
</code></pre>
",https://stackoverflow.com/questions/53811054/failed-unexpected-directive-newpracticequestioncomponent-imported-by-the-modu,"['angular6', 'angular-test']",2805,TRUE,2,1
SpringBoot Junit testing for filters in Zuul,"<p>I'm new to Zuul J-unit testing. I have a couple of filters which is ChangeRequestEntityFilter and SessionFilter, Where I pasted my filtercode below. Can someone tell me how to write a Junit for the filter. I've searched and trying to use MockWire for the unit testing(Also I pasted my empty methods with basic annotations and WireMock port). I need at-least one proper example how this J-unit for Zuul works. I've referred the <a href=""http://wiremock.org/docs/getting-started/"" rel=""nofollow noreferrer"">http://wiremock.org/docs/getting-started/</a> doc. Where I got what to do, but not how to do.</p>

<pre><code>public class ChangeRequestEntityFilter extends ZuulFilter {

    @Autowired
    private UtilityHelperBean utilityHelperBean;

    @Override
    public boolean shouldFilter() {
        // //avoid http GET request since it does'nt have any request body
        return utilityHelperBean.isValidContentBody();
    }

    @Override
    public int filterOrder() {
        //given priority
    }

    @Override
    public String filterType() {
        // Pre
    }

    @Override
    public Object run() {

        RequestContext context = getCurrentContext();

        try {
            /** get values profile details from session */
            Map&lt;String, Object&gt; profileMap = utilityHelperBean.getValuesFromSession(context,
                    CommonConstant.PROFILE.value());

            if (profileMap != null) {
                /** get new attributes need to add to the actual origin microservice request payload */
                Map&lt;String, Object&gt; profileAttributeMap = utilityHelperBean.getProfileForRequest(context, profileMap);
                /** add the new attributes in to the current request payload */
                context.setRequest(new CustomHttpServletRequestWrapper(context.getRequest(), profileAttributeMap));
            }

        } catch (Exception ex) {
            ReflectionUtils.rethrowRuntimeException(new IllegalStateException(""ChangeRequestEntityFilter : "", ex));
        }

        return null;
    }

}
</code></pre>

<p>I know ,I'm asking more. But give me any simple working complete example, I'm fine with it.</p>

<p>My current code with basic annotations and WireMock port.</p>

<pre><code>@RunWith(SpringRunner.class)
@SpringBootTest
@DirtiesContext
@EnableZuulProxy
public class ChangeRequestEntityFilterTest {

    @Rule
    public WireMockRule wireMockRule = new WireMockRule(8080);

    @Mock
    ChangeRequestEntityFilter requestEntityFilter;

    int port = wireMockRule.port();

    @Test
    public void changeRequestTest() {

    }
}
</code></pre>
",https://stackoverflow.com/questions/51512075/springboot-junit-testing-for-filters-in-zuul,"['microservices', 'zuul-testing']",4285,TRUE,3,2
alternative ways of stubbing collections,"<p>In <a href=""https://www.meteor.com/"" rel=""nofollow noreferrer"">meteor</a>, is there any way to stub a collection for unit testing without using <a href=""https://atmospherejs.com/hwillson/stub-collections"" rel=""nofollow noreferrer""><code>hwillson:stub-collections</code></a>? Using this package is unfortunately not an option due to package constraints (<code>mongo@1.0.11</code>), and neither is using a test Mongodb instance.</p>
",https://stackoverflow.com/questions/48751894/alternative-ways-of-stubbing-collections,"['mongodb', 'meteor', 'stubbing']",44,FALSE,1,0
Why my properties are not set within my js unit test?,"<p>I am new to Unit Testing with Javascript.
I have the following model:</p>

<pre><code>export class CartItem {
  item: Item;

  someVariableWhichIsNotImportant = {};

  varA = 12;
  constructor(cfg: Partial&lt;CartItem&gt; = {}) {
    if (!cfg.item) {
      throw new Error('Item is missing');
    }
    //...some other error conditions
    this.item = cfg.item;
    //....some other variables
  }
}
</code></pre>

<p>Then, my very simple, yet broken unit tests as follows:</p>

<pre><code>import { Item } from './item.model';
import { CartItem } from './cart-item.model';

describe('something to describe', () =&gt; {
  let a;
  const titel = ""blah blah"";
  const ITEM_1 = new Item();
  ITEM_1.title = title1 

  const CART_ITEM = new CartItem();
  CART_ITEM.item = ITEM_1;

  it('should have a start date of xxx', () =&gt; {
    expect(ITEM_1.tile).toBe(title1);
  });

});
</code></pre>

<p>When I run the test I have <code>Error: Item is missing</code>. What I am doing wrong?</p>
",https://stackoverflow.com/questions/53820117/why-my-properties-are-not-set-within-my-js-unit-test,"['javascript', 'angular', 'typescript', 'unit-testing']",33,TRUE,0,1
ng2-dragula unit test &quot;dragulaService.setOptions is not a function&quot;,"<p>I want to run unit tests on my component which has ng2-dragula.</p>

<p>However, when I run a simple unit test on the component, I get the error</p>

<blockquote>
  <p>TypeError: Cannot read property 'setOptions' of undefined</p>
</blockquote>

<p><strong>component.html</strong></p>

<pre><code>&lt;div [dragula]=""'section-bag'""
     [dragulaModel]='form.sections'&gt;
  &lt;div *ngFor=""let section of form.sections""&gt;
    &lt;div class=""drag-handle__section""&gt;&lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;
</code></pre>

<p><strong>component.ts</strong></p>

<pre><code>import { Component, Input } from '@angular/core';
import { DragulaService } from 'ng2-dragula';
...


export class MyComponent {

  @Input() form;

  constructor(private dragulaService: DragulaService) {
    dragulaService.setOptions('section-bag', {
      moves: (el, container, handle) =&gt; {
        return handle.classList.contains('drag-handle__section');
      }
    });
  }

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

<p><strong>component.spec.ts</strong></p>

<pre><code>import { DragulaService } from 'ng2-dragula';
...


describe('Test for MyComponent', () =&gt; {
  let comp: MyComponent;
  let fixture: ComponentFixture&lt;MyComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ MyComponent ],
      providers: [
        { provide: DragulaService }
      ]
    })
    .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(MyComponent);
    comp = fixture.componentInstance;
    comp.form.sections = [];
    comp.form.sections.push(new FormSection());

    fixture.detectChanges();
  });

  it('should create', () =&gt; {
    expect(comp).toBeTruthy();
  });

});
</code></pre>

<p>I guess that Dragula is not being imported correctly, so how do I add Dragula as a provider in the test to use it in the component's constructor?</p>

<p>I've looked at <a href=""https://stackoverflow.com/questions/43498055/angular2-unit-testing-testing-a-components-constructor"">Angular2 unit testing : testing a component&#39;s constructor</a> which <em>seems</em> related, but I can't resolve the error.</p>

<p>Note: I'm not so fussed about unit testing Dragula; I want to test other functionality in the component, but this error isn't allowing any further tests to run.</p>
",https://stackoverflow.com/questions/51630753/ng2-dragula-unit-test-dragulaservice-setoptions-is-not-a-function,"['angular', 'unit-testing', 'ng2-dragula']",2706,TRUE,2,1
Karma/Jasmine/PhantomJS &quot;TypeError: _this.handler.handle is not a function&quot;,"<p>while unit testing I get the exception:</p>

<blockquote>
  <p>TypeError: _this.handler.handle is not a function</p>
</blockquote>

<p>I already imported BrowserModule, HttpClient and HttpHandler to my *.spec.ts and to my *.module.ts -files.</p>

<p>You got a idea what the error coursed? </p>
",https://stackoverflow.com/questions/50257289/karma-jasmine-phantomjs-typeerror-this-handler-handle-is-not-a-function,"['jasmine', 'phantomjs', 'karma-jasmine']",346,FALSE,1,0
Testing for Algorithm Method,"<p>I am relatively new to unit testing and was wondering how I can check to ensure my algorithm would correctly return any the most common word in any given string that's passed to my function?</p>

<pre><code>var test = ""Let's figure. out what the most comm$on wor!!!!d is in the sentence.""

func checkForRandomChracters(string: String) -&gt; String {
    let charactersToRemove = Array("".:?!,@#$%^*,"")
    let arrayOfChars = Array(string)
    let filteredString = arrayOfChars.reduce("""") {
        let str = String($1)
        return $0 + (charactersToRemove.contains($1) ? """" : str)
    }
    return filteredString
}

func mostFrequentWords(string: String) -&gt; String {
    let lowerString = string.lowercased()
    let cleanedString = checkForRandomChracters(string: lowerString)
    let array = cleanedString.components(separatedBy: "" "")

    var itemInDictionary: [String: Int] = [:]

    for item in array {
        itemInDictionary[item] = (itemInDictionary[item] ?? 0) + 1
    }

    var mostCommonNameInArray  = """"

    for key in itemInDictionary.keys {
        if mostCommonNameInArray == """" {
            mostCommonNameInArray = key
        } else { 
            let count = itemInDictionary[key]!
            if count &gt; itemInDictionary[mostCommonNameInArray]! {
               mostCommonNameInArray = key
            }
         }
      }

    return mostCommonNameInArray
}


mostFrequentWords(string: test) // returns 'the'
</code></pre>
",https://stackoverflow.com/questions/48387689/testing-for-algorithm-method,"['swift', 'xcode', 'algorithm', 'unit-testing']",64,TRUE,0,1
Angular-Testing: Angular5 spyOn not working in child components,"<p>I have an angular app and its one child module is loading by lazy loading. I am using this code in app.routing.ts to load that module.</p>

<pre><code>{
    path: '',
    component: FullLayoutComponent,
    data: {
        title: 'Home'
    },
    children: [
        {
            path: 'dashboard',
            loadChildren: './views/dashboard/dashboard.module#DashboardModule'
        }
    ],
    canActivate: [LoggedInGuard]
},
</code></pre>

<p>Now in all the components in dashboard module my unit testing is not working. i.e. because spyOn is not working. let me show the spec file code and actual function</p>

<pre><code>it('be able to call getDemographicsData function from ngOnInit', () =&gt; {
        spy = spyOn(programDemographicsComponent, 'getDemographicsData').and.callThrough();
        spyOn(programDemographicsComponent, 'dateRangeHandler');
        programDemographicsComponent.ngOnInit();
        expect(programDemographicsComponent.getDemographicsData).toHaveBeenCalled();
    });
</code></pre>

<p>Function that I am unit testing is: </p>

<pre><code>ngOnInit() {
        this.qualifyingProductsTableCurrentPage = 0;
        this.qualifyingProductsTableValuesPerPage = 5;
        const startDateMillis = moment().subtract(90, 'days').valueOf();
        const endDateMillis = moment().valueOf();
        this.getDemographicsData(startDateMillis, endDateMillis)
    }

    getDemographicsData(startDateMillis, endDateMillis) {
        console.log('spy is not working')
        const metricsRequestData = new MetricsRequest();
        metricsRequestData.startDateMillis = startDateMillis;
        metricsRequestData.endDateMillis = endDateMillis;
        this.getGenderData(metricsRequestData);
        this.getAgeData(metricsRequestData);
    }
</code></pre>

<p>Since I am spying the <code>getDemographicsData(startDateMillis, endDateMillis)</code> method in test cases but my <code>console.log('spy is not working')</code> is still working. 
Please let me know if any more details are needed.</p>

<p>PS. I have checked same issue in parent components and my spyOn is working fine in them. I am facing problem only in components with lazyloading</p>
",https://stackoverflow.com/questions/52983830/angular-testing-angular5-spyon-not-working-in-child-components,"['angular', 'angular5', 'karma-jasmine', 'angular-routing', 'angular-test']",678,FALSE,2,1
How do I resolve an error in my configuration when trying to unit test a Spring Kafka Consumer?,"<p><strong>Code Location</strong></p>

<p>I think there might be to many modules to make this question clean looking, so here is the repo. I will hopefully include all the necessary components.
<a href=""https://github.com/ewingian/RestCalculator"" rel=""nofollow noreferrer"">https://github.com/ewingian/RestCalculator</a></p>

<p><strong>Problem</strong></p>

<p>I am learning to write Kafka services, this process includes learning unit testing for the producer and consumer. Followed a tutorial on setting up unit testing with the consumer. When I run the test I receive a class configuration error. </p>

<p><strong>ERROR</strong></p>

<pre><code>9:34:59.547 [main] WARN kafka.server.BrokerMetadataCheckpoint - No meta.properties file under dir /tmp/kafka-8346130278143417083/meta.properties
09:34:59.567 [main] ERROR kafka.server.KafkaServer - [Kafka Server 0], Fatal error during KafkaServer startup. Prepare to shutdown
java.lang.NoClassDefFoundError: org/apache/kafka/common/network/LoginType
    at kafka.network.Processor.&lt;init&gt;(SocketServer.scala:406)
    at kafka.network.SocketServer.newProcessor(SocketServer.scala:141)
    at kafka.network.SocketServer$$anonfun$startup$1$$anonfun$apply$1.apply$mcVI$sp(SocketServer.scala:94)
    at scala.collection.immutable.Range.foreach$mVc$sp(Range.scala:160)
    at kafka.network.SocketServer$$anonfun$startup$1.apply(SocketServer.scala:93)
    at kafka.network.SocketServer$$anonfun$startup$1.apply(SocketServer.scala:89)
    at scala.collection.Iterator$class.foreach(Iterator.scala:893)
    at scala.collection.AbstractIterator.foreach(Iterator.scala:1336)
    at scala.collection.MapLike$DefaultValuesIterable.foreach(MapLike.scala:206)
    at kafka.network.SocketServer.startup(SocketServer.scala:89)
    at kafka.server.KafkaServer.startup(KafkaServer.scala:219)
    at kafka.utils.TestUtils$.createServer(TestUtils.scala:120)
    at kafka.utils.TestUtils.createServer(TestUtils.scala)
    at org.springframework.kafka.test.rule.KafkaEmbedded.before(KafkaEmbedded.java:154)
    at org.junit.rules.ExternalResource$1.evaluate(ExternalResource.java:46)
    at org.junit.rules.RunRules.evaluate(RunRules.java:20)
    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)
Caused by: java.lang.ClassNotFoundException: org.apache.kafka.common.network.LoginType
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 23 common frames omitted
</code></pre>

<p>The picture shows my directory structure
<a href=""https://i.stack.imgur.com/NFJSc.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/NFJSc.jpg"" alt=""enter image description here""></a></p>

<p>When I look at the list of libraries in the project structure settings of IDEA I see <code>org.apache.kafka:kafka-clients:0.11.0.0</code>; however I cannot import the missing module, which I understand is part of kafka-clients. (<code>org/apache/kafka/common/network/LoginType</code>)</p>

<p><strong>Question</strong></p>

<p>Has anyone come across this error before? Have I misconfigured my gradle file? Is my project directory set up correctly to effectively What might I be missing?perform Kafka Unit testing? I have not found much information on the LoginType yet, but will keep searching.</p>

<p>Here is a copy of gradle build file:</p>

<pre><code>buildscript {
    repositories {
        mavenCentral()
    }misconfigured
    dependencies {
        classpath(""org.springframework.boot:spring-boot-gradle-plugin:1.5.10.RELEASE"")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'

jar {
    baseName = 'calculator'
    version =  '0.1.0'
}

repositories {
    mavenCentral()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    compile(""org.springframework.boot:spring-boot-starter-web"")
    testCompile(""org.springframework.boot:spring-boot-starter-test"")
    compile(""org.springframework.kafka:spring-kafka:1.3.2.RELEASE"")
    testCompile(""org.springframework.kafka:spring-kafka-test"")
}

task wrapper(type: Wrapper) {
    gradleVersion = '2.3'
}
</code></pre>

<p>If there is anything else I might need to include in this question please let me know. Thanks</p>

<p><strong>Unit Test Code</strong></p>

<pre><code>package com.calculator;

/**
 * Created by ian on 2/9/18.
 */
import com.calculator.kafka.services.*;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertThat;
import static org.springframework.kafka.test.assertj.KafkaConditions.key;
import static org.springframework.kafka.test.hamcrest.KafkaMatchers.hasValue;

import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule;
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.kafka.core.DefaultKafkaConsumerFactory;
import org.springframework.kafka.listener.KafkaMessageListenerContainer;
import org.springframework.kafka.listener.MessageListener;
import org.springframework.kafka.listener.config.ContainerProperties;
import org.springframework.kafka.test.rule.KafkaEmbedded;
import org.springframework.kafka.test.utils.KafkaTestUtils;

import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class KafkaTest {

//    private static final Logger LOGGER = LoggerFactory.getLogger(KafkaTest.class);
    private static final String TEMPLATE_TOPIC = ""input"";
    private static String SENDER_TOPIC = ""input"";
    @ClassRule
    public static KafkaEmbedded embeddedKafka = new KafkaEmbedded(1, true, TEMPLATE_TOPIC);

    private KafkaMessageListenerContainer&lt;String, Integer&gt; container;

    private BlockingQueue&lt;ConsumerRecord&lt;String, Integer&gt;&gt; records;

    @Autowired
    private KafkaConsumer consumer;

    @Before
    public void setUp() {
        // Set up the consumer properties
        Map&lt;String, Object&gt; integerProperties = KafkaTestUtils.consumerProps(""jsa-group"", ""false"", embeddedKafka);

        // create a Kafka consumer factory
        DefaultKafkaConsumerFactory&lt;String, Integer&gt; consumerFactory = new DefaultKafkaConsumerFactory&lt;String, Integer&gt;(integerProperties);

        // set the topic that needs to be consumed
        ContainerProperties containerProperties = new ContainerProperties(SENDER_TOPIC);

        // create a Kafka MessageListenerContainer
        container = new KafkaMessageListenerContainer&lt;&gt;(consumerFactory, containerProperties);

        // setup a Kafka message listener
        container.setupMessageListener(new MessageListener&lt;String, Integer&gt;() {
            @Override
            public void onMessage(ConsumerRecord&lt;String, Integer&gt; record) {
//                LOGGER.debug(""test-listener received message='{}'"", record.toString());
                records.add(record);
            }
        });

        // start the container and underlying message listener
        container.start();
    }

    @After
    public void tearDown() {
        // stop the container
        container.stop();
    }

    @Test
    public void testTemplate() throws Exception {
        // send the message
        String greeting = ""Hello Spring Kafka Sender!"";
        Integer i1 = 12;
        consumer.processMessage(i1);

        // check that the message was received
        ConsumerRecord&lt;String, Integer&gt; received = records.poll(10, TimeUnit.SECONDS);
        // Hamcrest Matchers to check the value
        assertThat(received, hasValue(i1));
        // AssertJ Condition to check the key
        assertThat(received).has(key(null));
    }
}
</code></pre>
",https://stackoverflow.com/questions/48723349/how-do-i-resolve-an-error-in-my-configuration-when-trying-to-unit-test-a-spring,"['spring', 'unit-testing', 'intellij-idea', 'apache-kafka']",1500,TRUE,1,1
Angular4: How to mock return value of 2 http calls called in sequence,"<p>I have a function that makes 2 sequential HTTP calls - the second call is made depending on the result of the first call. How can I mock both calls correctly when unit testing?</p>

<p>component.ts</p>

<pre><code>getValue(): Promise&lt;any[]&gt; {
    return this.http.get(URL1).toPromise()   // FIRST CALL
        .then(data =&gt; {
            this.enable = data.json()['enable'];
        })
        .then(() =&gt; {
            if (this.enable) {
                return new Promise&lt;any[]&gt;((resolve) =&gt; {
                    this.http.get(URL2).toPromise()  // SECOND CALL
                        .then(res =&gt; res.json()));
                });
            }
        })
        .catch(() =&gt; {
            return new Promise&lt;any[]&gt;((resolve) =&gt; resolve([]));
        });
}
</code></pre>

<p>component.spec.ts</p>

<pre><code>beforeEach(() =&gt; {
    TestBed.configureTestingModule({
        imports: [HttpModule],
        providers: [...]
    });
    service = TestBed.get(...);
    http = TestBed.get(Http);
});

it('getValue works as expected when call succeeds',() =&gt; {
    spyOn(http, 'get').and.returnValue(of({enable: true}));  // return of firstcall
    spyOn(http, 'get').and.returnValue(of(RAW_DATA));  // return of second call
    service.getValue ('uuid')
        .then(data =&gt; {
            expect(data).toEqual(expectedData);
        });
});
</code></pre>
",https://stackoverflow.com/questions/52725653/angular4-how-to-mock-return-value-of-2-http-calls-called-in-sequence,['angular'],29,FALSE,0,1
How to test a specific spec.ts file in Angular 4?,"<p>I am a novice in Angular. I am using Angular 4 in my current project.I was learning Unit testing with angular, just wanted to know if I can test a specific spec.ts file alone. </p>

<p>Any help is appreciated.</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/48315691/how-to-test-a-specific-spec-ts-file-in-angular-4,"['angular', 'unit-testing', 'karma-runner', 'karma-jasmine']",5025,TRUE,3,3
Is it possible to load url and get the browser rendered DOM object using Jest or any other testing library/framework?,"<p>I want to get the browser rendered DOM object rather than mocking DOM object. Is it possible to load url and get the browser rendered DOM object using Jest or any other unit testing library/framework?</p>
",https://stackoverflow.com/questions/52252135/is-it-possible-to-load-url-and-get-the-browser-rendered-dom-object-using-jest-or,"['javascript', 'jquery', 'unit-testing', 'mocha.js', 'jestjs']",127,TRUE,0,1
Not able to mock AccountManager class in Kotlin which is using RxJava,"<p>This is my code in kotlin and RxJava, I am trying to test method by mocking accountManager class from Android but not able to mock it :( .</p>

<p>Creating variable like this:</p>

<pre><code>private val accountManager:AccountManager= mock()
private val ACCOUNT_1 = Account(""XXXXX"", BuildConfig.APPLICATION_ID)
</code></pre>

<p>Injecting </p>

<pre><code>userLocalDataSource = UserLocalDataSource(accountManager)
</code></pre>

<p>Method to test :</p>

<pre><code>    override fun update(user: User, country: Country): Observable&lt;User&gt; {
    return Observable.create&lt;User&gt; {
        disposable -&gt;
        val accounts = accountManager.getAccountsByType(ACCOUNT_TYPE)
        for (account in accounts) {
            if (disposable.isDisposed) break
            val userId = accountManager.getUserData(account, KEY_USER_ID)
            if (account.name == country.appName &amp;&amp; user.id == userId) {
                accountManager.setUserData(account, KEY_USER_ID, user.id)
                accountManager.setUserData(account, KEY_USER_NAME, user.username)
                accountManager.setUserData(account, KEY_USER_FIRST_NAME, user.firstName)
                accountManager.setUserData(account, KEY_USER_LAST_NAME, user.lastName)
                accountManager.setUserData(account, KEY_USER_EMAIL, user.email)
                accountManager.setPassword(account, user.secret)
                accountManager.setUserData(account, KEY_USER_COUNTRY_ID, country.id.toString())
                accountManager.setUserData(account, KEY_USER_PHOTO, user.image?.url)
                disposable.onNext(user)
            }
        }
        disposable.onComplete()
    }
}
</code></pre>

<p>Unit testing method:</p>

<pre><code>@Test
fun testUpdate(){
    Mockito.`when`(accountManager.getAccountsByType(BuildConfig.APPLICATION_ID)).thenReturn(arrayOf(ACCOUNT_1))
    val result=userLocalDataSource.update(user,Country.GERMANY).blockingFirst()
    assertEquals(""XXX"",result?.username)
}
</code></pre>
",https://stackoverflow.com/questions/48440525/not-able-to-mock-accountmanager-class-in-kotlin-which-is-using-rxjava,"['android', 'unit-testing', 'kotlin', 'mockito', 'rx-java2']",430,FALSE,1,0
"Can I execute unit test EcmaScript 6(2015) code on Headless Browser like Phantom Js ? If no, Can you mention any other way to achieve this?","<p>I am unit testing angular application.</p>

<p>I couldn't able to execute unit tests of code which are written using ES6 on Chutzpah.</p>

<p>What could be the possible solution?</p>

<p><strong><em>I need a stable way to achieve this.</em></strong></p>
",https://stackoverflow.com/questions/48862481/can-i-execute-unit-test-ecmascript-62015-code-on-headless-browser-like-phantom,"['angularjs', 'unit-testing', 'phantomjs', 'puppeteer', 'chutzpah']",127,TRUE,0,1
The response is not a view message when unit test fails in laravel,"<p>I am new in laravel 5.5 unit testing.</p>

<p>I wrote a method in <code>NewsController</code> names index. It returns a view like below:</p>

<pre><code>public function index(Request $request)
{
     $news = DB::table('news')-&gt;orderBy('created_at', 'desc')-&gt;get();
     $data['news'] = $news;
     return view('news.index')-&gt;with($data);
}
</code></pre>

<p>I wrote a test for that like below:</p>

<pre><code> public function testIndex(){
     factory(News::class, 10)-&gt;create();
    $news = DB::table('news')-&gt;orderBy('created_at', 'desc')-&gt;get();
    $this-&gt;get('/admin/news')
       -&gt;assertViewHas('news', $news)
       -&gt;assertStatus(200);
}
</code></pre>

<p>But test failed. The message is:</p>

<p><code>The response is not a view.</code></p>

<p>Can anyone help me?</p>
",https://stackoverflow.com/questions/50104091/the-response-is-not-a-view-message-when-unit-test-fails-in-laravel,"['php', 'phpunit', 'laravel-5.5']",1251,TRUE,2,1
use doNothing() for method with return type in mockito,"<pre><code>public void attestResults(List&lt;OMInvestigationResultMutableDTO.Id&gt; resultIds, OMRequestSpeciality speciality)
{
  List&lt;Answer.Id&gt; attestIds = new ArrayList&lt;Answer.Id&gt;();
  for (OMInvestigationResultMutableDTO.Id id : resultIds)
  {
    Answer.Id answerId = answerIdFactory.createId(id.getValue(), null);
    attestIds.add(answerId);
  }

  orderManagementServiceProvider.getOrderManagementService()
    .attestResults(attestIds, 
  RequestSpeciality.valueOf(speciality.toString()));
}
</code></pre>

<p>My problem is how to write unit testing for attestResults()..
I want to try mock orderManagementServiceProvider.getOrderManagementService().attestResults() using doNothing() in mockito.</p>

<p>This is the method orderManagementServiceProvider.getOrderManagementService().attestResults,</p>

<pre><code>public List&lt;Id&gt; attestResults(List&lt;Id&gt; answerIds, RequestSpeciality speciality) {
    this.accessHandler.checkAccess(AccessRights.ATTEST_RESULTS);
    ArgumentValidator.argument(answerIds, ""AnswerIds"").notNull().notEmpty();
    ArgumentValidator.argument(speciality, ""Speciality"").notNull();
    ResultCreator resultCreator = new ResultCreator(this.resultToolkitAdapter, this.pathologyReportToolkitService);
    return resultCreator.attestResults(answerIds, speciality);
}
</code></pre>

<p>In this case I have not permission to use powerMockito.</p>

<p>I mocked 
  <code>when(orderManagementServiceProvider.getOrderManagementService()).thenReturn(omService);</code></p>
",https://stackoverflow.com/questions/48989739/use-donothing-for-method-with-return-type-in-mockito,"['java', 'unit-testing', 'methods', 'mockito']",3016,TRUE,2,2
Laravel Unit Test (The response is not a view),"<p>I am doing unit testing to my web application. My experience with Laravel and PHP Unit Testing too young. Now, I am just fiddling around with the Laravel Unit test. Now, I am testing if a view returned to the route contains specific text. Very simple. This is what I have done.</p>

<p>I created a view called, unit_test.blade.php with the following content</p>

<pre><code>&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;title&gt;&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
    This is unit test
&lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p>This is the route to display that view</p>

<pre><code>Route::get('unit/test', function(){
   return view('unit_test');
});
</code></pre>

<p>This is my test class and function</p>

<pre><code>class ApiV2EventController extends TestCase
{


    public function testUnitTest()
    {
        $response = $this-&gt;get('unit/test');

        $response-&gt;assertViewHas('unit');
    }
}
</code></pre>

<p>My test function is simple. It is just checking if the view contains the text, ""unit"". But when I run the test in the command line, it is giving </p>

<pre><code>There was 1 failure:

1) Tests\Feature\ApiV2EventController::testUnitTest
The response is not a view.
</code></pre>

<p>I am returning the view in the route. What is wrong with my code? How can I test it?</p>
",https://stackoverflow.com/questions/51445065/laravel-unit-test-the-response-is-not-a-view,"['php', 'laravel', 'unit-testing']",6357,TRUE,4,3
TypeError: this.props.myMaterials.fetch is not a function,"<p>I'm working on jest unit testing using <code>react-test-renderer</code>.The test cases fails and showing this error  </p>

<blockquote>
  <p>""TypeError: this.props.myMaterials.fetch is not a function""</p>
</blockquote>

<p>where <code>this.props.notes.fetch</code> is inside the <code>componentWillMount</code>.Is there any solution to fix this without using enzyme?</p>

<p>myComponent.jsx :</p>

<pre><code>class myComponent extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          column: this.getColumns(),
          pageNotFound: false
        };
      }


      componentWillMount() {
        this.props.notes.fetch(this.props.courseId);
        window.addEventListener('resize', this.handleResizeEvent);
        this.handleError = EventBus.on(constants.NOTES_NOT_FOUND, () =&gt; {
          this.setState({ pageNotFound: true });
        });
      }

      componentDidMount() {
        window.addEventListener('resize', this.handleResizeEvent);
      }

      componentWillUnmount() {
        window.removeEventListener('resize', this.handleResizeEvent);
        this.handleError();
      }

      handleResizeEvent = () =&gt; {
        this.setState({ column: this.getColumns() });
      };

      getColumns = () =&gt; (window.innerWidth &gt; (constants.NOTES_MAX_COLUMNS * constants.NOTES_WIDTH) ?
        constants.NOTES_MAX_COLUMNS :
        Math.floor(window.innerWidth / constants.NOTES_WIDTH))

      callback = (msg, data) =&gt; {
      }
      render() {
        const { notes, language } = this.props;
        if (this.state.pageNotFound) {
          return (&lt;div className=""emptyMessage""&gt;&lt;span&gt;Empty&lt;/span&gt;&lt;/div&gt;);
        }
        if (notes.loading) {
          return (&lt;Progress/&gt;);
        }
        // To Refresh Child component will receive props
        const lists = [...notes.cards];
        return (
          &lt;div className=""notesContainer"" &gt;
            &lt;NoteBook notesList={lists} callback={this.callback} coloums={this.state.column} /&gt;
          &lt;/div&gt;
        );
      }
    }

myComponent.propTypes = {
  notes: PropTypes.object,
  courseId: PropTypes.string,
  language: PropTypes.shape(shapes.language)
};
export default withRouter(myComponent);
</code></pre>

<p>myComponent.test.jsx:</p>

<pre><code>const tree = renderer.create(
&lt;myComponent.WrappedComponent/&gt;).toJSON();
expect(tree).toMatchSnapshot();
});
</code></pre>
",https://stackoverflow.com/questions/48221748/typeerror-this-props-mymaterials-fetch-is-not-a-function,"['javascript', 'reactjs', 'jestjs']",1581,TRUE,-1,3
test case for a react component method with jest and enzyme,"<p>I am new to unit testing. I have a react 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 default class Login extends Component{
  constructor(){
    super()
    this.state={
      email: '',
      password:'',
      validFields: false
    }
    
    this.handleChangeInput = this.handleChangeInput.bind(this);
  }
  
  handleChangeInput(e){
    const name = e.target.name;
    const value = e.target.value;
    this.setState({[name]: value});
    if (this.state.email.length&gt;0 &amp;&amp;         this.state.password.length&gt;0 ) {
      this.setState({validFields: true});
    } else {
      this.setState({validFields: false});
    }
  }
  
  render() {
    return (
      &lt;div&gt;
        &lt;form onSubmit={this.handleLoginSubmit}&gt;
          &lt;div className=""input""&gt;
            &lt;input id=""email"" type=""text"" name =""email"" placeholder=""Email"" value={this.state.email} onChange={this.handleChangeInput}/&gt;
          &lt;/div&gt;
          &lt;div className=""input""&gt;
            &lt;input id=""password"" type=""password"" name=""password"" placeholder=""Password"" value={this.state.password} onChange={this.handleChangeInput}/&gt;
          &lt;/div&gt;
          &lt;input id=""submitButton"" type=""submit"" value =""LOG IN"" disabled={!this.state.validFields}/&gt;
        &lt;/form&gt;
      &lt;/div&gt;
    )
  }
}</code></pre>
</div>
</div>
</p>

<p>Now I want to test the function handleChangeInput(e). Can anyone help to simulate the test case for the function ? I am using jest and enzyme.</p>
",https://stackoverflow.com/questions/49629521/test-case-for-a-react-component-method-with-jest-and-enzyme,"['javascript', 'reactjs', 'unit-testing', 'enzyme', 'jestjs']",2985,FALSE,0,1
How do I add a unit test target to a notification service extension for an app?,"<p>I have a notification service extension and I need to add a target for unit testing, but the option for adding the unit test target to the SE is greyed out. What is the best way to get a test target to hit my SE?</p>
",https://stackoverflow.com/questions/49059536/how-do-i-add-a-unit-test-target-to-a-notification-service-extension-for-an-app,"['ios', 'xcode', 'unit-testing']",270,FALSE,6,0
React + Karma : Uncaught ReferenceError: require is not defined\nat,"<p>Following is my spec file for the unit testing of the react component (<strong>helloworld.spec.js</strong>): </p>

<pre><code>import React from 'react';
import ReactTestUtils from 'react-dom/test-utils'; // ES6
import {HelloWorld} from './helloworld';

describe(""HelloWorld Test"",function(){

it(""check header"", function(){
    var component = ReactTestUtils.renderIntoDocument(
                    &lt;HelloWorld /&gt;
                    );
    var eventRow = TestUtils.findRenderedDOMComponentWithTag(
        component, 'h1'
        );
    expect(eventRow.getDOMNode().textContent)
    .toEqual(""template header"");
  });
});
</code></pre>

<p>And here is the <strong>helloworld.js</strong>:</p>

<pre><code>import React from 'react';

export class HelloWorld extends React.Component{
    render(){
        return(
            &lt;h1&gt;Hello World!&lt;/h1&gt;
        )
    }
}
</code></pre>

<p>I have setup karma and jasmine for the unit testing and getting the error :</p>

<p><strong>{
    ""message"": ""Uncaught ReferenceError: require is not defined\nat src/components/hello-world/helloworld.spec.js:3:14\n\nReferenceError: require is not defined\n    at src/components/hello-world/helloworld.spec.js:3:14"",
    ""str"": ""Uncaught ReferenceError: require is not defined\nat src/components/hello-world/helloworld.spec.js:3:14\n\nReferenceError: require
 is not defined\n    at src/components/hello-world/helloworld.spec.js:3:14""
  }</strong></p>

<p>But I don't see require in the code so how come it's not defined.
Any leads for where the issue could be, probably a config one?</p>
",https://stackoverflow.com/questions/48919981/react-karma-uncaught-referenceerror-require-is-not-defined-nat,"['reactjs', 'karma-jasmine']",671,FALSE,0,1
How to Unit Test a Ruby on Rails Application,"<p>My company recently received a new contract in which the client's technologies are Ruby and Ruby on Rails. I've finished learning those, but am really struggling to learn how to do Unit Testing. Since Unit Testing (and then other testing after that) are the primary goals for the first portion of the project, it's crucial that I figure this out.</p>

<p>In all of my research and googling, I've come across technologies such as Rspec, Faker, FactoryBot, Capybara, Launchy, MiniTest, etc. However, I'm not finding anything super helpful with any of it.</p>

<p>Please advise the best gems to use and links to learn, in depth, how to use those gems.</p>

<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/51428176/how-to-unit-test-a-ruby-on-rails-application,"['ruby-on-rails', 'ruby', 'unit-testing', 'testing', 'tdd']",410,TRUE,-1,2
Asp.net core session unit test,"<p>I hava a problem with unit testing asp.net core mvc controller!
the problem is that in my controller, i use sessions:</p>

<pre><code>[HttpPost]
public IActionResult OpretLobby(LobbyViewModel lobby)
{
    try
    {
        //find brugeren der har lavet lobby
        var currentUser = HttpContext.Session.GetObjectFromJson&lt;User&gt;(""user"");
        //save as a lobby
        ILobby nyLobby = new Lobby(currentUser.Username)
        {
            Id = lobby.Id
        };
        SessionExtension.SetObjectAsJson(HttpContext.Session, lobby.Id, nyLobby);
        //add to the list
        _lobbyList.Add(nyLobby);
        return RedirectToAction(""Lobby"",""Lobby"",lobby);
    }
</code></pre>

<p>this all works perfectly well online on the server, nothing wrong here.
BUT when it comes to the demand of unit testing this whole thing, its not so perfect anymore. </p>

<p>basicly the problem is, that i cant get access to my session from a test.. i have tryed in many ways to create mocks and what not, but most of the solutions work for .net framework, and not for .net core for some reason! please help im in pain! </p>

<p>note: </p>

<p>i used a dummy version of a test to isolate this problem:</p>

<pre><code>[Test]
public void TestIsWorking()
{
    SessionExtension.SetObjectAsJson(uut.HttpContext.Session, ""user"", _savedUser);
    //ViewResult result = uut.OpretLobby(lobbyViewModel) as ViewResult;

    //Assert.AreEqual(""OpretLobby"", result.ViewName);
    Assert.AreEqual(1,1);
}
</code></pre>

<p>goes wrong also here trying to set the session for a user :/</p>
",https://stackoverflow.com/questions/50066893/asp-net-core-session-unit-test,"['c#', 'session', 'asp.net-core-mvc']",3001,TRUE,3,3
How to Stub a jquery selector in Sinon js,"<p>I'm doing some unit testing, and I stuck trying to stub this method.
I'm also using materialize for dropdown, which I believe is related.
Does someone faced this problem and can help?</p>

<p>My code goes</p>

<pre><code>componentDidUpdate() {
    $('.dropdown-trigger-filter').dropdown({belowOrigin: true, alignment: 'right', closeOnClick: false});
    this.controller.isFirstLoginRedirect(this.props);
}
</code></pre>

<p>My test:</p>

<pre><code>describe('Home Component', async () =&gt; {
    let container = props =&gt; { return &lt;Home store={store} {...props} /&gt;;    };

    it('should render correctly', () =&gt; {
        const props = {};
        const wrapper = mount(shallow(container(props)).get(0));
        const tree = renderer.create(container(props)).toJSON();

        expect(tree).matchSnapshot();
    });

    it('should change state of selected tab to quotes ', () =&gt; {
        const props = {};
        const wrapper = mount(shallow(container(props)).get(0));
        const $ = sinon.stub();
        $.withArgs('.dropdown-trigger-filter').returns({});
        (wrapper.find('.tab').at(0)).simulate('click');
        expect(wrapper.state('selectedTab')).equal('##quotes');
        expect(wrapper.debug()).matchSnapshot();
    });
});
</code></pre>

<p>Error: </p>

<pre><code> TypeError: $(...).dropdown is not a function
</code></pre>
",https://stackoverflow.com/questions/51505239/how-to-stub-a-jquery-selector-in-sinon-js,"['javascript', 'jquery', 'unit-testing', 'sinon']",464,FALSE,0,1
How to print log during karma Testing,"<p>I am a beginner for Angular, recently I started working on Angular.
I have written some unit testing code, as follows.</p>

<pre><code>it('fetch data should be correct',
inject(
  [HttpTestingController, Service2Service],
  (
    httpMock: HttpTestingController,
    dataService: Service2Service
  ) =&gt;{
        dataService.getData().subscribe((event: HttpEvent&lt;any&gt;) =&gt; {
          console.info(""HttpEventType.Response"",HttpEventType.Response);
          switch (event.type) {
            case HttpEventType.Response:{
              console.log(""body"",event.body);
              expect(event.body.length).toEqual(110);
            }
          }
        });
      }
  )
</code></pre>

<p>);</p>

<p>I am trying to print using console.log but it not printing on console.
Kindly suggest another way to print log.</p>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/53313287/how-to-print-log-during-karma-testing,"['angular', 'unit-testing', 'karma-jasmine']",8610,TRUE,5,1
CGREEN compilation error: ‘assertion_tests’ does not name a type,"<p>When I try to compile cgreen unit testing framework in cygwin64 I get this error:</p>

<pre><code>[ 34%] Building CXX object tests/CMakeFiles/cgreen_cpp_tests.dir/assertion_tests.cpp.o
/home/Administrator/cgreen/tests/assertion_tests.cpp:1:1: error: ‘assertion_tests’ does not name a type 
assertion_tests.c 
^~~~~~~~~~~~~~~ 
make[2]: *** [tests/CMakeFiles/cgreen_cpp_tests.dir/build.make:63: tests/CMakeFiles/cgreen_cpp_tests.dir/assertion_tests.cpp.o] Error 1 
make[1]: *** [CMakeFiles/Makefile2:1615: tests/CMakeFiles/cgreen_cpp_tests.dir/all] Error 2 make: *** [Makefile:161: all] Error 2
</code></pre>

<p>I have searched on google with no result.</p>

<p>I am using cygwin64 with cmake 3.6.2 and gcc 7.3.0</p>

<p>Any help will be appreciated!</p>
",https://stackoverflow.com/questions/53252103/cgreen-compilation-error-assertion-tests-does-not-name-a-type,"['c++', 'c', 'unit-testing']",82,TRUE,0,1
Response status code [200] is not a redirect status code. Failed asserting that false is true,"<p>this is my code laravel unit testing for login </p>

<pre><code>public function testClientSucceslogin()
{
    $user = factory(User::class)-&gt;create([
        'password' =&gt; 'secret',
        'status' =&gt; User::STATUS_ACTIVE,
        'type' =&gt; User::TYPE_CLIENT
    ]);
    $clientProfile = ClientProfile::where('client_id', $user-&gt;client_id)-&gt;first();
    $client_alias = Client::where('id', $user-&gt;client_id)-&gt;first();

    $this-&gt;get(route('login', [$user-&gt;email, $user-&gt;password]))
        -&gt;assertStatus(200)
        -&gt;assertRedirect('dashboard', [$client_alias-&gt;alias, $clientProfile-&gt;id])
        -&gt;assertTrue(true);


}
</code></pre>

<p>and I got this error</p>

<pre><code>Response status code [200] is not a redirect status code. Failed asserting that false is true.
</code></pre>

<p>and i changed status code to 302 but i got this error</p>

<pre><code>enter code heExpected status code 302 but received 200.
</code></pre>

<p>Failed asserting that false is true.</p>

<p>How I can fix this issue?</p>
",https://stackoverflow.com/questions/48484868/response-status-code-200-is-not-a-redirect-status-code-failed-asserting-that,"['unit-testing', 'testing', 'laravel-5', 'laravel-5.4', 'laravel-testing']",2548,FALSE,0,1
Angular Unit Test SpyOn giving me errors,"<p>I am trying to do the unit testing for services, I mocked the data and expecting some result but getting error
Below is my component ts file 
ts file</p>

<pre><code>setPrefixSuffixDetails(): void {
    this.profileService.getPrefixSuffixDetails()
      .subscribe(
        data =&gt; {
          if(data.body.prefixlist.length &gt; 0) {
            this.prefixConfig.options = data.body.prefixlist;
          }
        }
      );
  }
</code></pre>

<p>Below is my 
Spec.ts File</p>

<pre><code>providers: [{provide: ProfileService, useClass: ProfileStub}]

beforeEach(() =&gt; {
        fixture = TestBed.createComponent(ProfileBeneficiariesViewComponent);
        component = fixture.componentInstance;
        component.ngOnInit();
        profileService = fixture.debugElement.injector.get(ProfileService);
    });

    let data = {body:['prefixList']}
    it('should have a method to get details', () =&gt; {
    profileService = fixture.debugElement.injector.get(ProfileService);

    spyOn(profileService, 'getPrefixSuffixDetails').and.callThrough();
             component.ngOnInit();
     expect(data.body).toContain([ 'prefixlist' ]);

 });
</code></pre>

<p>Error which I am getting is below</p>

<pre><code>Error: &lt;spyOn&gt; : could not find an object to spy upon for setPrefixSuffixDetails()
Usage: spyOn(&lt;object&gt;, &lt;methodName&gt;)


class ProfileStub {
        getPrefixSuffixDetails = function () {
            return Observable.of(data);
        }
</code></pre>
",https://stackoverflow.com/questions/50706995/angular-unit-test-spyon-giving-me-errors,"['typescript', 'angular5', 'karma-jasmine']",1494,FALSE,1,2
unit test of domain classes in spring boot 2,"<p>Strangely, I have not found any guides, tutorials, examples, videos, etc about how specifically make unit testing of domain classes in an application developed using spring boot 2. Domain classes are using JPA annotations.</p>

<p>Any suggestions??</p>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/51145760/unit-test-of-domain-classes-in-spring-boot-2,"['spring-boot', 'spring-test']",599,FALSE,0,0
ReferenceError : File is not defined,"<p>I am doing react unit testing using mocha and enzyme. I'm checking whether data passed is an instance of File </p>

<pre><code>if (data instanceof File) {} 
</code></pre>

<p>What package should I import/require in order for this to work?</p>

<p>Note: The code works actually, it's only during testing that I'm having problems</p>
",https://stackoverflow.com/questions/49789615/referenceerror-file-is-not-defined,"['reactjs', 'file', 'unit-testing', 'mocha.js', 'enzyme']",3149,FALSE,4,0
Angular 2+ testing a component,"<p>I have the following service which make a call to an API :  </p>

<pre><code>export class MoviesService {

    constructor(private httpClient: HttpClient) { }

    // Return an obsevable with all the movies from the API
    getAllMovies(): Observable&lt;Movie[]&gt; {
        return this.httpClient.get&lt;EmbeddedTitle&gt;(""http://localhost:8080/api/movies"", { params: params })
        .pipe(
            map(response =&gt; {
                return response;
            }
            ));
}
</code></pre>

<p>And here's the component that inject that service and call the <strong>getAllMovies</strong> method:  </p>

<pre><code>export class MoviesListingComponent implements OnInit {

    public movies: Movie[];

    constructor(private moviesService: MoviesService) { }

    ngOnInit(): void {
        this.getAllMovies();
    }

    // Subscribe to method service (getAllMovies) and assign the results to a class object (movies)
    getAllMovies(): void {
        this.moviesService.getAllMovies()
            .subscribe(movies =&gt; {
                this.movies = movies;
            });
    }

}
</code></pre>

<p>I want to know how to unit testing the component's method <strong>getAllMovies</strong> with Jasmine.</p>
",https://stackoverflow.com/questions/51865174/angular-2-testing-a-component,"['javascript', 'angular', 'unit-testing', 'jasmine', 'angular6']",35,FALSE,-1,1
How do you unit test a firebase function wrapped with express?,"<p>With firebase functions, you can utilize express to achieve nice functionality, like middleware etc. I have used <a href=""https://github.com/firebase/functions-samples/blob/master/authorized-https-endpoint/functions/index.js"" rel=""noreferrer"">this example</a> to get inspiration of how to write https firebase functions, powered by express.</p>

<p>However, my issue is that <a href=""https://firebase.google.com/docs/functions/unit-testing"" rel=""noreferrer"">the official firebase documentation on how to do unit testing</a>, does not include a https-express example.</p>

<p>So my question is how to <strong>unit test</strong> the following function (typescript)?: </p>

<pre><code>// omitted init. of functions
import * as express from 'express';

const cors = require('cors')({origin: true});
const app = express();
app.use(cors);

// The function to test
app.get('helloWorld, (req, res) =&gt; {
   res.send('hello world');
   return 'success';
});

exports.app = functions.https.onRequest(app);
</code></pre>
",https://stackoverflow.com/questions/49352060/how-do-you-unit-test-a-firebase-function-wrapped-with-express,"['firebase', 'google-cloud-functions']",5270,TRUE,21,7
Inner Dependency Injection in groovy grails,"<p>In groovy/grails, I am using SPOC and junit framework for unit testing and I want to inject <strong>MockDatabaseService</strong> for the unit test <strong>TestControllerSpec</strong></p>

<pre><code>import org.springframework.beans.factory.annotation.Autowired
import grails.testing.web.controllers.ControllerUnitTest
import spock.lang.Specification

//Controller
class TestController {

    @Autowired
    BusinessService businessService

    def callServiceMethod() {

        businessService.callBusinessServiceMethod()
    }
}

//Business Service
class BusinessService {

    @Autowired
    DatabaseService databaseService

    def callBusinessServiceMethod() {
        databaseService.callDBServiceMethod()
    }
}

//Database service
class DatabaseService {


    def callDBServiceMethod() {

    }

}

//Unit test
class TestControllerSpec extends Specification implements ControllerUnitTest&lt;TestController&gt; {

    //Need to pass the MockDatabaseService instead of DatabaseService

    def ""test ""(){

        controller.callServiceMethod()
    }
}

//Mocked DatabaseService
class MockDatabaseService {

    def callDBServiceMethod() {

        //Mock method
    }

}
</code></pre>

<p>I am trying to inject the Mock for DatabaseService inside the TestControllerSpec, how can we achieve it?</p>
",https://stackoverflow.com/questions/52552745/inner-dependency-injection-in-groovy-grails,"['grails', 'groovy', 'spock']",318,FALSE,0,1
Can&#39;t bind to &#39;routerDirection&#39; since it isn&#39;t a known property of &#39;div&#39;,"<p>I have created Application using ionic 4, and I have added routerDirection to my div</p>

<pre><code>&lt;div class=""finger-print-content"" (click)=""loginUsingFingerprint()"" [routerDirection]=""'forward'""&gt;
      &lt;img class=""fingerprint-btn-img"" src=""assets/images/fingerprint.png""&gt;
      &lt;p class=""fingerprint-btn-text"" translate&gt;SIGN_IN_USING_FINGERPRINT&lt;/p&gt;
    &lt;/div&gt;
  &lt;/div&gt;
</code></pre>

<p>when run<code>ionic serve</code> all of things working fine and I serve application in  browser , but when I need to run unit testing <code>ng test</code> I see that error.</p>

<pre><code>Can't bind to 'routerDirection' since it isn't a known property of 'div'
</code></pre>
",https://stackoverflow.com/questions/53722012/cant-bind-to-routerdirection-since-it-isnt-a-known-property-of-div,"['unit-testing', 'ionic3', 'ionic4']",362,TRUE,0,1
expressJS/jestJS: How to split get() function to write simple jest unit test?,"<p>How do I define a get() routing in an expressJS application with the intention of doing easy unit testing?</p>

<p>So as a first step I moved the function of <code>get()</code> in an own file:</p>

<p><strong>index.js</strong></p>

<pre><code>const express = require('express')
const socketIo = require('socket.io')
const Gpio = require('pigpio').Gpio

const app = express()
const server = http.createServer(app)
const io = socketIo(server)

const setStatus = require('./lib/setStatus.js')

app.locals['target1'] = new Gpio(1, { mode: Gpio.OUTPUT })

app.get('/set-status', setStatus(app, io))
</code></pre>

<p><strong>lib/setStatus.js</strong></p>

<pre><code>const getStatus = require('./getStatus.js')

module.exports = (app, io) =&gt; {
  return (req, res) =&gt; {
    const { id, value } = req.query // id is in this example '1'
    req.app.locals['target' + id].pwmWrite(value))
    getStatus(app, io)
    res.send({ value }) // don't need this
  }
}
</code></pre>

<p><strong>lib/getStatus.js</strong></p>

<pre><code>const pins = require('../config.js').pins

module.exports = async (app, socket) =&gt; {
  const res = []
  pins.map((p, index) =&gt; {
    res.push(app.locals['target' + (index + 1)].getPwmDutyCycle())
  })
  socket.emit('gpioStatus', res)
}
</code></pre>

<p>So first of all I'm not quite sure, if I split that code correctly - thinking of doing unit testing.</p>

<p>For me the only thing which has to be done by calling <code>/set-status?id=1&amp;value=50</code> is to call <code>pwmWrite()</code> for an (I guess) object, which is defined by <code>new Gpio</code> and stored in <code>locals</code> of expressJS.</p>

<p>And for the second: If this should be the correct way, I do not understand how to write a jestJS unit test to check if <code>pwmWrite</code> has been called - which is inside of an asyncronous function.</p>

<p>This is my attempt, but I can't test for the inside call of pwmWrite:</p>

<pre><code>test('should call pwmWrite() and getStatus()', async () =&gt; {
  const app = {}
  const io = { emit: jest.fn() }
  const req = {
    app: {
      locals: {
        target1: { pwmWrite: jest.fn() }
        }
      }
    }
  }
  expect.assertions(1)
  expect(req.app.locals.target1.pwmWrite).toHaveBeenCalled()
  await expect(getStatus(app, io)).toHaveBeenCalled()
})
</code></pre>
",https://stackoverflow.com/questions/52842582/expressjs-jestjs-how-to-split-get-function-to-write-simple-jest-unit-test,"['javascript', 'unit-testing', 'express', 'jestjs']",738,TRUE,5,1
jasmine angular 4 unit test router.url,"<p>I am unit testing a function in angular 4 project using jasmine which a switch  statement like mentioned below:</p>

<pre><code>    switch(this.router.url) {

    case 'firstpath': {
               // some code
            }
        break;
    case 'secondpath': {
               // some more code
            }
       break;
    default:
        break;

    }
</code></pre>

<p>In my spec.ts file. I can't stub or change the value of router.url.I want my cases to execute but default is executing. I tried different ways to set or spyOn and return value, but everytime url is '/'. Every suggestion or solution will be welcomed.  </p>
",https://stackoverflow.com/questions/53314181/jasmine-angular-4-unit-test-router-url,"['angular', 'unit-testing', 'karma-jasmine', 'router']",29846,TRUE,17,2
java.lang.RuntimeException: Method i in android.util.Log not mocked,"<p>I am working in android studio.
I'm training to understand how to do unit testing. 
when I run my test i have this error:
<strong>java.lang.RuntimeException: Method i in android.util.Log not mocked. See <a href=""http://g.co/androidstudio/not-mocked"" rel=""nofollow noreferrer"">http://g.co/androidstudio/not-mocked</a> for details.</strong></p>

<p>thank in advance.</p>

<pre><code>    package com.bignerdranch.android.beatbox;

import org.junit.Before;
import org.junit.Test;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

public class SoundViewModelTest {
    private BeatBox mBeatBox;
    private Sound mSound;
    private SoundViewModel mSubject;

    @Before
    public void setUp() throws Exception {
        mBeatBox = mock(BeatBox.class);
        mSound = new Sound(""assetPath"");
        mSubject = new SoundViewModel(mBeatBox);
        mSubject.setSound(mSound);
    }

    @Test
    public void exposesSoundNameAsTitle() {
        assertThat(mSubject.getTitle(), is(mSound.getName()));
    }


}
</code></pre>
",https://stackoverflow.com/questions/49531013/java-lang-runtimeexception-method-i-in-android-util-log-not-mocked,['android'],4608,TRUE,2,1
Mock Insert returning 0 as entity.Id but working when app is hosted and request using Curl,"<pre><code>    public class ArticlesController : Controller
    {
        private readonly IArticleRepository _articleRepository;

        public ArticlesController(IArticleRepository articleRepository)
        {
            _articleRepository = articleRepository;
        }

 public async Task&lt;IActionResult&gt; Post([FromBody]ArticleModel model)
        {
            var article = create article object by fill input from model ;
            await _articleRepository.InsertAsync(article);
            return Created($""articles/{article.Id}"", article);
        }
    }
</code></pre>

<hr>

<pre><code>public interface IArticleRepository : IGenericRepository&lt;Article&gt;
    {
    }
</code></pre>

<hr>

<pre><code>public abstract class GenericRepository&lt;T&gt; : IGenericRepository&lt;T&gt;
        where T : BaseEntity, new()
    {
 public async Task InsertAsync(T entity)
        {
            _dbContext.Set&lt;T&gt;().Add(entity);
            await _dbContext.SaveChangesAsync();
        }
    }
</code></pre>

<p>--
When i mock the insert , it return 0 as entity.Id , but when i run after hosting the app . The Insert works and return entity.id > 0. What am i doing wrong ? I am pretty new to moq and unit testing
-- Test Method</p>

<pre><code>     private Mock&lt;IArticleRepository&gt; _articleRepositoryMock = new Mock&lt;IArticleRepository&gt;();

        public ArticlesControllerTests()
        {
            _articlesController = new ArticlesController(_articleRepositoryMock.Object);
        }

 [Fact]
        public async Task Post_SingleItem()
        {
            var article = Builder&lt;Article&gt;.CreateNew().Build();
            _articleRepositoryMock.As&lt;IGenericRepository&lt;Article&gt;&gt;().Setup(m=&gt;m.InsertAsync(article)).Returns(Task.CompletedTask);

            var result = await _articlesController.Post(atricleModel);

            //verify after casting the result to desired object and check .Id &gt; 0 fails


        }
</code></pre>
",https://stackoverflow.com/questions/50220651/mock-insert-returning-0-as-entity-id-but-working-when-app-is-hosted-and-request,"['c#', 'unit-testing', 'nunit', 'moq']",305,FALSE,0,0
Testing Lodash sortBy function argument using Jasmine,"<p>I have a controller in my project that goes like this:</p>

<pre><code>define(function (require) {
  'use strict';

  function AllOrgsController($rootScope, $uibModalInstance) {
    var vm = this;
    var clonedOrgs = _.cloneDeep($rootScope.userData.org);
    vm.modelContainer = _.sortBy(clonedOrgs, function (org) {
      return org.organizationName.toLowerCase();
    });

    vm.openFacilityModal = function () {
      $uibModalInstance.close();
    };

    vm.saveOrgsModal = function () {
      $uibModalInstance.close({ $value: vm.currentFacility });
    };

    vm.cancelOrgsModal = function () {
      $uibModalInstance.dismiss();
    };
  }

  AllOrgsController.$inject = ['$rootScope', '$uibModalInstance'];

  return AllOrgsController;
});
</code></pre>

<p>But the anonymous function being used within Lodash’s <code>_.sortBy</code>  method is not covered according to Istanbul. Since I’m a noob with unit testing I haven’t figured out why – does anybody know?</p>

<p><a href=""https://i.stack.imgur.com/VHb8v.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/VHb8v.jpg"" alt=""&quot;function not covered&quot; error message on my code""></a></p>
",https://stackoverflow.com/questions/49017143/testing-lodash-sortby-function-argument-using-jasmine,"['javascript', 'unit-testing', 'lodash', 'istanbul', 'jasmine2.0']",548,TRUE,0,1
How to write a test method for createNewToken Method?,"<p>I am new to this Mockito J-Unit Testing and I want to test my <code>createNewToken()</code>-Method but I cant understand the logic of it.</p>

<p>This is my method:</p>

<pre><code>public String createNewToken(String usertoken) {
    WebToken oldToken = getTokenByUserToken(usertoken);
    if (!Assert.isNull(oldToken)) {
        em.remove(oldToken);
    }
    WebToken webToken = new WebToken();
    webToken.setToken(UUID.randomUUID().toString());
    webToken.setUserToken(usertoken);
    em.persist(webToken);

    return webToken.getToken();
}
</code></pre>

<p>And this is my test method but i am sure it is wrong:</p>

<pre><code>@RunWith(Enclosed.class)
public class WebTokenPSTest extends AbstractPersistenceTest {
    @InjectMocks
    WebTokenPS cut;

    @RunWith(MockitoJUnitRunner.class)
    public static class createNewToken extends WebTokenPSTest {

        @Test
        public void happyPath() {
            String token = cut.createNewToken(""token"");
            String result = token;
            assertThat(result).isEqualTo(token);
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/50016601/how-to-write-a-test-method-for-createnewtoken-method,"['java', 'unit-testing', 'junit', 'mockito']",285,TRUE,0,1
Verify that method is called after retrofit callback response arrives,"<p>I have this simple DataInteractor which fetches a JsonObject from an api. When the data is not null, I save it locally just in case next time the request fails I can load it from there. I want to create a unit test which checks that when the response is not empty I actually call the method which backs up the information (sharedPreferencesManager.setLocalBackup()).</p>

<p>I've done unit testing only once or twice and for much simpler cases. I've found this links but I honestly feel I'm missing something...well...cause I haven't been able to implement the test, basically.</p>

<p><a href=""https://stackoverflow.com/questions/44713462/android-test-method-called-after-presenter-executes-retrofit-call"">Android test method called after presenter executes retrofit call</a></p>

<p><a href=""https://stackoverflow.com/questions/45160055/unit-testing-in-retrofit-for-callback"">Unit Testing in Retrofit for Callback</a></p>

<p>My Interactor:</p>

<pre><code>public class DataInteractorImpl implements MainActivityContract.DataInteractor {

private SharedPreferencesManager sharedPreferencesManager;

private Retrofit retrofit = new retrofit2.Retrofit.Builder()
        .baseUrl(""https://api.nytimes.com/"")
        .addConverterFactory(GsonConverterFactory.create())
        .build();

public DataInteractorImpl(SharedPreferencesManager sharedPreferencesManager){
    this.sharedPreferencesManager = sharedPreferencesManager;
}

@Override
public void getNoticeArrayList(final OnFinishedListener onFinishedListener) {

    // RetrofitInstance interface
    DataInteractorService dataService = retrofit.create(DataInteractorService.class);

    Call&lt;JsonObject&gt; call = dataService.getNewsData(getCurrentDateYYYYMMDD());

    call.enqueue(new Callback&lt;JsonObject&gt;() {
        @Override
        public void onResponse(Call&lt;JsonObject&gt; call, Response&lt;JsonObject&gt; response) {

            // if the response is not null, try to process it. Otherwise check the local backup
            if(response.body() != null){
                sharedPreferencesManager.setLocalBackup(response.body().toString());
            }
            onFinishedListener.onFinished(response.body());
        }

        @Override
        public void onFailure(Call&lt;JsonObject&gt; call, Throwable t) {
            //check the local backup, return the backup if there is one
            if(sharedPreferencesManager.getLocalBackup() != null) {
                onFinishedListener.onFinished(sharedPreferencesManager.getLocalBackup());
            } else {
                onFinishedListener.onFailure(t);
            }
        }
    });
}

private String getCurrentDateYYYYMMDD(){
    Date date = new Date();
    return new SimpleDateFormat(""yyyyMMdd"").format(date);
}
</code></pre>

<p>}</p>

<p>Any and help could be very useful.
Thanks to all in advance!</p>
",https://stackoverflow.com/questions/52806599/verify-that-method-is-called-after-retrofit-callback-response-arrives,"['java', 'android', 'unit-testing', 'mockito', 'retrofit2']",317,FALSE,1,0
Entity Framework - Validation of Foreign Keys,"<p>Having the following <code>TestClass</code>:</p>

<pre><code>[Table(""xyz"")]
public partial class TestClass{
    [Key]
    public int key {get; set;}
    [ForeignKey(""key"")]
    public virtual ICollection&lt;ExternalClass&gt; externalClasses{get; set;}

    public IEnumerable&lt;ValidationResult&gt; Validate(ValidationContext validationContext)
    {
        ... 
    }
}
</code></pre>

<p>How do I need to set that class up to match my following requirements:</p>

<ul>
<li>I want to test the model with Entity Framework unit testing</li>
<li>In production, the <code>externalClasses</code> shouldn't get saved (should already be in database)</li>
<li>The EF must assure, that each external class exists in DB. If not, throw exception.</li>
</ul>

<p>My first thought was to set the foreign objects null and request the database within the validate method to check if the foreign-key(s) exist. But this approach doesn't work that good with Unit Testing and in addition to that in my opinion it's not that clean to have database requests within a model.</p>

<p>Does anyone have an idea how to handle that on a clean way using the EF?</p>
",https://stackoverflow.com/questions/51609598/entity-framework-validation-of-foreign-keys,"['c#', 'entity-framework', 'entity-framework-6']",2152,TRUE,1,2
Mock embedded struct in go test,"<p>Given:</p>

<pre><code>// FileReader interface for reading from a file
type FileReader interface {
    ReadFile(filename string) ([]byte, error)
}

type FileRead struct {}

// ReadFile reads from filename fn using ioutilReadFile
func (fr FileRead) ReadFile(fn string) ([]byte, error) {
    return ioutil.ReadFile(fn)
}

type Dev struct {
    *FileRead
}

func NewDev() *Dev {
    frd := FileRead{}
    return &amp;Dev{frd}
}

// Function that does some job
func (dev Dev) DoSomeStuff() {
    //...
    dev.ReadFile(""file"")
    //...
}

func main () {
    doer := NewDev()
    doer.DoSomeStuff()
}
</code></pre>

<p>During unit testing, the ReadFile operation should be mocked. How can one best achieve this in go test?</p>

<p>Dev struct could instead use FileReader interface, but then struct embedding is no longer used and the syntax in DoSomeStuff becomes less obvious.</p>
",https://stackoverflow.com/questions/52430510/mock-embedded-struct-in-go-test,"['unit-testing', 'go']",947,FALSE,1,1
TypeError: undefined is not a constructor (evaluating &#39;angular.controller(&#39;myView&#39;)&#39;),"<p>I'm getting the below error while doing karma/jasmine unit testing for both the test cases.I tried by modifying the controller by adding angular.controller in the spec file even then it is not working.Is there any way to fix?</p>

<pre><code> TypeError: undefined is not a constructor (evaluating 'angular.controller('myView')') 
</code></pre>

<p>myView.spec.js</p>

<pre><code>// myView.spec.js
(function(){
describe('controller: myView', function(){


     var module,myView,$q, $rootScope, $scope, uiGridConstants, overviewService, commonService, $timeout;
    beforeEach(function() {
        module = angular.module('app.myView');
        controller= angular.controller('myView')
    });

    beforeEach(inject(function ($controller, _$q_, _$rootScope_, _$timeout_) {

        $q= _$q_;
        $rootScope = _$rootScope_;
         $timeout= _$timeout_;

        myView= $controller('myView', {
            $q : _$q_,
            $rootScope :  _$rootScope_,
             $timeout:  _$timeout_
        });


    }));

    describe(""myViewto be defined"", function() {
        it(""should be created successfully"", function () {
            expect(controller).toBeDefined();
        });

        it(""overview should be defined"", function () {
            expect(myView()).toBeDefined();
        });

    });

});

})();
</code></pre>

<p>and myView.js</p>

<pre><code>(function() {
    'use strict';

    angular
        .module('app.myView')
        .controller('myView', myView);

    function myView($q, $rootScope, $scope, uiGridConstants, myViewService, commonService, $timeout) {
        var vm = this;
        vm.callFeedback = function () { };
})();
</code></pre>
",https://stackoverflow.com/questions/50036312/typeerror-undefined-is-not-a-constructor-evaluating-angular-controllermyvie,"['angularjs', 'karma-jasmine', 'gulp-karma']",1934,TRUE,1,2
I want to check if the Correct BusinessException is thrown with unit test?,"<p>This is my method in the controller.</p>

<pre><code>public ActionResult DeleteModelAliasData(string alias)
{
    if (!ModelState.IsValid)
    {
        ModelState.LogModelStateError();
        throw new BusinessException(""COMMON_ERROR"");
    }

    var response = _vehicleDataBusinessService.DeleteModelAliasData(alias);
    return Json(response);
}
</code></pre>

<p>I am new at unit testing and I want to write the unit test that when the ""<code>!ModelState.IsValid</code>"" then the exception is thrown, I want to check that is it the correct exception which I Wanted?</p>
",https://stackoverflow.com/questions/49292447/i-want-to-check-if-the-correct-businessexception-is-thrown-with-unit-test,"['c#', 'unit-testing', 'nunit']",156,TRUE,1,2
How to unit test this effect (with {dispatch: false})?,"<p>ngrx and unit testing beginner here. I have the following effect:</p>

<pre class=""lang-js prettyprint-override""><code>@Injectable()
export class NotificationEffects {
  @Effect({dispatch: false})
  notificationShow$ = this.actions$
    .ofType(notificationAction.NOTIFICATION_SHOW)
    .do((action: notificationAction.NotificationShowAction) =&gt; {
      this.notificationService.info(action.payload.config);
    });

  constructor(private actions$: Actions, private notificationService: NotificationService) {}
}
</code></pre>

<p>Specifically, I would like to test that the notificationService method info has been called. How would I do that?</p>

<p>I have followed these examples but not found a solution:</p>

<p><a href=""https://netbasal.com/unit-test-your-ngrx-effects-in-angular-1bf2142dd459"" rel=""noreferrer"">https://netbasal.com/unit-test-your-ngrx-effects-in-angular-1bf2142dd459</a>
<a href=""https://medium.com/@adrianfaciu/testing-ngrx-effects-3682cb5d760e"" rel=""noreferrer"">https://medium.com/@adrianfaciu/testing-ngrx-effects-3682cb5d760e</a>
<a href=""https://github.com/ngrx/effects/blob/master/docs/testing.md"" rel=""noreferrer"">https://github.com/ngrx/effects/blob/master/docs/testing.md</a></p>
",https://stackoverflow.com/questions/48318095/how-to-unit-test-this-effect-with-dispatch-false,"['angular', 'unit-testing', 'ngrx-effects']",7200,TRUE,19,5
Angular 4 unit test cases: Injecting router module error &quot;ReferenceError: Router is not defined&quot;,"<p>inject function is not loading valid parameters</p>

<pre><code>import { TestBed, async, inject, fakeAsync, tick, ComponentFixture, getTestBed } from '@angular/core/testing';
import { RouterTestingModule } from ""@angular/router/testing""
import { Router } from ""@angular/router"";
import { Location } from ""@angular/common"";
import { DriversModule } from '../../drivers.module';
import { DriverAddComponent } from './driver.add.component';
import { routes, routing } from '../../drivers.routing';
import { DebugElement, NO_ERRORS_SCHEMA } from '@angular/core';
import { By } from '@angular/platform-browser';
import { Observable } from 'rxjs/Observable';
import { DriverService } from '../../services/driver.service';


describe('Add driver Component', () =&gt; {
    let component: DriverAddComponent;
    let fixture: ComponentFixture&lt;DriverAddComponent&gt;;
    let routerMock;
    let routerSpy: any;
    let location: Location;

    let getvendorsdatastub: getVendorsDataStub;
    beforeEach(async(() =&gt; {
        routerMock = {
            navigate: jasmine.createSpy('navigate')
        };

        TestBed.configureTestingModule({
            imports: [DriversModule, RouterTestingModule.withRoutes(routes)],
            providers: [
                { provide: Router, useValue: routerMock },
                { provide: DriverService, useValue: getVendorsDataStub }
            ],
            schemas: [NO_ERRORS_SCHEMA]
        }).compileComponents();


   })); 
 it('should navigate to the add a new driver page', 
    inject([Router],(router: Router) =&gt; {    // &lt;= injecting router error
        const spy = spyOn(router, 'navigate');
        fixture = TestBed.createComponent(DriverAddComponent);
        component = fixture.componentInstance;
        component.goBack();
            expect(router.navigate).toHaveBeenCalledWith(['/addDriver']);
        }));
})
</code></pre>

<p>When debugging the code I found that params 'Router' is not passing in inject function and throws an error as ""ReferenceError: Router is not defined""</p>

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

<p>Stack Trace:</p>

<pre><code>`""ReferenceError: Router is not defined↵    at eval (eval at &lt;anonymous&gt; (http://localhost:9876/base/src/test.ts?c92fcd34ca1f3fdca5a758e21439c0cb69837438:38527:5), &lt;anonymous&gt;:1:1)↵    at Suite.&lt;anonymous&gt; (http://localhost:9876/base/src/test.ts?c92fcd34ca1f3fdca5a758e21439c0cb69837438:38527:5)↵    at ZoneDelegate.invoke (http://localhost:9876/base/src/polyfills.ts?7c20fa2756eb46abb635df734b059df04f5129cb:3306:26)↵    at Zone.run (http://localhost:9876/base/src/polyfills.ts?7c20fa2756eb46abb635df734b059df04f5129cb:3056:43)↵    at Suite.&lt;anonymous&gt; (http://localhost:9876/base/src/test.ts?c92fcd34ca1f3fdca5a758e21439c0cb69837438:126680:29)↵    at addSpecsToSuite (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?b92f226f045eefc6b7ea6f5d62253577587c5fc8:994:25)↵    at Env.describe (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?b92f226f045eefc6b7ea6f5d62253577587c5fc8:961:7)↵    at Env.jasmineEnv.(anonymous function) [as describe] (http://localhost:9876/base/src/test.ts?c92fcd34ca1f3fdca5a758e21439c0cb69837438:126657:38)↵    at describe (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?b92f226f045eefc6b7ea6f5d62253577587c5fc8:3999:18)↵    at Object.Array.concat.Object.defineProperty.value (http://localhost:9876/base/src/test.ts?c92fcd34ca1f3fdca5a758e21439c0cb69837438:38487:1)`
</code></pre>

<p>Help me out.. Any suggestions thanks..I'm new to unit testing..</p>
",https://stackoverflow.com/questions/48381011/angular-4-unit-test-cases-injecting-router-module-error-referenceerror-router,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",692,FALSE,2,0
Set Up a running Unit Test for the following :,"<p>I'm unable to set up a unit testing for the following: Having a hard time to visualize what should be Tested</p>

<p>Using JS/ REACT + jest/enzyme </p>

<p>Goal is to make sure the function gets call and what would be an output example</p>

<pre><code>function prepadSigned(hexStr) {
  const msb = hexStr[0];
  if (msb &lt; '0' || msb &gt; '7') {
    return `00${hexStr}`;
  }
  return hexStr;
}
</code></pre>
",https://stackoverflow.com/questions/53872640/set-up-a-running-unit-test-for-the-following,"['javascript', 'reactjs', 'unit-testing', 'jestjs']",60,TRUE,0,1
Unit Test Linq XML Function,"<p>I have the next function which creates a List from the data in the document.</p>

<p>I need to do some unit testing but have no clue how to actually do that for this particular function. I have read everywhere but still no luck.</p>

<pre><code>public List&lt;Info&gt; getInfo()
{
    XDocument doc = loadDocument();

    var variable = (from elem in doc.Descendants(""Information"").Elements()
                   select new Info
                   {
                       Include = elem.Element(""Include"") != null &amp;&amp; (elem.Element(""Include"").Value.Equals(""true"") || elem.Element(""Include"").Value.Equals(""false"")) ? Convert.ToBoolean(elem.Element(""Include"").Value) : false,
                       InfoName = elem.Element(""Name"") != null ? elem.Element(""Name"").Value : String.Empty,
                       StartDate = elem.Element(""StartDate"") != null ? elem.Element(""StartDate"").Value : String.Empty,
                       EndDate = elem.Element(""EndDate"") != null ? elem.Element(""EndDate"").Value : String.Empty,
                       Mark = elem.Element(""Mark"") != null ? Convert.ToDouble(elem.Element(""Mark"").Value) : Double.NaN
                   }
                   ).ToList();

    return variable;
}

public XDocument loadDocument() 
{ 
    XDocument doc = XDocument.Load(""info.xml""); 
    return doc; 
}
</code></pre>
",https://stackoverflow.com/questions/51247089/unit-test-linq-xml-function,"['c#', 'linq', 'unit-testing']",212,TRUE,0,2
Django Rest Framework failing to patch Serializer(many=True).data in view test,"<p>I'm unit testing a view and I am attempting to patch the <code>.data</code> property on my serializer but it looks like it behaves differently when the <code>many=True</code> kwarg is passed to the serializer constructor and thus not properly patching. Here is a generalized example of my code.</p>

<pre><code># myapp/serializers.py
class MySerializer(serializers.Serializer):
    some_field = serializers.CharField()


# myapp/views.py
class MyView(View):

    def get(self, request):
        # ..stuff
        some_data = []
        serializer = MySerializer(some_data, many=True)
        print(type(serializer))  # &lt;class 'rest_framework.serializers.ListSerializer'&gt;
        print(type(serializer.data))  # &lt;class 'rest_framework.utils.serializer_helpers.ReturnList'&gt;


        return Response({""data"": seralizer.data, status=200})


# in tests
def test_view_case_one(mocker):

    # setup other mocks

    serialized_data = mocker.patch(""myapp.views.MySerializer.data"", new_callable=mocker.PropertyMock)

    # invoke view
    response = MyView().get(fake_request)

    # run assertions
    serialized_data.assert_called_once() # this says it's never called 
</code></pre>
",https://stackoverflow.com/questions/52319519/django-rest-framework-failing-to-patch-serializermany-true-data-in-view-test,"['python', 'django', 'django-rest-framework', 'pytest']",525,TRUE,1,1
Error: StaticInjectorError(DynamicTestModule) Angular 5 Karma Jasmine 2.8.0,"<p>My app is working fine but while i am trying to perform unit testing i am getting below mentioned error :</p>

<blockquote>
  <p>Error: StaticInjectorError(DynamicTestModule)[AppComponent ->
  FinanceserviceService]:    StaticInjectorError(Platform:
  core)[AppComponent -> FinanceserviceService]: 
      NullInjectorError: No provider for FinanceserviceService!</p>
</blockquote>

<p>My codes are given below :</p>

<p>financeservice.service.ts</p>

<pre class=""lang-ts prettyprint-override""><code>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import 'rxjs/add/operator/map';

@Injectable()
export class FinanceserviceService {

  constructor(private _http: HttpClient) { }
  finData() {
    return this._http.get(""./assets/data.json"")
      .map(result =&gt; result);
  }
}
</code></pre>

<p>test.spec.ts</p>

<pre class=""lang-ts prettyprint-override""><code>import { TestBed, inject,async,ComponentFixture } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { FinanceserviceService } from './financeservice.service';
import { AppComponent } from './XXXX.component';
import { SliderModule  } from 'angular-image-slider';
import { CUSTOM_ELEMENTS_SCHEMA,NO_ERRORS_SCHEMA } from '@angular/core';
import 'rxjs/add/operator/map';


describe('FinanceserviceService', () =&gt; {
  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      providers: [FinanceserviceService],
      schemas: [
        CUSTOM_ELEMENTS_SCHEMA,
        NO_ERRORS_SCHEMA
      ]
    });
  });

  it(`should create`, async(inject([HttpTestingController, FinanceserviceService],
    (httpClient: HttpTestingController, financeservice: FinanceserviceService) =&gt; {
      expect(financeservice).toBeTruthy();
  })));

});
</code></pre>

<p>*.component.ts</p>

<pre class=""lang-ts prettyprint-override""><code>import { Component } from '@angular/core';
import { FinanceserviceService } from './financeservice.service';
import { Chart } from 'chart.js';


constructor(private _fin: FinanceserviceService){
  }

  ngOnInit() {

    this._fin.finData()
      .subscribe(res =&gt; {

        let Fmax = res['list'].map(res =&gt; res.main.temp_max);
        let Fmin = res['list'].map(res =&gt; res.main.temp_min);
        let alldates = res['list'].map(res =&gt; res.dt)

        let FDates = []
        alldates.forEach((res) =&gt; {
            let jsdate = new Date(res * 1000)
            FDates.push(jsdate.toLocaleTimeString('en', { year: 'numeric', month: 'short', day: 'numeric' }))
        })

        this.chart=new Chart('canvas',{
          type: 'line',
          data: {
            labels: FDates,
            datasets: [
              { 
                data: Fmax,
                borderColor: ""#3cba9f"",
                fill: false
              },
              { 
                data: Fmin,
                borderColor: ""#ffcc00"",
                fill: false
              },
            ]
          },
          options: {
            legend: {
              display: false
            },
            scales: {
              xAxes: [{
                display: true
              }],
              yAxes: [{
                display: true
              }],
            }
          }

        })

      })
  }
</code></pre>

<p>*.module.ts</p>

<pre class=""lang-ts prettyprint-override""><code>import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { FinanceserviceService } from './financeservice.service';
import { NgModule,CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { AppComponent } from './XXX.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { SliderModule } from 'angular-image-slider';
import { CommonModule } from '@angular/common';
import { NO_ERRORS_SCHEMA } from '@angular/core';


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    BrowserAnimationsModule,
    SliderModule,
  ],
  schemas: [NO_ERRORS_SCHEMA],
  providers: [FinanceserviceService],
  bootstrap: [AppComponent]
})

export class AppModule { }
</code></pre>

<p>Kindly help</p>
",https://stackoverflow.com/questions/50088891/error-staticinjectorerrordynamictestmodule-angular-5-karma-jasmine-2-8-0,"['karma-jasmine', 'angular5']",2007,FALSE,3,0
Unit test Quick and Numble - Not shown in coverage,"<p>I'm having a problem with some unit testing and coverage.</p>

<pre><code>class InputFileReaderSpec: QuickSpec {

    override func spec() {

        beforeEach {

        }

        describe(""InputFileReader"") {
            it(""should be able to read a file"") {
                let inputFileReader = InputFileReader()
                let string = try? inputFileReader.readFileAt(""f_digital-security-incident.yml"")
                expect(string).notTo(beNil())
            }

            it(""should try to read a file doesnt exist"") {
                let inputFileReader = InputFileReader()
                expect {
                    try inputFileReader.readFileAt(""test.yml"")
                    }.to(throwError(InputFileReaderError.inputFileNotFound))

            }

            it(""should try to read a file with format invalid"") {
                let inputFileReader = InputFileReader()
                expect {
                    try inputFileReader.readFileAt(""tool_cobian1.png"")
                    }.to(throwError(InputFileReaderError.invalidFileFormat))
            }
        }

        afterEach {

        }
    }
}
</code></pre>

<p>My InputFileReader</p>

<pre><code>import Foundation

enum InputFileReaderError: Error {
    case inputFileNotFound
    case invalidFileFormat
}

class InputFileReader {

         func readFileAt(_ fileName: String) throws -&gt; String {
        guard let path = Bundle(for: type(of: self)).path(forResource: fileName, ofType: """") else {
            throw InputFileReaderError.inputFileNotFound
        }

        guard let content = try? String(contentsOfFile: path) else {
            throw InputFileReaderError.invalidFileFormat
        }
        return content
    }
}
</code></pre>

<p>The problem that happens is that the coverage shows that it had no test for the code snippet, but when running it passes and is tested.</p>

<p><a href=""https://i.stack.imgur.com/NVhfO.png"" rel=""nofollow noreferrer"">Coverage</a></p>

<p>Has anyone ever experienced this?
<a href=""https://i.stack.imgur.com/BSD5A.png"" rel=""nofollow noreferrer"">Coverage</a></p>
",https://stackoverflow.com/questions/50926721/unit-test-quick-and-numble-not-shown-in-coverage,"['swift', 'unit-testing', 'code-coverage', 'quick-nimble']",198,FALSE,1,0
pyspark zip file creation using gradle,"<p>How can we build pyspark project using gradle? I want to build it just like how we buuild a scala gradle project. The build must do compilation and zip file creation of pyspark project . Must be able to do the  python unit testing if possible..</p>
",https://stackoverflow.com/questions/53625753/pyspark-zip-file-creation-using-gradle,"['gradle', 'pyspark', 'pygradle']",104,FALSE,1,0
How to mock JSON import Jest TypeScript,"<p>I want to mock a .json file using Jest for unit testing in Typescript.</p>

<p>I'm currently using this global mock inside jest.config.js file. And this is working fine:</p>

<pre><code>    'package.json': '&lt;rootDir&gt;/__tests__/tasks/__mocks__/data.json'
</code></pre>

<p>But I want to mock it locally, inside my test class.</p>

<p>This didn't work for me:</p>

<pre><code>jest.mock('../../package.json', () =&gt; ({
    package : { name: '__name__', 'version': '__version__'};
}), { virtual: true })
</code></pre>
",https://stackoverflow.com/questions/53809184/how-to-mock-json-import-jest-typescript,"['javascript', 'typescript', 'unit-testing', 'jestjs']",4142,TRUE,1,2
Unit Test (Rhino) DBUp in Azure Durable HTTPStart Method,"<p><strong>Technology Stack</strong></p>

<ol>
<li>DBUP for DB upgrades</li>
<li>Azure Durable for activities</li>
<li>Rhino mocks for unit testing.</li>
</ol>

<p><strong>Situation</strong></p>

<p>Currently, I have placed my DB Upgrade (DBUp) statements in the HTTPStart method as its the entry point of my durable azure function.</p>

<pre><code>DeployChanges.To
.SqlDatabase(connectionString)
.WithScriptsEmbeddedInAssembly(Assembly.GetExecutingAssembly())
.LogToConsole()
.Build(); 
</code></pre>

<p><strong>Problem</strong></p>

<p>Problem with this approach is that DBUp uses a static class to upgrade DB and I can't use Rhino to mock methods on a static class. </p>

<p><strong>Question</strong></p>

<p>I thought of wrapping the DBUp part in a non-static class but then I would need to mock constructor initialization. Not sure if this would work</p>

<p><strong>Code - Helper Class which upgrades DB</strong></p>

<pre><code>public class DBUPHelper
    {
        public bool UpgradeDB()
        {
            bool status = true;
            var connectionString = ""Data Source=localhost;Initial Catalog=master;Integrated Security=True;Connect Timeout=15"";
            var upgrader =
                DeployChanges.To
                    .SqlDatabase(connectionString)
                    .WithScriptsEmbeddedInAssembly(Assembly.GetExecutingAssembly())
                    .LogToConsole()
                    .Build();

            var result = upgrader.PerformUpgrade();

            if (!result.Successful)
            {
                status = false;
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(result.Error);
                Console.ResetColor();
            }
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine(""Success!"");
            Console.ResetColor();
            return status;
        }
    }
</code></pre>

<p><strong>Code - HTTPStart Method which calls Helper class</strong></p>

<pre><code>private static ILogger logObj;
           [FunctionName(""HttpStart"")]
           public static async Task&lt;HttpResponseMessage&gt; Run(
               [HttpTrigger(AuthorizationLevel.Function, methods: ""post"", Route = ""orchestrators/{functionName}"")] HttpRequestMessage req,
               [OrchestrationClient] DurableOrchestrationClientBase starter,
               string functionName,
               ILogger log, ExecutionContext context)
       {
           HttpResponseMessage response = null;            
           var config = new ConfigurationBuilder()
           .SetBasePath(context.FunctionAppDirectory)
           .AddJsonFile(""local.settings.json"", optional: true, reloadOnChange: true)
           .AddEnvironmentVariables()
           .Build();
           Helper.Helper helper = new Helper.Helper(config.GetConnectionString(""ConnString""););
           if (helper.UpgradeDB())
           {
               log.LogInformation(""DB Upgraded Successfully"");
               logObj = log;
               try
               {
                   var provider = new MultipartMemoryStreamProvider();
                   await req.Content.ReadAsMultipartAsync(provider);
                   Application policy = await GeneratePolicyObject(provider);
                   string instanceId = await starter.StartNewAsync(functionName, policy);
                   log.LogInformation($""Started orchestration with ID = '{instanceId}'."");
                   response = starter.CreateCheckStatusResponse(req, instanceId);
                   response.Headers.RetryAfter = new RetryConditionHeaderValue(TimeSpan.FromSeconds(10));
               }
               catch (Exception ex)
               {
                   response = new HttpResponseMessage();
                   log.LogCritical(ex.ToString());
                   log.LogCritical(ex.InnerException.ToString());
                   log.LogCritical(ex.StackTrace);
                   response.Content = new StringContent(ex.ToString());
                   response.StatusCode = System.Net.HttpStatusCode.InternalServerError;
               }
           }
           else log.LogCritical(""DB Upgrade Failed. Check logs for exception"");
           return response;
       }
</code></pre>

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

<p>See the highlighted area. I want to mock the constructor initialization so that DB calls does not happen while Unit Testing. </p>

<p>Can anyone help, please. </p>

<p>Regards Tarun</p>
",https://stackoverflow.com/questions/52157361/unit-test-rhino-dbup-in-azure-durable-httpstart-method,"['c#', 'unit-testing', 'rhino-mocks', 'azure-durable-functions', 'dbup']",260,TRUE,2,1
Angular 4 Jasmine Unit Test Directive Export Function,"<p>I have a created custom directive in angular 4 the directive is below.</p>

<pre><code>import { Directive } from '@angular/core';
import { NG_VALIDATORS, FormControl } from '@angular/forms';
export function appValidator(control: FormControl) {
let tWordsLength = false;
if (control.value) {
let test = control.value.split("","");
var lengths = test.map(function (word) {
  if(word.length &gt; 30){
    tWordsLength = true;
  }
  return word.length
})
if (test.length &gt; 10 || tWordsLength) {
  return {
    tagsDomain: {
      parsedDomain: false
    }
  }
}
}
return null;
}
@Directive({
  selector: '[appGeneral][ngModel]',
   providers: [
   {
    provide: NG_VALIDATORS,
    useValue: appValidator,
    multi: true
   }
 ]
})
export class GeneralDirective {
};
</code></pre>

<p><strong>And My spec is as below</strong></p>

<pre><code>import {TestBed} from '@angular/core/testing';
import { GeneralDirective } from './app-general.directive';
describe('GeneralDirective', () =&gt; {
beforeEach(() =&gt; {
 TestBed.configureTestingModule({
   declarations: [GeneralDirective]
  });
 });
 it('should create an instance', () =&gt; {
   const directive = new GeneralDirective();
   expect(directive).toBeTruthy();
  });
 });
</code></pre>

<p>I want to cover the unit testing for export function 'appValidator' in Directive. Can anyone suggest the way on how to achieve coverage on export function.</p>
",https://stackoverflow.com/questions/49251480/angular-4-jasmine-unit-test-directive-export-function,"['angular', 'karma-jasmine']",1092,TRUE,0,1
Testing Firebase Database with an in-memory fake/db,"<p>Is there any in-memory implementation for Firebase database for testing Android client logic and integration? I have seen node.js fakes but could not find anything in java. I am not looking for a plain mock which is only good for basic unit-testing.</p>
",https://stackoverflow.com/questions/50447047/testing-firebase-database-with-an-in-memory-fake-db,"['android', 'firebase-realtime-database']",588,FALSE,-5,1
TDD: Does EF Core In Memory Provider validates referential constraints?,"<p>I'm really excited about in memory feature of EF Core for unit testing. It relieves  me of the burden to write dedicated repository, just for the sake of making code unit testable. But merely in memory testing in a collection wont't suffice.</p>

<blockquote>
  <p>Does EF Core In Memory Provider validates referential constraints?</p>
</blockquote>
",https://stackoverflow.com/questions/50999975/tdd-does-ef-core-in-memory-provider-validates-referential-constraints,"['c#', 'unit-testing', 'tdd', 'entity-framework-core', 'ef-core-2.0']",577,TRUE,5,1
dialogRef.afterClosed is not a function,"<p>Hi im doing unit testing and trying to get coverage for my subscription. However it keeps failing with the error <strong>dialogRef.afterClosed is not a function</strong></p>

<p>Im not sure at what or how I can spy on the afterClosed() function, but thats the only part I cant seem to cover. 
    ...</p>

<pre><code>import { MatDialog } from '@angular/material/dialog';
....
constructor( private dialog: MatDialog) { }

showLogin(): void {

  const dialogRef = this.dialog.open(LoginDialogComponent, {
    width: '400px',
    height: 'auto',
    data: this.loginContext
  });

  dialogRef.afterClosed().subscribe(result =&gt; {
    if (this.loginContext.loggedIn) {
      this.showApply();
    }
  });
}
</code></pre>

<p>this is the <strong>LoginDialogComponent</strong></p>

<pre><code> ....

 @Component({
   selector: 'app-login-dialog',
   templateUrl: './login-dialog.component.html',
   styleUrls: ['./login-dialog.component.scss']
 })
 export class LoginDialogComponent implements OnInit {

   constructor(
     private authService: AuthService,
     private alertService: AlertService,
     public dialogRef: MatDialogRef&lt;LoginState&gt;,
     @Inject(MAT_DIALOG_DATA) public data: LoginState) { }

   ngOnInit() {
     this.data.loggedIn = false;
   }

   login(loginEvent: LoginEvent): void {


     this.authService.login(loginData).then(
       resp =&gt; {
         this.data.loggedIn = true; // feedback
         this.dialogRef.close();
       },
       err =&gt; {
         this.alertService.showAlert(err);
       }
     );
   }

 }
</code></pre>
",https://stackoverflow.com/questions/52968940/dialogref-afterclosed-is-not-a-function,"['angular', 'unit-testing', 'jasmine']",12552,TRUE,7,2
How to set: 2015-06-17 05:25:21 +0000 as a let NSDate constant,"<p>I'm trying to set an <code>NSDate</code> constant:</p>

<pre><code>let formattedDate: NSDate = 2015-06-17 05:25:21 +0000
</code></pre>

<p>but when I set it I get numerous errors:</p>

<blockquote>
  <p>Cannot convert value of type 'Int' to specified type 'NSDate'<br>
  Consecutive declarations on a line must be separated by ';'</p>
</blockquote>

<p>I'm unit testing so I need the <code>formattedDate: NSDate</code> to test against.</p>
",https://stackoverflow.com/questions/48427978/how-to-set-2015-06-17-052521-0000-as-a-let-nsdate-constant,"['ios', 'swift', 'nsdate']",50,TRUE,0,1
Testing if external component method is called in jest,"<p>I am using <code>jest</code> and <code>enzyme</code> for unit testing. Below is my <code>index.js</code> file. I need to test <code>openNotification</code> and  <code>uploadErrorNotification</code> function of the file. However, only <code>uploadErrorNotification</code> function is exported. So, How do I test both the functions.</p>

<p>Also, I don't want to use any other libray except <code>jest</code> and <code>enzyme</code>.</p>

<pre><code>//index.js
import {
      notification
    } from 'antd';

    const openNotification = (message, description, className) =&gt; {
      notification.open({
        key: 'upload-template',
        message,
        description,
        placement: ""bottomRight"",
        duration: null,
      });
    };

    const uploadErrorNotification = (uploadFailedText, errorMsg) =&gt; {
      openNotification(uploadFailedText, errorMsg, 'error');
    };

    export {
      uploadErrorNotification
    }
</code></pre>

<p>This is my test file:</p>

<pre><code>//test.js

import { uploadErrorNotification } from '../index.js

jest.mock('notification', () =&gt; ({ open: () =&gt; jest.fn() })); // was trying this but I couldn't understand how it will work

describe('Notification validation functions testing', () =&gt; {
  uploadErrorNotification('Upload failed', 'Something went wrong.');
  expect(""openNotification"").toHaveBeenCalledTimes(1); // want to do something like this
});
</code></pre>
",https://stackoverflow.com/questions/53332660/testing-if-external-component-method-is-called-in-jest,"['jestjs', 'enzyme']",1478,TRUE,3,3
How to mock a nested method?,"<p>I'm learning more about Jasmine Unit Testing and I've ran into something that I can't figure out. I'm new to both JavaScript and Unit Testing. I've tried to look for examples about nested methods and mocking them, but I'm still unable to have a successful test. I'm making a game with PhaserJS (HTML5 Game Library) and I've written successful tests so far. This is an example of my successful test.     </p>

<pre><code> function createGameScreenBorder(gameState) {
      var border = gameState.game.add.graphics();
    }
</code></pre>

<p>This is my test block.</p>

<pre><code>it(""create gamescreen background border"", function() {
    gameState.game = {
    add: jasmine.createSpyObj('add', ['graphics'])
    };
      createGameScreenBorder(gameState);
      expect(gameState.game.add.graphics).toHaveBeenCalled();
    });
</code></pre>

<p>Now the above code works, it doesn't do much. What I want is to draw a rectangle which is a method part of the graphics method. </p>

<pre><code>function createGameScreenBorder(gameState) {
      var border = gameState.game.add.graphics();
          // drawRect: x, y width, length
          border.drawRect(0, 0, 0, 0);
      }
</code></pre>

<p>This is my test block.</p>

<pre><code>    it(""create gamescreen background border"", function() {
          gameState.game = {
            add: {
              graphics: jasmine.createSpyObj('graphics', ['drawRect'])
            }
          }
          createGameScreenBorder(gameState);
          expect(gameState.game.add.graphics).toHaveBeenCalled();
          expect(gameState.game.add.graphics().lineStyle).toHaveBeenCalledWith(0,0,0,0);
        });
</code></pre>

<p>I want to be able to make sure that drawRect() is called with my parameters, but I am confused as to how to do it. </p>

<p>Thank you!  </p>
",https://stackoverflow.com/questions/49088590/how-to-mock-a-nested-method,"['javascript', 'unit-testing', 'jasmine', 'jasmine2.0']",2711,TRUE,1,1
Weird behavior of assertRaises (TestCase),"<p>I've been trying/learning about unit testing works in Python and I came across this weird behavior, am I doing something wrong?</p>

<p><strong>Class</strong></p>

<pre><code>class Entity:

    def __init__(self, n):
        if not isinstance(n, int):
            raise TypeError('n must be a number.')
        self.n = n
</code></pre>

<p><strong>Test</strong></p>

<pre><code>from src.entity import Entity

class TestEntity(TestCase):

    def test__init__types(self):
        self.assertRaises(TypeError, Entity.__init__, ""2"")
        self.assertRaises(TypeError, Entity.__init__, 2)
</code></pre>

<p>Shouldn't the test fail in the second <code>assertRaises</code> since 2 is a number thus the <code>TypeError</code> isn't raised? instead it says OK.</p>
",https://stackoverflow.com/questions/51223638/weird-behavior-of-assertraises-testcase,"['python', 'python-3.x', 'unit-testing']",227,TRUE,0,1
left outer join with EF in-memory data crashes but works fine with SqlServer,"<p>I have run into this in a couple places while unit testing. I write a query like this using a left outer join:</p>

<pre><code>from user in db.SSUserInfo
from purchase in db.Purchases.Where(p =&gt; p.UserId == user.Id &amp;&amp; p.PackageGroupId == Id).DefaultIfEmpty()
where userIdList.contains(user.
select new {
    purchaseId = (int?)purchase.Id
}
</code></pre>

<p>This works fine when querying against the database even though purchase will be Null if no purchases exist for the user. However, when querying against an in memory list (for unit testing), when purchase returns as null, this crashes with a NULL Reference Exception.</p>

<p>I can get the in-memory version to not crash by doing:</p>

<pre><code>purchaseId = (int?)((purchase != null) ? purchase.Id : null)
</code></pre>

<p>but that causes bloat in the SQL sent to the database.</p>

<p>Does anybody know how to get the in-memory query to not crash on null and at the same time keep the SQL efficient? </p>

<p>This is happening with EF 6.2.0 and .Net 4.6.1. It happened on earlier versions too.</p>
",https://stackoverflow.com/questions/48178324/left-outer-join-with-ef-in-memory-data-crashes-but-works-fine-with-sqlserver,['entity-framework'],94,FALSE,0,0
Unit test - What double (actor) are entities (model classes)?,"<p>Conceptual question here about entities in unit tests. Trying to fully understand the concepts.</p>

<p>How should I name my entities in my unit tests?... I mean, I usually create a class like PersonMock that has different methods like ""newPerson1()"", ""newPerson2()"" and so on, each method returning an instance with different state for testing different scenarios.</p>

<p>But it looks like this is not the pure concept of ""mock"" (currently reading a unit testing book). For what I understand, entities (and entity buiders) are not mocks (and not stubs, fakes, dummies, etc)... what are they in unit testing? Just model builders?</p>

<p>How do you guys manage and name these objects responsible for creating entities that will be used in the tests? (Like PersonMock above.)</p>

<p>And any other further best practice tips are welcome. Thanks in advance!</p>
",https://stackoverflow.com/questions/52156266/unit-test-what-double-actor-are-entities-model-classes,"['unit-testing', 'junit', 'mocking', 'mockito', 'easymock']",45,TRUE,0,1
Unit test RecyclerView Adapter Using Mockito,"<p>In Recycler View Adapter I have this method:</p>

<pre><code>public void addGridItemsToView(int position, Tile data) {
    tileList.add(position, data);
    notifyItemInserted(position);
}
</code></pre>

<p>I want to do unit testing on this method and check if <code>notifyItemInserted(position)</code> was called or not.</p>

<p>This is my test class:</p>

<pre><code>public class AdapterTest  {
    @Mock
    private LiveZoneGridAdapter liveZoneGridAdapter;
    @Mock
    Context context;


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

    @Test
    public void addGridItemsToViewNotifiesParentAndAddsItemToTileList() {
        liveZoneGridAdapter = spy(new LiveZoneGridAdapter(context));
        doNothing().when((RecyclerView.Adapter) liveZoneGridAdapter).notifyItemInserted(anyInt());
        liveZoneGridAdapter.addGridItemsToView(0, new Tile(""test"", 0, 0, ""test""));
        Mockito.verify(liveZoneGridAdapter).notifyItemInserted(0);
    }

}
</code></pre>

<p>If I run my test cases like this it gives <code>NullPointerException</code> on <code>notifyItemInserted</code> which is <code>RecyclerView.Adapter</code> class method.
So how can I test this scenario?</p>
",https://stackoverflow.com/questions/48989248/unit-test-recyclerview-adapter-using-mockito,"['android', 'unit-testing', 'junit', 'mockito']",6608,TRUE,4,1
How to get Enzyme type() of null instead of function?,"<p>I'm new to <em>unit-testing</em> and ran into a problem. I can't get <em>Enzyme</em> to return null for my Element which has an if statement <code>!item =&gt; null</code>.
  How to check if element is null if no '<em>item prop</em>' given?</p>

<pre><code> it(""should not render without `props.item`"", () =&gt; {
    wrapper.setProps({
      item: null,
    })

    console.log(wrapper.find('ThemeTile').childAt(0).name()) // === 'Link'
    expect(wrapper.find('ThemeTile').childAt(0).type()).toEqual(null);

    // returns expect(received).toEqual(expected)
    // Expected value to equal:
    //    null
    //Received:
    //   [Function Link]
  })
</code></pre>

<p>And this is the relevant render method of the ThemeTile.</p>

<pre><code>render() {
    const { classes, item, href } = this.props;

    if(!item) {
      return null;
    }

    const image                   = buildImageUrl(item, 'square', 300, 300);

    return (
      &lt;Link to={href} className={classes.root}&gt;
        &lt;div className={classes.imageContainer}&gt;
          &lt;div className={classes.image} style={{backgroundImage: `url(${image})`}} /&gt;
        &lt;/div&gt;
        &lt;Typography className={classes.title}&gt;
          {this.props.item.title}
        &lt;/Typography&gt;
      &lt;/Link&gt;
    );
  }
</code></pre>
",https://stackoverflow.com/questions/50906912/how-to-get-enzyme-type-of-null-instead-of-function,"['javascript', 'reactjs', 'unit-testing', 'jestjs', 'enzyme']",50,FALSE,0,1
Enabling running single test for each input managed by for loop in java using testng framework,"<p>I want to send inputs that are being produced by the baseTestBeforeTest() method for each of the input which invoked in runTestSuite() method (that will be the unit testing method), in other words: how can i use a loop in order to send different output to my test methods for each iteration of the loop?   </p>

<pre><code>@BeforeTest
    public void baseTestBeforeTest() throws Exception {

        String cageInstanceIp = Configuration.prop.getProperty(""suite.pusher.defaultParams.cageInstanceIp"");

        addingAllFilesToList();

        int size = this.files.size();
        System.out.println(""number of session to be run are: "" + size);
        for(int i=0;i&lt;size;i++){

                System.out.println(""-------------------------------------------------------------------------------------------------------------------------"");
                System.out.println(""running test for the following json input file: "" + this.files.get(i));
                System.out.println(""-------------------------------------------------------------------------------------------------------------------------"");
                this.list=this.runHelperForTestsPreparationMethods.runHelperPreparation(this.files.get(i), this.list);
                if(i==size-1){
                    isLast=true;
                }
                runTestSuite();
        }

      }
</code></pre>

<p>This is runTestSuite() method:</p>

<pre><code>@Test
    public void runTestSuite() throws Exception {
       this.runHelperForTestsPreparationMethods.testCompareJsonPercentage(this.isLast);
          testCompareJsonPercentage(isLast);

    }
</code></pre>

<p>But what I get is that after the for loop is done and running tests as expected for each input it then goes right away again to runTestSuite() method as part of the logic of TestNG, I want to be able to not face this issue and to run base test and test (unit testing) for each input. </p>

<p>I searched the network for solution but did not find any... </p>
",https://stackoverflow.com/questions/49614881/enabling-running-single-test-for-each-input-managed-by-for-loop-in-java-using-te,"['java', 'unit-testing', 'testing', 'automated-tests']",32,TRUE,0,1
How to get messages sent with the `array` mail driver?,"<p>Starting from version 5.7 Laravel suggests to use the <code>array</code> driver for Mail during testing:</p>

<p><a href=""https://github.com/laravel/laravel/blob/v5.7.0/phpunit.xml#L31"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/mD5ET.png"" alt=""""></a></p>

<p>Unfortunately, <a href=""https://laravel.com/docs/5.7/mail"" rel=""noreferrer"">the documentation</a> tells nothing about this driver. According to <a href=""https://github.com/laravel/framework/blob/5.7/src/Illuminate/Mail/Transport/ArrayTransport.php"" rel=""noreferrer"">the source code</a>, the driver stores all the messages in memory without actually sending them. How to get the stored ""sent"" messages during unit testing (in order to check them)?</p>
",https://stackoverflow.com/questions/52176937/how-to-get-messages-sent-with-the-array-mail-driver,"['php', 'laravel', 'laravel-5']",3415,TRUE,7,4
Instantiate mockup model with codeception,"<p>I'm doing some unit testing with laravel using codeception</p>

<p>I have a mock model class that goes like this</p>

<pre><code>&lt;?php namespace framework\tests\unit\mockModel;

    use \Codeception\Stub;
    use project\mvc\model\modelPermissionLevel;
    use project\mvc\model\modelUser;
    use project\mvc\model\modelApplicantsRestriction;

    class mockModels
    {
    }
</code></pre>

<p>and my test class goes like this</p>

<pre><code>&lt;?php
use framework\tests\unit\mockModel\mockModels;

class blAuthenticationTest extends \Codeception\Test\Unit
{ 
    protected function _before()
    {
        $this-&gt;mockModels = new mockModels();
    }
}
</code></pre>

<p>it showing me an error  [Error] Class 'framework\tests\unit\mockModel\mockModels' not found. I don't know where I did wrong </p>
",https://stackoverflow.com/questions/53661584/instantiate-mockup-model-with-codeception,"['php', 'laravel', 'phpunit', 'codeception']",77,FALSE,0,1
Unit test for insertedFact in optaplanner,"<p>How do we unit test rules in optaplanner that depend on <strong>insertedFact</strong>? </p>

<p>As per the examples for drools, its inserting fact using <strong>session</strong> object and then unit testing the actual rule. How can we access session object in optaplanner? I am creating SolverFactory using xml resource. </p>
",https://stackoverflow.com/questions/52900070/unit-test-for-insertedfact-in-optaplanner,"['unit-testing', 'drools', 'optaplanner', 'drools-planner']",73,FALSE,0,1
vue.js eslint how to get rid of the warning : Could not find a declaration file for module,"<p>unit testing a component, I have to import a mixin ( vue-howler)  </p>

<pre><code>import VueHowler from ""vue-howler"";  
</code></pre>

<p>I am getting a warning on the import regarding the implicit any ... </p>

<pre><code>[ts]
Could not find a declaration file for module 'vue-howler'. '/Users/yves/Developments/WIP/VUE.JS-cli-3/3-chocha-home-content/chocha/node_modules/vue-howler/dist/vue-howler.common.js' implicitly has an 'any' type.
  Try `npm install @types/vue-howler` if it exists or add a new declaration (.d.ts) file containing `declare module 'vue-howler';`
</code></pre>

<p>How I can solve this warning ? there is no @types/vue-howler ) ?</p>

<p>here is the related package.json eslint block</p>

<pre><code>package.json

....
 ""eslintConfig"": {
    ""root"": true,
    ""env"": {
      ""node"": true
    },
    ""extends"": [
      ""plugin:vue/essential"",
      ""@vue/prettier""
    ],
    ""rules"": {
      ""no-console"": 0
    },
    ""parserOptions"": {
      ""parser"": ""babel-eslint""
    }
  },
 ....
</code></pre>

<p>thanks for feedback</p>
",https://stackoverflow.com/questions/52428247/vue-js-eslint-how-to-get-rid-of-the-warning-could-not-find-a-declaration-file,"['vue.js', 'eslint']",146,FALSE,0,1
How to mock data with array inside object in jest,"<p>I am using jest for unit testing in react native. Here is my componentWillMount() function:</p>

<pre><code>componentWillMount() {
    this.setState({ loading: true });
    axios.get(SERVER_URL + '/courses')
        .then(response =&gt; {

            this.state.trainingcatalogues = []
            this.state.traininglist = []
            this.state.Location1 = []
            this.state.Category1 = []
            this.state.Location2 = ['All']
            this.state.Category2 = ['All']                
            for (var key in response.data) {
                if (response.data[key].coursetype === 'Instructor-Led' &amp;&amp; response.data[key].status === 'Active' ) {
                    this.state.Location1.push(response.data[key].location);
                    this.state.Category1.push(response.data[key].category);
                    this.state.trainingcatalogues.push(response.data[key]);
                    this.state.traininglist.push(response.data[key]);
                }
            } 
</code></pre>

<p>I want to mock the 'response' in my test case. It has the following format:</p>

<pre><code>let response = 
   {
     ""data"": [
       {
         ""_id"": ""5acb16701e09ae8abc29e7fb"",
         ""courseName"": ""Agile Fundamentals420"",
         ""category"": ""Agile"",
         ""coursetype"": ""Instructor-Led"",
         ""duration"": 22,
         ""addnote"": ""contractor"",
         ""status"": ""Completed"",
         ""registrations"": 10
       }
     ]
   }
</code></pre>

<p>This is my unit test case:</p>

<pre><code>it('should test the componentwillMount function', () =&gt; {
 const wrapper = shallow(&lt;Instructor_cata navigation = {navigation}/&gt;);
    const instance = wrapper.instance();
    const componentWillMountSpy = jest.spyOn(instance,""componentWillMount"");
    instance.forceUpdate();
    instance.componentWillMount();
    expect(componentWillMountSpy).toHaveBeenCalled(); 
</code></pre>

<p>});</p>

<p>How do I mock this response data inside the unit test case?</p>
",https://stackoverflow.com/questions/50596000/how-to-mock-data-with-array-inside-object-in-jest,"['unit-testing', 'react-native', 'jestjs', 'enzyme']",6720,FALSE,1,1
How to use import statement instead of require TypeScript,"<pre><code> const proxyquire = require('proxyquireify')(require);
</code></pre>

<p>I'm using proxyquire to mock dependencies for jasmine in unit testing. When i use the code mentioned above, I'm getting some errors because of using 'require' method. </p>

<p>Is there any way to use import statement for this scenario instead of require or is there any alternative to proxyquire?</p>
",https://stackoverflow.com/questions/53183650/how-to-use-import-statement-instead-of-require-typescript,"['javascript', 'typescript', 'gulp', 'jasmine', 'karma-jasmine']",107,FALSE,1,0
Excluding jars via Gradle in unit tests,"<p>I'm including some locally-built libs from another project by using <code>fileTree()</code>:</p>

<pre><code>dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    ...
}
</code></pre>

<p>For unit testing, I want to use my own mock classes instead of those jars. How can I have the <code>testImplementation</code> configure <em>not</em> use those jar files and instead use similarly-named classes out of my source hierarchy?</p>
",https://stackoverflow.com/questions/52787449/excluding-jars-via-gradle-in-unit-tests,"['java', 'android', 'gradle']",1965,TRUE,1,2
How to get Mocha to execute unit tests in multiple subfolders in Node.js,"<p>I'm integrating tests into my Node server and am having some trouble with unit testing. When I run <code>npm test</code> in my root directory, Mocha automatically runs all tests inside of my <code>test</code> folder. However, the unit tests which are dispersed throughout the project do not run. How can I ensure that Mocha automatically runs them?</p>
",https://stackoverflow.com/questions/48245004/how-to-get-mocha-to-execute-unit-tests-in-multiple-subfolders-in-node-js,"['javascript', 'node.js', 'mocha.js']",1964,TRUE,4,2
Vue-test-utils | Jest: How to handle dependencies?,"<p><strong>THE SITUATION:</strong></p>

<p>I am implementing unit-testing in my Vue app, using vue-test-utils with Jest configuration.</p>

<p>When I am testing simple components everything is fine. But when I am testing components that import other dependencies, the test fails.</p>

<p><strong>CONFIGURATION:</strong></p>

<p>Vue version: <code>2.5.17</code> <br>
@vue/test-utils: <code>1.0.0-beta.20</code> <br>
cli-plugin-unit-jest: <code>3.0.3</code> <br>
babel-jest: <code>23.0.1</code></p>

<p><strong>THE ERROR MESSAGE:</strong></p>

<p>The exact error message depends on which dependency I am importing.</p>

<p>For example with <a href=""https://github.com/epicmaxco/epic-spinners"" rel=""noreferrer"">epic-spinners</a> the error is:</p>

<pre><code>SyntaxError: Unexpected token import
</code></pre>

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

<p>With <a href=""https://github.com/wyzant-dev/vue-radial-progress"" rel=""noreferrer"">vue-radial-progress</a> the error is:</p>

<pre><code>SyntaxError: Unexpected token &lt;
</code></pre>

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

<p><strong>HOW TO REPRODUCE:</strong></p>

<ul>
<li>Make a fresh install of vue (with Jest as unit testing suite)</li>
<li>Run the example test, it should pass</li>
<li>Install a dependency (for example: <code>npm install --save epic-spinners</code>)</li>
<li>Import the dependency inside the HelloWorld component</li>
<li>Run the test again (without changing anything)</li>
</ul>

<p>If I do these steps, the test fails with the above error message.</p>

<p><strong>THE QUESTION:</strong></p>

<p>How can I handle dependencies import in vue-test-utils / Jest ?</p>
",https://stackoverflow.com/questions/52777978/vue-test-utils-jest-how-to-handle-dependencies,"['unit-testing', 'vue.js', 'vuejs2', 'jestjs', 'vue-test-utils']",2745,TRUE,5,3
helper functions in jasmine standalone,"<p>I have a Spec file unit testing a bunch of methods. In the same file I have helper functions. Is there a way to move the helper functions to a separate file with jasmine standalone and vanilla js?  </p>

<pre><code>  describe('#formatDateAndTime', () =&gt; {
    it('formats the date and time as per the requirements', () =&gt; {
      expect(till._formatDateAndTime()).toEqual(timeAndDate());
    });
  });

  function timeAndDate () {
    let today = new Date();
    return [today.getFullYear() + '.' + (today.getMonth() + 1) + '.' +
    today.getDate() + ' ' + today.getHours() + ':' + today.getMinutes() +
    ':' + today.getSeconds()];
  }
</code></pre>

<p>how can I move timeAndDate() function to a helper file </p>
",https://stackoverflow.com/questions/53964495/helper-functions-in-jasmine-standalone,"['javascript', 'jasmine', 'helper']",737,TRUE,-2,1
Vue/Typescript/Jest - Jest Unit Test SyntaxError: Unexpected token import,"<p>I am running a Vue/Typescript/Vuetify project(Created with vue cli 3). For unit testing I am using Jest. I upgraded to a newer version of Vuetify(1.3.1). Since the upgrade I get an error when running my Jest tests:</p>

<pre><code>location_to_project\node_modules\vuetify\lib\index.js:1
    ({""Object.&lt;anonymous&gt;"":function(module,exports,require,__dirname,__filename,global,jest){import Vuetify from './components/Vuetify';
                                                                                        ^^^^^^
   SyntaxError: Unexpected token import

      1 | import Vue from 'vue'
      2 | // @ts-ignore
    &gt; 3 | import Vuetify from 'vuetify/lib'
        | ^
      4 | import 'vuetify/src/stylus/app.styl'
      5 |
      6 | Vue.use(Vuetify, {

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:4    7)
03:17)
      at Object.&lt;anonymous&gt; (src/plugins/vuetify.ts:3:1)
</code></pre>

<h3>Versions and Environment</h3>

<p><code>Vuetify: 1.3.0</code>
<code>Vue: 2.5.17</code></p>

<h3>Previously worked in:</h3>

<p><code>Vuetify: 1.2.10</code>
<code>Vue: 2.5.17</code></p>

<p>babel.config.js</p>

<pre><code>module.exports = {
  presets: [
        [
            ""@vue/app"",
            {
                useBuiltIns: ""entry""
            }
    ],
  ],
};
</code></pre>

<p>tsConfig Compiler:</p>

<p><code>""target"": ""esnext""</code></p>

<p><code>""module"": ""esnext""</code></p>
",https://stackoverflow.com/questions/52950214/vue-typescript-jest-jest-unit-test-syntaxerror-unexpected-token-import,"['typescript', 'vue.js', 'jestjs', 'vuetify.js', 'babel-jest']",1284,TRUE,2,2
Difference between feature test and integration testing,"<p>I am currently developing a Project using Laravel5.7 and now am doing testing part. I have written code for unit testing in tests/unit directory. 
Next thing I see is a test/Feature directory. So my question is whether feature testing and integration testing are the same or do they have any difference.</p>

<p>Any help is appreciated</p>
",https://stackoverflow.com/questions/53863076/difference-between-feature-test-and-integration-testing,"['php', 'laravel', 'eloquent']",3972,TRUE,7,1
Testing forms in angular,"<p>I have been unit testing angular forms validation using Jasmine and Karma. Now I want to use protractor and karma for the same thing. To test if the inputs are valid or not (maxlength, required, etc).</p>

<p>Is it possible in protractor, since it is used for end to end testing?</p>

<p>Thanks,</p>
",https://stackoverflow.com/questions/50655360/testing-forms-in-angular,"['javascript', 'html', 'angular', 'unit-testing']",79,TRUE,2,1
[Vue warn]: Unknown custom element: &lt;nuxt-link&gt; - When running jest unit tests,"<p><strong>Problem</strong></p>
<p>I'm using nuxt 1.4 with routing using Jest to do unit testing. My application doesn't throw errors and seems to work perfectly. However when running my unit test <code>npm run unit</code> (which runs jest) it throws an error in the terminal: <code>[Vue warn]: Unknown custom element: &lt;nuxt-link&gt; - did you register the component correctly? For recursive components, make sure to provide the &quot;name&quot; option.</code></p>
<p><strong>Expected</strong></p>
<p>I would expect it to not throw this error since my application is working.</p>
<p><strong>Files</strong></p>
<p><code>package.json</code>:</p>
<pre class=""lang-json prettyprint-override""><code>{
  &quot;name&quot;: &quot;vue-starter&quot;,
  &quot;version&quot;: &quot;1.0.0&quot;,
  &quot;description&quot;: &quot;Nuxt.js project&quot;,
  &quot;private&quot;: true,
  &quot;scripts&quot;: {
    &quot;dev&quot;: &quot;nuxt&quot;,
    &quot;build&quot;: &quot;nuxt build&quot;,
    &quot;start&quot;: &quot;nuxt start&quot;,
    &quot;generate&quot;: &quot;nuxt generate&quot;,
    &quot;lint&quot;: &quot;eslint --ext .js,.vue --ignore-path .gitignore .&quot;,
    &quot;precommit&quot;: &quot;npm run lint&quot;,
    &quot;test&quot;: &quot;npm run lint &amp;&amp; npm run unit&quot;,
    &quot;unit&quot;: &quot;jest&quot;,
    &quot;unit:report&quot;: &quot;jest --coverage&quot;
  },
  &quot;dependencies&quot;: {
    &quot;babel-jest&quot;: &quot;^22.4.1&quot;,
    &quot;jest-serializer-vue&quot;: &quot;^1.0.0&quot;,
    &quot;node-sass&quot;: &quot;^4.7.2&quot;,
    &quot;npm&quot;: &quot;^5.7.1&quot;,
    &quot;nuxt&quot;: &quot;^1.0.0&quot;,
    &quot;sass-loader&quot;: &quot;^6.0.7&quot;,
    &quot;vue-jest&quot;: &quot;^2.1.1&quot;
  },
  &quot;devDependencies&quot;: {
    &quot;@vue/test-utils&quot;: &quot;^1.0.0-beta.12&quot;,
    &quot;babel-eslint&quot;: &quot;^8.2.1&quot;,
    &quot;eslint&quot;: &quot;^4.15.0&quot;,
    &quot;eslint-friendly-formatter&quot;: &quot;^3.0.0&quot;,
    &quot;eslint-loader&quot;: &quot;^1.7.1&quot;,
    &quot;eslint-plugin-vue&quot;: &quot;^4.0.0&quot;,
    &quot;jest&quot;: &quot;^22.4.2&quot;
  },
  &quot;browserslist&quot;: [
    &quot;&gt; 1%&quot;,
    &quot;last 2 versions&quot;,
    &quot;not ie &lt;= 8&quot;
  ],
  &quot;jest&quot;: {
    &quot;moduleFileExtensions&quot;: [
      &quot;js&quot;,
      &quot;vue&quot;
    ],
    &quot;transform&quot;: {
      &quot;^.+\\.js$&quot;: &quot;&lt;rootDir&gt;/node_modules/babel-jest&quot;,
      &quot;.*\\.(vue)$&quot;: &quot;&lt;rootDir&gt;/node_modules/vue-jest&quot;
    },
    &quot;snapshotSerializers&quot;: [
      &quot;&lt;rootDir&gt;/node_modules/jest-serializer-vue&quot;
    ]
  }
}
</code></pre>
<p>The component that I test:</p>
<pre class=""lang-html prettyprint-override""><code>&lt;template&gt;
  &lt;div&gt;
    &lt;nuxt-link class=&quot;name&quot; :to=&quot;{ path: `entity/${item.id}`, params: { id: item.id }}&quot;&gt;{{item.name}}&lt;/nuxt-link&gt;
    &lt;button class=&quot;connect&quot; @click=&quot;connect&quot;&gt;{{ btnText }}&lt;/button&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
  // import nuxtLink from '../.nuxt/components/nuxt-link';

  const connectionStatusMap = [
    'Connect',
    'Connected',
    'Pending',
    'Cancel',
  ];

  export default {
    /*components: {
      'nuxt-link': nuxtLink,
    },*/
    props: {
      item: {
        type: Object
      }
    },
    ...
  }
&lt;/script&gt;
</code></pre>
<p>My test script:</p>
<pre class=""lang-js prettyprint-override""><code>import TestItem from '../components/TestItem';
import { shallow, mount, createLocalVue } from '@vue/test-utils';
import Vuex from 'vuex';
import VueRouter from 'vue-router';

const localVue = createLocalVue()

localVue.use(Vuex)
localVue.use(VueRouter)

...
it(`should show the entity`, () =&gt; {
    const wrapper = mount(TestItem, {
      propsData: { item },
      localVue,
      store,
      // stubs: ['nuxt-link'],
    })
    expect(wrapper.find('.name').text()).toBe(item.name);
  });

  it(`should show allow me to connect if I'm not yet connected`, () =&gt; {
    const wrapper = shallow(TestItem, {
      propsData: { item },
      localVue,
      store,
      stubs: ['nuxt-link'],
    })
    expect(wrapper.find('.connect').text()).toBe('Connect');
  });
  ...
</code></pre>
<p><strong>I tried</strong></p>
<p>I tried creating a localVue and also stubbing the component as suggested <a href=""https://github.com/vuejs-templates/webpack/issues/709#issuecomment-337778293"" rel=""noreferrer"">in this github comment</a>
I also tried <code>shallow</code>/<code>mount</code> but that did not seem to work either.</p>
",https://stackoverflow.com/questions/49665571/vue-warn-unknown-custom-element-nuxt-link-when-running-jest-unit-tests,"['vue.js', 'jestjs', 'vue-router', 'nuxt.js', 'vue-test-utils']",18543,TRUE,32,9
NPE on FilePart mock in Spring WebFlux at reactor.core.publisher.MonoWhen$WhenCoordinator,"<p>I would appreciate any hints on the following problem I've encountered. While unit testing multipart file upload service method in <code>Spring Reactive WebFlux</code> app, I am getting NPE for <code>reactor.core.publisher.MonoWhen$WhenCoordinator</code> as follows</p>

<pre><code>java.lang.NullPointerException
    at reactor.core.publisher.MonoWhen$WhenCoordinator.subscribe(MonoWhen.java:149) 
</code></pre>

<p>Complete log is listed below as well.</p>

<p>Test :</p>

<pre><code>@RunWith(SpringRunner.class)
@SpringBootTest
public class FileServiceTest2 {


@MockBean
private UploadedImageRepository uploadedImageRepository;

...

       @Test
        public void assembleImageTest() {
            UploadedImage ui1 = new UploadedImage(""1"", ""ui1.png"");
            UploadedImage ui2 = new UploadedImage(""2"", ""ui2.png"");

            FilePart filePart1 = mock(FilePart.class);
            FilePart filePart2 = mock(FilePart.class);

            given(this.uploadedImageRepository.save(ui1))
                    .willReturn(Mono.just(ui1));
            given(this.uploadedImageRepository.save(ui2))
                    .willReturn(Mono.just(ui2));
            given(this.uploadedImageRepository.findAll())
                    .willReturn(Flux.just(ui1, ui2));

            given(filePart1.filename())
                    .willReturn(ui1.getImageName());
            given(filePart1.transferTo(any()))
                    .willReturn(Mono.empty());
            given(filePart2.filename())
                    .willReturn(ui2.getImageName());
            given(filePart2.transferTo(any()))
                    .willReturn(Mono.empty());

            Flux&lt;FilePart&gt; files = Flux.just(filePart1, filePart2);

            StepVerifier.create(this.uploadService.createFile(files))
                    .verifyComplete();
        }
</code></pre>

<p>Under test :</p>

<pre><code>@Service
public class UploadService {

Mono&lt;Void&gt; createFile(Flux&lt;FilePart&gt; fileParts) {
        return fileParts.flatMap(part -&gt; {
            Mono&lt;UploadedImage&gt; savedToDBImage = this.uploadedImageRepository.save(
                    new UploadedImage(UUID.randomUUID().toString(), part.filename()))
                    .log(""createFile-fileSavedToDB""); // NPE!

            Mono&lt;Void&gt; copiedFile = Mono.just(Paths.get(UPLOAD_URL, part.filename()).toFile())
                    .log(""createFile-pathAssembled"")
                    .doOnNext(destinationFile -&gt; {
                        try {
                            destinationFile.createNewFile();
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    })
                    .log(""createFile-fileAssembled"")
                    .flatMap(part::transferTo)
                    .log(""createFile-fileCopied"");

            return Mono.when(savedToDBImage, copiedFile)
                    .log(""createFile-monoWhen"");
        })
                .log(""createFile-flatMap"")
                .then()
                .log(""createFile-done"");
    }
</code></pre>

<p><code>UploadedImage</code> class (w Lombok) :</p>

<pre><code>@Data
@RequiredArgsConstructor
@NoArgsConstructor
public class UploadedImage {

        @NonNull private String id;
        @NonNull private String imageName;

}
</code></pre>

<p>SpringData Reactive Repository:</p>

<pre><code>@Repository
public interface UploadedImageRepository extends ReactiveCrudRepository&lt;UploadedImage, String&gt; {

}
</code></pre>

<p>Logs are as follows:</p>

<pre><code>java.lang.NullPointerException
    at reactor.core.publisher.MonoWhen$WhenCoordinator.subscribe(MonoWhen.java:149)
    at reactor.core.publisher.MonoWhen.subscribe(MonoWhen.java:99)
    at reactor.core.publisher.MonoOnAssembly.subscribe(MonoOnAssembly.java:76)
    at reactor.core.publisher.MonoLogFuseable.subscribe(MonoLogFuseable.java:53)
    at reactor.core.publisher.Mono.subscribe(Mono.java:3080)
    at reactor.core.publisher.FluxFlatMap$FlatMapMain.onNext(FluxFlatMap.java:372)
    at reactor.core.publisher.FluxPeekFuseable$PeekFuseableSubscriber.onNext(FluxPeekFuseable.java:198)
    at reactor.core.publisher.FluxArray$ArraySubscription.slowPath(FluxArray.java:118)
    at reactor.core.publisher.FluxArray$ArraySubscription.request(FluxArray.java:91)
    at reactor.core.publisher.FluxPeekFuseable$PeekFuseableSubscriber.request(FluxPeekFuseable.java:138)
    at reactor.core.publisher.FluxFlatMap$FlatMapMain.onSubscribe(FluxFlatMap.java:332)
    at reactor.core.publisher.FluxPeekFuseable$PeekFuseableSubscriber.onSubscribe(FluxPeekFuseable.java:172)
    at reactor.core.publisher.FluxArray.subscribe(FluxArray.java:53)
    at reactor.core.publisher.FluxArray.subscribe(FluxArray.java:59)
    at reactor.core.publisher.FluxLogFuseable.subscribe(FluxLogFuseable.java:53)
    at reactor.core.publisher.FluxFlatMap.subscribe(FluxFlatMap.java:97)
    at reactor.core.publisher.FluxLog.subscribe(FluxLog.java:50)
    at reactor.core.publisher.MonoIgnoreElements.subscribe(MonoIgnoreElements.java:37)
    at reactor.core.publisher.MonoLog.subscribe(MonoLog.java:51)
    at reactor.core.publisher.Mono.subscribe(Mono.java:3080)
    at reactor.test.DefaultStepVerifierBuilder$DefaultStepVerifier.verify(DefaultStepVerifierBuilder.java:728)
    at reactor.test.DefaultStepVerifierBuilder$DefaultStepVerifier.verify(DefaultStepVerifierBuilder.java:700)
    at reactor.test.DefaultStepVerifierBuilder.verifyComplete(DefaultStepVerifierBuilder.java:566)
    at pb.sl.UploadService.createFile(FileServiceTest2.java:112)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    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.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:73)
    at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83)
    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:251)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    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:190)
    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)
</code></pre>
",https://stackoverflow.com/questions/50764658/npe-on-filepart-mock-in-spring-webflux-at-reactor-core-publisher-monowhenwhenco,"['mockito', 'reactive-programming', 'spring-test', 'spring-webflux', 'project-reactor']",3381,TRUE,0,1
How to unittest a python function that takes no arguments?,"<p>Say I have a python function called sample(). It takes no arguments. It returns a dictionary in the end though. How can I perform unit testing for such a function ? Can I test it with status code like 200 ? How can i test if the function is written correctly ?</p>
",https://stackoverflow.com/questions/48861309/how-to-unittest-a-python-function-that-takes-no-arguments,"['python', 'python-unittest']",1418,TRUE,0,2
TypeError: Cannot read property &#39;prototype&#39; of undefined + Jest + NodeJS,"<p>I am using jest for unit testing in of nodeJS APIs. I have installed jest and added it to the script in package.json as well. But facing the issue:</p>

<p>FAIL api/test/math.test.js
● Test suite failed to run</p>

<pre><code>TypeError: Cannot read property 'prototype' of undefined

 at module.exports (node_modules/request-promise-core/configure/request2.js:34:48)
 at Object.&lt;anonymous&gt; (node_modules/request-promise-native/lib/rp.js:15:1)
 at Object.&lt;anonymous&gt; (node_modules/jsdom/lib/api.js:6:17)

 Test Suites: 1 failed, 1 total
 Tests:       0 total
 Snapshots:   0 total
 Time:        0.091s
 Ran all test suites.
 npm ERR! code ELIFECYCLE
 npm ERR! errno 1
 npm ERR! chain-analytics@1.0.0 test: `jest`
 npm ERR! Exit status 1
 npm ERR!
 npm ERR! Failed at the sample-project@1.0.0 test script.
 npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
</code></pre>

<p>Below are my sample classes for the same :</p>

<p>math.js :</p>

<pre><code>  const sum = (a, b) =&gt; a + b
  const mul = (a, b) =&gt; a * b
  const sub = (a, b) =&gt; a - b
  const div = (a, b) =&gt; a / b

  export default { sum, mul, sub, div };
</code></pre>

<p>math.test.js :</p>

<pre><code> const  {sum, mul, sub, div}  = require(""./math"")

 test(""Adding 1 + 1 equals 2"", () =&gt; {
   expect(sum(1, 1)).toBe(2)
 })
 test(""Multiplying 1 * 1 equals 1"", () =&gt; {
   expect(mul(1, 1)).toBe(1)
 })
 test(""Subtracting 1 - 1 equals 0"", () =&gt; {
   expect(sub(1, 1)).toBe(0)
 })
 test(""Dividing 1 / 1 equals 1"", () =&gt; {
   expect(div(1, 1)).toBe(1)
 })
</code></pre>

<p>Any suggestions are appreciated. Thanks!</p>
",https://stackoverflow.com/questions/53612044/typeerror-cannot-read-property-prototype-of-undefined-jest-nodejs,"['javascript', 'node.js', 'jestjs', 'babel-jest']",4993,TRUE,3,3
custom data under unit test result,"<p>I want to add custom details to the unit test result under error message. I am using Microsoft visual studio test tools for unit testing. </p>

<p>I tried using <code>System.Diagnostics.Trace.WriteLine()</code> but that adds the data under <code>Result StandardOutput</code>, but I want the custom data in Result Message.</p>

<p>Any idea how to achieve that</p>
",https://stackoverflow.com/questions/49405033/custom-data-under-unit-test-result,"['c#', 'unit-testing', 'microsoft-test-manager']",134,TRUE,0,1
How to unit test &#39;Azure AD and OpenID Connect&#39; code in ASP.NET MVC app,"<p>Hi I am using the Azure AD and OpenID Connect to authenticate users to my app. I have used the traditional code as mentioned in azure docs.</p>

<blockquote>
  <p>Startup.cs</p>
</blockquote>

<pre><code>public partial class Startup
{
    /// &lt;summary&gt;
    /// Function to set the authentication configurtion
    /// &lt;/summary&gt;
    /// &lt;param name=""app""&gt;Owin properties&lt;/param&gt;
    public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);
    }
}
</code></pre>

<blockquote>
  <p>Startup.Auth.cs</p>
</blockquote>

<pre><code>private void ConfigureAuth(IAppBuilder app) {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseCookieAuthentication(new CookieAuthenticationOptions());

        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions {
                ClientId = ""ClientId"",
                Authority = ""Authority"",
                PostLogoutRedirectUri = ""PostLogoutRedirectUri""
            });
    }
</code></pre>

<blockquote>
  <p>AccountController.cs</p>
</blockquote>

<pre><code>public class AccountController : Controller
{
    public void SignIn()
    {
        // Send an OpenID Connect sign-in request.
        if (!Request.IsAuthenticated) {
            HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties {RedirectUri = ""/""},
                OpenIdConnectAuthenticationDefaults.AuthenticationType);
        }
    }

    /// &lt;summary&gt;
    /// Function to signout the session user from the application
    /// &lt;/summary&gt;
    public void SignOut()
    {
        if (Request.Url == null) {
            return;
        }
        string callbackUrl = Url.Action(""SignOutCallback"", ""Account"", null, Request.Url.Scheme);

        HttpContext.GetOwinContext().Authentication.SignOut(
            new AuthenticationProperties {RedirectUri = callbackUrl},
            OpenIdConnectAuthenticationDefaults.AuthenticationType,
            CookieAuthenticationDefaults.AuthenticationType);
    }

    /// &lt;summary&gt;
    /// Function to redirect the user to home screen.
    /// &lt;/summary&gt;
    /// &lt;returns&gt;Redirects to home screen if authentication still exists&lt;/returns&gt;
    public ActionResult SignOutCallback()
    {
        if (Request.IsAuthenticated) {
            return RedirectToAction(""Index"", ""Home"");
        }

        return View();
    }
}
</code></pre>

<p>Not sure how to start unit testing the above code. I didn't find much useful resources on this topic, will <strong>appreciate</strong> any leads. </p>
",https://stackoverflow.com/questions/51191883/how-to-unit-test-azure-ad-and-openid-connect-code-in-asp-net-mvc-app,"['asp.net-mvc', 'unit-testing', 'azure-active-directory', 'owin', 'openid-connect']",783,TRUE,3,1
Test automation Google Apps Script Gmail Add-ons,"<p>I am working on Gmail Add-on using Google Apps Script. I am using <a href=""https://script.google.com"" rel=""nofollow noreferrer"">Clasp</a> to develop it on locally then using this I am pushing it to <a href=""https://codelabs.developers.google.com/codelabs/clasp"" rel=""nofollow noreferrer"">script.google.com</a>. </p>

<p>In local, I can do <strong>Unit testing</strong> using any JavaScript testing framework. </p>

<p>But is there any way to do <strong>Integration testing</strong> and automate it?</p>
",https://stackoverflow.com/questions/50560866/test-automation-google-apps-script-gmail-add-ons,"['google-apps-script', 'automation', 'integration-testing', 'gmail-addons']",480,FALSE,3,1
How can I Unit Test using mock with EPPlus?,"<p>I'm using EPPLus for a project, and I'm trying to just create an Excel Worksheet in memory to mock it.</p>

<p>the class I'm using for unit testing has a method</p>

<pre><code>public ExcelPackage GetExcelPackage()
{
    using (var package = new ExcelPackage())
    {
        ExcelWorksheet returnWorksheet = package.Workbook.Worksheets.Add(""worksheet"");
        returnWorksheet.Cells[1, 1].Value = ""043"";
        returnWorksheet.Cells[1, 2].Value = ""21677"";
        returnWorksheet.Cells[1, 3].Value = ""100"";
        returnWorksheet.Cells[1, 4].Value = String.Empty;
        returnWorksheet.Cells[1, 5].Value = ""12292016"";
        returnWorksheet.Cells[1, 6].Value = String.Empty;
        return package;
    }
}
</code></pre>

<p>In my InputFileController, I get a null object error when I call package.Workbook.Worksheets.First.</p>

<pre><code>public static IInputFileRepository ReadExcelFile(IFileDataSource excelFileDataSource)
    {
        FileInfo fileToRead = new FileInfo(excelFileDataSource.InputFile);
        List&lt;string&gt; lines = new List&lt;string&gt;();
        ExcelPackage package = excelFileDataSource.GetExcelPackage();
        ExcelWorksheet worksheet = package.Workbook.Worksheets.First();
</code></pre>

<p>Any idea what I could be doing wrong?</p>
",https://stackoverflow.com/questions/52877874/how-can-i-unit-test-using-mock-with-epplus,"['c#', 'unit-testing', 'mocking', 'epplus']",613,FALSE,1,2
Unable to perform mocking setup,"<p>I am trying to make use of nunit together with to do unit testing. However I am experiencing this error:</p>

<blockquote>
  <p>Moq.MockException: The following setups were not matched:
  <code>User m =&gt; m.encrptPassword(It.IsAny&lt;String&gt;(), It.IsAny&lt;String&gt;())</code></p>
</blockquote>

<p>The following is the snippet of my code that is having issues:</p>

<pre><code>private User _User;
Mock&lt;User&gt; mockUser;

[SetUp]
public void init()
{
    mockUser = new Mock&lt;User&gt;();
    _User = new User();
}

[Test]
[TestCase(""1"",""admin"",""??????_????k0O???qr#??%szq??` ?j???????D&gt;?????????Lvz??BP"")]
public void encryptPasswordTest(string userID, string password, string output)
{

    mockUser.Setup(m =&gt; m.encryptPassword(It.IsAny&lt;string&gt;(), It.IsAny&lt;string&gt;())).Returns(() =&gt; output);
    string result = _User.encryptPassword(userID, password);
    Assert.That(result.Equals(output));

    mockUser.VerifyAll();
}
</code></pre>

<p>The following is the method that I am trying to mock</p>

<pre><code>public virtual string encryptPassword(string userID, string password) {
    string hashed = """";
    HashAlgorithm sha256 = new SHA256CryptoServiceProvider();
    string salted = userID + password;
    byte[] result = sha256.ComputeHash(Encoding.ASCII.GetBytes(salted));
    hashed = Encoding.ASCII.GetString(result);
    return hashed;
}
</code></pre>
",https://stackoverflow.com/questions/51195876/unable-to-perform-mocking-setup,"['c#', 'unit-testing', 'nunit', 'moq']",71,TRUE,1,1
Is it possible to list array of component dependency injectors?,"<p>How do I list all the dependency injectors of a component in angular?</p>

<p>This requirement is for unit testing.</p>

<p>I have an instance of a component created as follows :</p>

<pre><code>component = fixture.componentInstance();
</code></pre>

<p>So in my test case, I need something like </p>

<p><code>console.log(component.constructor.params) // should print all the constructor parameteres</code></p>

<p>For ex in the below code : </p>

<pre><code>constructor(private _logger: LoggerService, private _router: Router,
                private _adminService: AdminService) {
}
</code></pre>

<p>I need to fetch array of DI's </p>

<pre><code>0 -&gt; LoggerService
1 -&gt; Router
2 -&gt; AdminService
</code></pre>
",https://stackoverflow.com/questions/50912115/is-it-possible-to-list-array-of-component-dependency-injectors,"['javascript', 'angular', 'typescript', 'karma-jasmine', 'angular2-testing']",534,FALSE,1,3
How to test for/mock JSON in typescript,"<p>I have the following <code>data.ts</code>. Assuming all the setup is done with jest and all ( I'll point you to any setup errors I get if any), how do I test for/mock <code>team.json</code> in a <code>data.spec.ts</code>? I'm new to unit testing and cant find helpful step by step resources with typescript.</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 { Student } from '../models';

const data: Student[] = require('../data/team.json');

/**
 * Returns an array of students
 *
 * @export
 * @returns {Student[]}
 */
export function getStudentData(): Student[] {
	return data;
}</code></pre>
</div>
</div>
</p>

<p>My <code>data.spec.ts</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>const getStudentData = require('./data');

test('gets students...', () =&gt; {
	// how to execute it here?
	
});</code></pre>
</div>
</div>
</p>

<p>Example <code>team.json</code> data</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>[
  {
    ""login"": ""jason"",
    ""id"": 1482046,
    ""site_admin"": false
  },
  {
    ""login"": ""michael"",
    ""id"": 1819122,
    ""site_admin"": false
  },
  {
    ""login"": ""arnold"",
    ""id"": 2323810,
    ""admin"": true
  }
]</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/49124812/how-to-test-for-mock-json-in-typescript,"['javascript', 'typescript', 'jestjs']",3669,FALSE,0,1
How to test a function that has side effects?,"<p>Given a function that does some operation on a database for instance. </p>

<p>In python, it would look like the following:</p>

<pre><code>def dao_transfer(cnx, account_id1, account_id2, money):
   spam = cnx.execute('query 1', account_id1)
   egg = cnx.execute('query 2', account_2, spam)
   return egg
</code></pre>

<p>What I do in my unit tests is that I mock the <code>cnx</code> object, and only check
that <code>cnx.execute</code> is called and that <code>dao_transfer</code> returns the last mock return value of <code>cnx.execute</code>. </p>

<p>I have the feeling that this poor testing.</p>

<p>What Django does, is that it doesn't unittest functions that interacts with the database but instead, do what I call <em>integration</em> tests ie. you spawn a full database, you load it with some initial data, execute your side-effect powered function and check that the database is in the correct state.</p>

<p>I could do that, but I'd rather prefer unittests. Is there an approach to unit testing side effect function that doesn't rely on checking every single side effect function calls arguments?</p>

<p>Is there pure approach to IO that allows better unit testing?</p>
",https://stackoverflow.com/questions/48279339/how-to-test-a-function-that-has-side-effects,"['testing', 'functional-programming', 'side-effects']",656,FALSE,3,0
How to set Jasmine global variables as coming from the window?,"<p>How can I add to <code>Jasmine</code> global variables for unit testing?</p>

<p>For example, I have function <code>foo</code> on window, and the testes code relies on that function.</p>

<p>And no, using this specific function as a pure function is not possible in this case.. it must be some mock for the window object..</p>
",https://stackoverflow.com/questions/53506740/how-to-set-jasmine-global-variables-as-coming-from-the-window,"['javascript', 'ecmascript-6', 'jasmine']",56,FALSE,0,0
MVC Core Get Controller ViewModel Results,"<p>I am trying to get result from Controller which calls Repository which extracts a ViewModel at the end, this is for Unit testing. The bold below is not working.</p>

<p>Compile error:</p>

<blockquote>
  <p>IAction Result does not contain a definition for View and no extension method View accepting a first argument of type IAction Result</p>
</blockquote>

<pre><code>public async Task&lt;IActionResult&gt; Search(int? id)
{
    return View(await _repository.GetProductData(id));
}

var searchresult1 = await _controller.Search(5);
</code></pre>

<p><strong><code>var modelresult = searchresult1.View.ProductName;</code></strong></p>
",https://stackoverflow.com/questions/50441288/mvc-core-get-controller-viewmodel-results,"['c#', 'asp.net-mvc', 'asp.net-core-mvc']",131,TRUE,2,1
Unit test mode identification in golang,"<p>I am building unit testing of the application that uses os.Exit(1), once os.Exit(1) executes remaining test file are skipped with go test, 
I am thinking about suppressing os.Exit during the unit test execution only. I wonder how I can determine that app has been bootstrap from go test runner?</p>
",https://stackoverflow.com/questions/48716090/unit-test-mode-identification-in-golang,['go'],550,TRUE,0,1
XUnit tests and live unit tests in Visual Studio 2017,"<p>Having Visual Studio 2017 last version. I am unable run XUnit tests from test explorer in asp.net core Solution.
However, ""dotnet test"" works properly and Live Unit testing work properly as well.</p>

<p>I couldn't find any information how to fix my Visual Studio.
May you all can suggest me something?</p>
",https://stackoverflow.com/questions/51721667/xunit-tests-and-live-unit-tests-in-visual-studio-2017,"['unit-testing', 'visual-studio-2017', 'xunit']",338,FALSE,0,0
unit test node.js mongoose mocha chai sinon,"<p>I'm new to unit testing. My Web API project is MVC base on node-express-mongoose.</p>

<p>I have a <code>conroller.js</code> as following:</p>

<pre><code>const getComments = async (req, res) =&gt; {
  let query = {};

  try {
    query = req.query.filter ? { email: new RegExp(`.*${req.query.filter}.*`, 'i') } : query;
    const comments = await util.getComments(query);
    return res.json(comments);
  } catch (err) {
    return res.status(500).send(`Internal server error: ${err}`);
  }
};
</code></pre>

<p>The controller use <code>util.js</code> function(s) which implements all database operations:</p>

<pre><code>const comments = require('../models/comments');

exports.getComments = (query) =&gt; {
      try {
        return comments.find(query).sort({ createdAt: -1 });
      } catch (err) {
        throw err;
      }
};
</code></pre>

<p>How do I create unit test using mocha &amp; chai? Do I have to create fake mock using sinon etc?</p>
",https://stackoverflow.com/questions/50546533/unit-test-node-js-mongoose-mocha-chai-sinon,"['node.js', 'unit-testing', 'mongoose', 'mocha.js', 'sinon']",2224,TRUE,0,2
What is the FakeItEasy equivalent of the Moq VerifyNoOtherCalls() method,"<p>I'm currently a Moq user and I'm researching other mocking frameworks.  </p>

<p>When unit testing I frequently call _mock.VerifyNoOtherCalls() so I can be certain there are no unexpected interactions beyond the ones that I have already verified.</p>

<p>I've searched the FakeItEasy docs and cannot find the equivalent option in their framework.  Can anyone suggest how I might do this?</p>
",https://stackoverflow.com/questions/53006106/what-is-the-fakeiteasy-equivalent-of-the-moq-verifynoothercalls-method,"['c#', 'moq', 'fakeiteasy']",994,TRUE,5,1
How to quickly run a static code snippet in Java using an IDE?,"<p>I'd like to quickly check the result of a static method I'm analyzing, within the IDE if possible.</p>

<pre><code>public static int foo(int a, int b){
    return (a &amp; 11) ^ b;
}
</code></pre>

<p>For example, right-click the expression and run it, something like</p>

<pre><code>&gt; foo(11, 2)
&gt; 9
&gt; foo(28, 3)
&gt; 11
</code></pre>

<p>I don't know the result in advance (the actual code is more complicated), so unit testing is out of the question.</p>

<p>How can I do this?</p>
",https://stackoverflow.com/questions/50483974/how-to-quickly-run-a-static-code-snippet-in-java-using-an-ide,"['java', 'eclipse', 'intellij-idea', 'static-analysis']",2293,TRUE,3,3
Test Visibility of Angular Component,"<p>Is there a way for me, using <code>offsetParent</code>, during unit testing using Jasmine/Karma to tell whether or not a component is visible?</p>

<p>If I have some component: </p>

<p><code>&lt;my-component *ngIf=""some condition""&gt;&lt;/my-component&gt;</code></p>

<p>I'd like to write a test that will check if the component is visible if <code>some condition</code> is true.</p>

<p>I was trying something like:</p>

<pre><code>// Assert
expect(ftuFixture.nativeElement.offsetParent).toEqual(!null);
</code></pre>

<p>Thanks</p>
",https://stackoverflow.com/questions/48890479/test-visibility-of-angular-component,"['javascript', 'angular']",532,FALSE,0,0
How do I unit test the method which has dependency on base classes?,"<p>I have a below class, which having base class and I am trying to write unit test.</p>

<pre><code>public class CarService : ServiceBase, IProvisioningService
{
    private IAuditRepository _repository;
    public CarService(IHostingFactory hostingFactory) : base(name, hostingFactory)
    {         

    }

    public override void DoWork()
    {
        if (_repository == null)
          {
             //its calling the base method.
            _repository = CurrentContext.ContainerFactory.GetInstance&lt;IAuditRepository&gt;();                  
        try
        {
            _repository.Insert(""something"");
        }
        catch (Exception ex)
        {

        }
    }       
  }
}
</code></pre>

<p>CurrentContext.ContainerFactory is part of base class. <code>CurrentContext.ContainerFactory</code> throws null exception. How do I create Mock for these classes?</p>

<p>Is interface is must for unit testing?</p>

<p><strong>Updated with base class</strong></p>

<pre><code>public abstract class ServiceBase : IServiceBase
{
    public HostingContext CurrentContext { get; }
    public string ServiceName { get; }

    protected ServiceBase(string serviceName, IHostingFactory hostingFactory)
    {
        ServiceName = serviceName;

        _stopSignal = false;
        CurrentContext = hostingFactory.CreateContext(serviceName);
        Logger = CurrentContext.LoggerInstance;
    }

}
</code></pre>

<p><strong>HostingContext class</strong></p>

<pre><code>   public class HostingContext
   {
        public HostingContext(
        Func&lt;string, ILogger&gt; loggerFactory,
        string serviceName, 
        string connString): this(loggerFactory(contextName),serviceName, connString, new ContainerFactory())
    {}
 }
</code></pre>

<p><strong>Unit Test Class</strong></p>

<pre><code>       MockRepository repository = new MockRepository(MockBehavior.Default);
       var containerFactoryMock = repository.Create&lt;IContainerFactory&gt;();
       var auditRepositoryMock = repository.Create&lt;IAuditRepository&gt;();
       var hostingFactoryMock = repository.Create&lt;IHostingFactory&gt;();
                   var hostingContextMock = new HostingContext(""Sample"", ""ConnString"",containerFactoryMock.Object);


        hostingFactoryMock.Setup(factory =&gt; factory.CurrentContext(It.IsAny&lt;string&gt;()))
            .Returns(hostingContextMock);
        CarService carService = new CarService(hostingFactoryMock.Object);

        carService.Work();
</code></pre>
",https://stackoverflow.com/questions/51473303/how-do-i-unit-test-the-method-which-has-dependency-on-base-classes,"['c#', 'unit-testing', 'moq']",432,TRUE,0,1
Junit Mockito Test Dependent Class Attribute,"<p>The objective is to perform Unit Testing Using mockito. In the first excercise, I created dummy object of dependent class attribute and tested the class, It works fine. </p>

<p>Now I want to mock the class attribute not directly under test using mockito. But I am getting NullPointerException. Kindly advise.</p>

<pre><code>        java.lang.NullPointerException
        at edu.uncc.ssdi.FlightReservation.&lt;init&gt;(FlightReservation.java:25)
        at edu.uncc.ssdi.FlightReservationTest.testFlightReservation_ParaConstructor(FlightReservationTest.java:44)
        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.mockito.internal.junit.JUnitRule$1.evaluateSafely(JUnitRule.java:52)
        at org.mockito.internal.junit.JUnitRule$1.evaluate(JUnitRule.java:43)
        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.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:538)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
        at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
</code></pre>

<p>FlightReservationTest</p>

<pre><code>        import static org.junit.Assert.assertEquals;

        import java.text.ParseException;
        import java.text.SimpleDateFormat;
        import java.util.Date;

        import org.junit.Before;
        import org.junit.Rule;
        import org.junit.Test;
        import org.mockito.Mock;
        import org.mockito.Mockito;
        import org.mockito.junit.MockitoJUnit;
        import org.mockito.junit.MockitoRule;

        public class FlightReservationTest {

        @Mock
        private Flight tempFlight;

        private Date tempDate;

        @Rule
        public MockitoRule rule = MockitoJUnit.rule();

        @Before
        public void setup() {
            tempDate = new Date();

        }

        @Test
        public void testFlightReservation_ParaConstructor() {
            try {

                Date date1 = new SimpleDateFormat(""dd/MM/yyyy"").parse(""26/05/2018"");

                // tempFlight = new Flight(""s1"",""s2"",""s3"",""s4"",date1,date1,100);

                FlightReservation fRes1 = new FlightReservation(tempFlight, tempDate, 1, 1);

                Mockito.when(tempFlight.getDepartureDate()).thenReturn(date1);
                Mockito.when(tempFlight.getArrivalDate()).thenReturn(date1);
                Mockito.when(tempFlight.getOriginAirport()).thenReturn(""s1"");
                Mockito.when(tempFlight.getDestinationAirport()).thenReturn(""s1"");

                assertEquals(tempFlight, fRes1.flightType);
                assertEquals(tempDate, fRes1.flightReservationDate);
                assertEquals(1, fRes1.noOfAdult);
                assertEquals(1, fRes1.noOfChildren);

            } catch (ReservationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

        }
</code></pre>

<p>FlightReservation </p>

<pre><code>     import java.util.Date;

    public class FlightReservation {

        public Flight flightType;
        public Date flightReservationDate;
        public int noOfAdult;
        public int noOfChildren;

        public FlightReservation() {

            flightType = null;
            flightReservationDate = null;
            noOfAdult = 0;
            noOfChildren = 0;
        }

        public FlightReservation(Flight flightType, Date flightReservationDate, int noOfAdult, int noOfChildren)
                throws ReservationException {
            super();
            String flightDetails = flightType.getOriginAirport() + ""--&gt;"" + flightType.getDestinationAirport();

            if (flightType.getDepartureDate().compareTo(flightReservationDate) &lt; 0)
                throw new ReservationException(
                        ""Departure Date must be atleast 1 day after Reservation/System Date "" + flightDetails);

            if (flightType.getArrivalDate().compareTo(flightType.getDepartureDate()) &lt; 0)
                throw new ReservationException(""Arrival Date is before Departure Date"" + "": "" + flightDetails);

            if (!checkAdultNo(noOfAdult))
                throw new ReservationException(""No of Adult cannot be less than 1"" + "": "" + flightDetails);

            this.flightType = flightType;
            this.flightReservationDate = flightReservationDate;
            this.noOfAdult = noOfAdult;
            this.noOfChildren = noOfChildren;

        }

        public boolean checkAdultNo(int noOfAdult) {

            boolean flag = true;

            if (noOfAdult &lt; 1) {

                flag = false;

            }

            return flag;
        }

    }
</code></pre>
",https://stackoverflow.com/questions/49966495/junit-mockito-test-dependent-class-attribute,"['java', 'unit-testing', 'junit', 'mockito']",419,FALSE,0,1
clojure.test should assert the equality of two different float point number within a certain range,"<p>I'm using <a href=""https://clojure.github.io/clojure/clojure.test-api.html"" rel=""nofollow noreferrer"">clojure.test</a> for unit testing.</p>

<p>Some of the tests fail because very close floating point numbers are considered differents.</p>

<pre><code>expected: (= expected result)
  actual: (not (= 1.0 0.9999999999999998))

expected: (= expected result)
  actual: (not (= 0.5 0.4999999999999999))
</code></pre>

<p>I need to instruct clojure.test to understand that <code>(= 0.9999 1.0)</code> is true.</p>

<p>As an example, with NUnit I could use <a href=""https://github.com/nunit/docs/wiki/EqualConstraint"" rel=""nofollow noreferrer"">Is.EqualTo().Within()</a> to achieve this.</p>

<p><strong>Note</strong></p>

<p>In my specific case, <code>1.0</code> and <code>0.999</code> are really the same thing.</p>
",https://stackoverflow.com/questions/50143364/clojure-test-should-assert-the-equality-of-two-different-float-point-number-with,"['unit-testing', 'clojure']",628,TRUE,3,2
Reverse proxy configuration for Karma during Angular testing,"<p>My application makes calls to a backend web service. During development I configure reverse proxy for the Angular CLI server and everything works fine. </p>

<pre><code>ng serve --proxy-config proxy.config.json
</code></pre>

<p>I need to do the same for Karma during unit testing. I add this to <code>karma.conf.js</code>.</p>

<pre><code>proxies: {
  ""/books"":""http://localhost:3000/"",
  ""/books/*"":""http://localhost:3000/"",
}
</code></pre>

<p>None of this works. My calls always get 404. If, however, I configure a full URL, it works.</p>

<pre><code>proxies: {
  ""/books/167"":""http://localhost:3000/books/167""
}
</code></pre>

<p>How can I properly configure reverse proxy using wildcard?</p>
",https://stackoverflow.com/questions/48890922/reverse-proxy-configuration-for-karma-during-angular-testing,"['angular', 'karma-runner']",2563,TRUE,11,2
c# Moq objects void method that changes objects parameter value,"<p>I'm trying to use Mocks in my Unit testing but I struggle with below code.
I want to Callback from AppendName method in right way so that this method is correctly tested and mocked object name is actually changed.</p>

<pre><code>public class GenericTests
{
   [TestMethod]
   public void TestMethod1()
   {
       IFile newFile = GetNewFile(""Document"").Object;
       newFile.AppendName();
       Assert.AreEqual(""AppendedDocument"", newFile.Name);
   }

   public Mock&lt;IFile&gt; GetNewFile(string name)
   {
       Mock&lt;IFile&gt; file = new Mock&lt;IFile&gt;();
       file.Setup(f =&gt; f.Name).Returns(name);
       file.Setup(f =&gt; f.Path).Returns(@""C:\Folder\"" + name);
       file.Setup(f =&gt; f.AppendName()).Callback.....problem is here.....

        return file;
   }
}
public interface IFile
{
    string Name { get; set; }
    string Path { get; set; }
    void AppendName();
}
public class LocalFile : IFile
{
    public string Name { get; set; }
    public string Path { get; set; }
    public void AppendName()
    {
        this.Name = ""AppendedDocument"";
    }
} 
</code></pre>

<p>Can someone please advice how to complete Callback for AppendName() ??? please</p>
",https://stackoverflow.com/questions/52349077/c-moq-objects-void-method-that-changes-objects-parameter-value,"['c#', 'mocking', 'moq']",1495,TRUE,0,1
karma unit test: How to resolve &#39;Error: No provider for &quot;framework:karma-sinon&quot;! (Resolving: framework:karma-sinon)&#39;?,"<p>I am trying to add the karma-sinon module to my angularjs unit test, this is a fragment of my karma config:</p>

<pre><code>frameworks: ['mocha','karma-sinon', 'chai', 'fixture'],
</code></pre>

<p>it also contains:</p>

<pre><code>plugins: [
      require(""karma-chai""),
      require(""karma-chrome-launcher""),
      require(""karma-coverage""),
      require(""karma-mocha""),
      require(""karma-mocha-reporter""),
      require(""karma-sourcemap-loader""),
      require(""karma-webpack""),
      require(""karma-fixture""),
      require(""karma-json-fixtures-preprocessor""),
      require(""karma-sinon"")
    ],
</code></pre>

<p>How can I resolve this error and start unit testing with sinon? Goal is to use  a spy statement so I am open to other solutions.</p>
",https://stackoverflow.com/questions/49371849/karma-unit-test-how-to-resolve-error-no-provider-for-frameworkkarma-sinon,"['angularjs', 'unit-testing', 'webpack', 'karma-jasmine', 'sinon']",237,FALSE,0,0
TypeError: Path must be a string. Received undefined,"<p>I a persistent error while using <code>serverless</code> framework with <code>serverless-offline</code> and <code>jest</code> unit testing module.</p>

<p>I am trying to test my serverless function (lambda) using <code>serverless-jest-plugin</code> which is supposed to integrate <code>jest</code> on <code>serverless</code>. Following is my <code>jest</code> configuration in my <code>serverless.yml</code>:
</p>

<pre><code>custom:
 default:
  stage: dev
 table:
  dictionary: Dictionary
  rules: Rules
 jest:
  verbose: true
  testResultsProcessor: jest-junit
  modulePaths: [""&lt;rootDir&gt;/node_modules"", ""&lt;rootDir&gt;/lib""]
  roots: [""&lt;rootDir&gt;/tests""]
  testEnvironment: node
plugins:
   - serverless-jest-plugin
   - serverless-dynamodb-local
   - serverless-offline
</code></pre>

<p>I have a lambda function which uses dynamoDB to get some data etc.</p>

<p>Whenever I use <code>sls invoke test</code> I have the following: 
</p>

<pre><code>$ sls invoke test
 FAIL  tests/file.test.js
  ● Test suite failed to run

TypeError: Path must be a string. Received undefined

  at assertPath (path.js:7:11)
  at Object.relative (path.js:1226:5)
  at process._tickDomainCallback (internal/process/next_tick.js:135:7)
Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.386s
Ran all test suites.
</code></pre>

<p>I'm running the following <code>package.json</code>:
</p>

<pre><code>{
  ""dependencies"": {
    ""ajv"": ""^6.1.1"",
    ""async"": ""^2.6.0"",
    ""aws-sdk"": ""^2.188.0"",
    ""notevil"": ""^1.1.0""
  },
  ""devDependencies"": {
    ""jest"": ""^22.2.1"",
    ""jest-junit"": ""^3.5.0"",
    ""serverless-dynamodb-local"": ""^0.2.27"",
    ""serverless-jest-plugin"": ""^0.1.6"",
    ""serverless-offline"": ""^3.16.0""
  }
}
</code></pre>

<p>Cheers.</p>
",https://stackoverflow.com/questions/48690247/typeerror-path-must-be-a-string-received-undefined,"['node.js', 'amazon-dynamodb', 'jestjs', 'serverless-framework', 'serverless-plugins']",2789,FALSE,4,0
Can we test ngrx flow by using Jasmine/Karma in Angular?,"<p>I have used ngrx for my angular application. Now i am trying to do unit testing by using Jasmine and karma tools But I couldn't find proper approach to test ngrx flow.</p>

<p>Kindly help me to provide any approach or else source also fine, Thanks in advance.</p>

<p>Please find below component which i am going to test.
<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>login-form.component.ts


import { Component, OnInit, AfterViewInit, AfterViewChecked, AfterContentInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';
import { ModalService } from '../../../@carbon/modal';
import { LoginResponse } from '../../../@core/login/login.contract';
import { LoginService } from '../../../@core/login/login.service';
import { SessionStorageService } from '../../../@core/session-storage/session-storage.service';
import { LocalStorageService } from '../../../@core/local-storage/local-storage.service';
import { Store } from '@ngrx/store';
import { AppState } from '../../../@models/app-state';
import { ActionSignIn, selectorLogin } from '../../../@core/login/login.reducer';
import { LoginState } from '../../../@core/login/login.state';
import { BusyState } from '../../../@shared/busy-indicator/busy-state';
import {Router} from '@angular/router';


@Component({
  selector: 'eose-login-form',
  templateUrl: './login-form.component.html',
  styleUrls: ['./login-form.component.scss']
})
export class LoginFormComponent implements OnInit {

 // loading: BusyState;
  loading: boolean = false;
  loadingMsg: string = '';
  authForm: FormGroup;
  changeForm: FormGroup
  constructor(
    private store: Store&lt;AppState&gt;,
    private fb: FormBuilder,
    private modalService: ModalService
  ) {
    this.authForm = this.fb.group({
      'env': new FormControl('cdtdevdir'),
      'email': new FormControl('', Validators.required),
      'password': new FormControl('', Validators.required),
      'newpassword': new FormControl(''),
      'confirmpassword': new FormControl('')
    })
  }

  handleLoadingChange(loadingState: BusyState) {
   // this.loading = loadingState;
  }


  ngOnInit() {
    this.store.select(selectorLogin)
    .subscribe((loginState: LoginState) =&gt; {
      this.loading = loginState.loading;
      this.loadingMsg = loginState.loadingMsg;
    })
  }

  openModal() {
    this.modalService.open('sign-in');
  }

  onLogin() {
     this.store.select(selectorLogin)
     .subscribe((loginState: LoginState) =&gt; {
       this.loading = loginState.loading;
     })
    console.log('Login Payload', this.authForm.value);
   this.store.dispatch(new ActionSignIn(this.authForm.value));
  }
}</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/51393920/can-we-test-ngrx-flow-by-using-jasmine-karma-in-angular,"['javascript', 'angular', 'unit-testing', 'karma-jasmine', 'ngrx']",282,FALSE,4,1
Redis unit test using redis mock,"<p>I'm using the <a href=""https://dzone.com/articles/java-redis-mock"" rel=""nofollow noreferrer"">following</a> tool to run an embedded redis for unit testing.</p>

<p>In the beginning of my <strong>registrationService</strong> is creating a new instance of redis server.</p>

<pre><code>@Import({RedisConfiguration.class})
@Service
public class RegistrationService

RedisTemplate redisTemplate = new RedisTemplate();  //&lt;- new instance

public String SubmitApplicationOverview(String OverviewRequest) throws IOException {

    . . .

    HashMap&lt;String,Object&gt; applicationData = mapper.readValue(OverviewRequest,new TypeReference&lt;Map&lt;String,Object&gt;&gt;(){});

    redisTemplate.setHashKeySerializer(new StringRedisSerializer());
    redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());

    UUID Key = UUID.randomUUID();

    redisTemplate.opsForHash().putAll(Key.toString(), (applicationData)); //&lt;-- ERRORS HERE

    System.out.println(""Application saved:"" + OverviewRequest);

    return Key.toString();
 }
}
</code></pre>

<p>And I'm starting a mock redis server in my <strong>Test</strong> below.</p>

<pre><code>...

RedisServer redisServer;

@Autowired
RegistrationService RegistrationService;

@Before
public void Setup() {
    redisServer = RedisServer.newRedisServer();
    redisServer.start();
}

@Test
public void testSubmitApplicationOverview() {
    String body = ""{\n"" +
            ""    \""VehicleCategory\"": \""CAR\"",\n"" +
            ""    \""EmailAddress\"": \""email@email.com\""\n"" +
            ""}"";
    String result = RegistrationService.SubmitApplicationOverview(body);

    Assert.assertEquals(""something"", result);
}
</code></pre>

<p>Redis settings in <strong>application.properties</strong></p>

<pre><code>#Redis Settings
spring.redis.cluster.nodes=slave0:6379,slave1:6379
spring.redis.url= redis://jx-staging-redis-ha-master-svc.jx-staging:6379
spring.redis.sentinel.master=mymaster
spring.redis.sentinel.nodes=10.40.2.126:26379,10.40.1.65:26379
spring.redis.database=2
</code></pre>

<p>However, I'm getting a <code>java.lang.NullPointerException</code> <strong>error on the following line</strong> in my service under test (registrationService).</p>

<pre><code>redisTemplate.opsForHash().putAll(Key.toString(), (applicationData));
</code></pre>
",https://stackoverflow.com/questions/50293800/redis-unit-test-using-redis-mock,"['unit-testing', 'redis']",14990,TRUE,4,1
Argument of type &#39;Observable&lt;LoginRequest&gt;&#39; is not assignable to parameter of type &#39;LoginRequest&#39;,"<p>I am trying to do unit testing by using Karma/Jasmine, I am getting error </p>

<blockquote>
  <p>Argument of type 'Observable' is not assignable to parameter of type 'LoginRequest'. Property 'userid' is missing in type 'Observable'</p>
</blockquote>

<p>I am getting the error in compile time in login.service.spec.ts where i am calling <code>service.login(loginRequest);</code>.</p>

<p>login.service.spec.ts</p>

<pre><code>import { ComponentFixture, TestBed, inject } from '@angular/core/testing';
import { ApiConnectorService } from '../api-handlers/api-connector.service';
import { LoginService } from './login.service';
import { HttpClient, HttpHandler } from '@angular/common/http'; 
import { Observable } from 'rxjs';
import { of } from 'rxjs/observable/of';
import { LoginResponse, LoginRequest } from './login.contract';


class ApiConnectorServiceStub {
  constructor() { }
  post(address: string, payload: LoginRequest): Observable&lt;LoginResponse&gt; {
    let str:LoginResponse = {token:'success'};
    return  of(str);
  }
}
describe('LoginService', () =&gt; {
  let service: LoginService;
  let fixture: ComponentFixture&lt;LoginService&gt;;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
           providers: [LoginService, ApiConnectorService, HttpClient, HttpHandler,
          {provide: ApiConnectorService, useClass: ApiConnectorServiceStub}]
    });
  });

  it('should be created', inject([LoginService], (service: LoginService) =&gt; {
    expect(service).toBeTruthy();
  }));

  it('should call post on apiConnectorService with right parameters when login is called',
                                          inject([LoginService], (service: LoginService) =&gt; {
    const apiConnectorStub = TestBed.get(ApiConnectorService);
    const str:LoginResponse = {token:'success'};
    const spy = spyOn(apiConnectorStub, 'post').and.returnValue(of(str));
    const lRequest: LoginRequest={userid:'spraju@gmail.com',password:'hsjshsj',newpassword:'hsjshsj'};
    const loginRequest = of(lRequest);
    service.login(loginRequest);

    expect(spy).toHaveBeenCalledWith('/api/login', loginRequest);
  })); 

});
</code></pre>

<p>login.service.ts</p>

<pre><code>import { Injectable } from '@angular/core';
import { ApiConnectorService } from '../api-handlers/api-connector.service';
import { LoginRequest, LoginResponse } from './login.contract';
import { Observable } from 'rxjs/Observable';
import { map } from 'rxjs/operators';
import * as marked from 'marked';

@Injectable()
export class LoginService {

  constructor(private apiConnector: ApiConnectorService) { }
  login(payload: LoginRequest): Observable&lt;LoginResponse&gt; {
    console.log('Login payload ', payload);
    return this.apiConnector.post('/api/login', payload)
      .pipe(
        map((data: LoginResponse) =&gt; data)
      )
  }

}
</code></pre>

<p>login.contract.ts</p>

<pre><code>export interface LoginRequest {
    env?: string;
    userid: string;
    password: string;
    newpassword: string;
}

export interface LoginResponse {
    token: string;
}
</code></pre>

<p>api-connector.service.ts</p>

<pre><code>import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { ErrorObservable } from 'rxjs/observable/ErrorObservable';
import { Observable } from 'rxjs/Observable';
import {environment} from '../../../environments/environment';
import { catchError } from 'rxjs/operators/catchError';


@Injectable()
export class ApiConnectorService {

  constructor(private http: HttpClient) { }

 private  getQueryString(params): string {
    const queryString = Object.keys(params).map(key =&gt; key + '=' + params[key]).join('&amp;');
    console.log('QUERY STRING', queryString);
    return ('?' + queryString);
  }

  private formatErrors(error: any) {
    return new ErrorObservable(error.error);
  }
  post(path: string, body: Object): Observable&lt;any&gt; {
    // console.log('API SERVICE BODY', body)
    return this.http.post(
      `${environment.base_url}${path}`,
      body
    ).pipe(catchError(this.formatErrors));
  }
}
</code></pre>
",https://stackoverflow.com/questions/51359228/argument-of-type-observableloginrequest-is-not-assignable-to-parameter-of-ty,"['javascript', 'angular', 'karma-jasmine']",1739,TRUE,1,1
How to really unit test Symfony forms?,"<p>The following example comes from the <a href=""https://symfony.com/doc/3.3/form/unit_testing.html#the-basics"" rel=""nofollow noreferrer"">official documentation</a>:</p>

<pre class=""lang-php prettyprint-override""><code>use AppBundle\Form\Type\TestedType;
use AppBundle\Model\TestObject;
use Symfony\Component\Form\Test\TypeTestCase;

class TestedTypeTest extends TypeTestCase
{
    public function testSubmitValidData()
    {
        $formData = array(
            'test' =&gt; 'test',
            'test2' =&gt; 'test2',
        );

        $form = $this-&gt;factory-&gt;create(TestedType::class);

        $object = TestObject::fromArray($formData);

        // submit the data to the form directly
        $form-&gt;submit($formData);

        $this-&gt;assertTrue($form-&gt;isSynchronized());
        $this-&gt;assertEquals($object, $form-&gt;getData());

        $view = $form-&gt;createView();
        $children = $view-&gt;children;

        foreach (array_keys($formData) as $key) {
            $this-&gt;assertArrayHasKey($key, $children);
        }
    }
}
</code></pre>

<p>However, with a real unit testing approach, the test should only contain an individual class as a <a href=""http://xunitpatterns.com/SUT.html"" rel=""nofollow noreferrer"">SUT</a>, everything else should be <a href=""http://xunitpatterns.com/Test%20Double.html"" rel=""nofollow noreferrer"">Test Doubles</a> like stubs, mock objects...</p>

<p><strong>How should we unit test a Symfony form using Test Doubles like mock objects?</strong></p>

<p>We could assume a simple form class:</p>

<pre class=""lang-php prettyprint-override""><code>class TestedType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            -&gt;add('firstname', TextType::class, [
                'label' =&gt; 'First name',
                'attr' =&gt; [
                    'placeholder' =&gt; 'John Doe',
                ],
            ])
    }
}
</code></pre>
",https://stackoverflow.com/questions/48082212/how-to-really-unit-test-symfony-forms,"['php', 'symfony', 'unit-testing', 'mocking', 'phpunit']",2194,TRUE,4,1
Is this Unit Test implemented correctly?,"<p>I have a unit test which is intended to check the access right and also make sure there is enough access right to file system before constructing a class. But, I think my unit test is violating the unit testing principle (FIRST) such as: Isolated/Independent and Thorough which are talking about building an independent unit test and also considering several aspects of failure scenarios. I also believe that this unit test in the way that is implemented is unit testing the .Net framework not the functionality of the code written by me because the underlying class is not mocked. But I would like to know your opinions as well and see how wrong or right I am.</p>

<p><em>Explanation of the Unit Test:</em></p>

<p>The unit test is trying to make sure that the constructor of <code>EventFeedFile</code> is executing a method which is checking the access rights. That method called <code>VerifyWritable()</code>. Note that the <code>EventFeedFile</code> is a separate class and the <code>VerifyWritable()</code> is seating in another class.</p>

<pre><code>[Test]
public void DirectoryNotWritableTest()
{
    var tempPath = Path.Combine(Path.GetTempPath(), ""EventFileDirectoryWriteDeniedTest"");
    int pageSize = 10;

    try
    {
        if (Directory.Exists(tempPath))
            Directory.Delete(tempPath, true);

        var directoryInfo = Directory.CreateDirectory(tempPath);
        var securityRules = directoryInfo.GetAccessControl();
        var writeDeniedRule =
            new FileSystemAccessRule(""Everyone"", FileSystemRights.CreateFiles, AccessControlType.Deny);
        securityRules.AddAccessRule(writeDeniedRule);
        directoryInfo.SetAccessControl(securityRules);

        // ReSharper disable once ObjectCreationAsStatement
        Assert.Throws&lt;UnauthorizedAccessException&gt;(() =&gt; new EventFeedFile(new PersistenceDirectory(tempPath),
            pageSize));
    }
    finally
    {
        if (Directory.Exists(tempPath))
            Directory.Delete(tempPath, true);
    }
}

/// &lt;param name=""directory""&gt;The directory containing the persistence file.&lt;/param&gt;
/// &lt;param name=""pageSize""&gt;The size of event feed page.&lt;/param&gt;
public EventFeedFile(PersistenceDirectory directory, int pageSize)
{
    directory.EnsureExists();
    directory.VerifyWritable();
    mParentDirectory = directory.TargetPath;
    mFullName = Path.Combine(mParentDirectory, Constants.FILE_NAME_EVENTPERSISTENCE);
    mPageSize = pageSize;
}

public void VerifyWritable()
{
    using (File.Create(
        Path.Combine(TargetPath, Path.GetRandomFileName()),
        1024,
        FileOptions.DeleteOnClose))
    {
    }
}
</code></pre>
",https://stackoverflow.com/questions/52778421/is-this-unit-test-implemented-correctly,"['c#', 'unit-testing']",182,TRUE,5,3
Difference between spec and test folders,"<p>I have a concept problem, I am working on a rails project &amp; as per my knowledge both the test &amp; spec are used for tests. Where test refers to unit testing &amp; spec refers to integration testing. But I want to have to have full idea about those two folders &amp; if they both refers to test then what is the major difference between them?</p>
",https://stackoverflow.com/questions/48828372/difference-between-spec-and-test-folders,"['ruby-on-rails', 'unit-testing', 'testing', 'integration-testing']",4049,TRUE,10,1
PHP method mock check for an argument passed to the method,"<p>I am using the Phpunit for unit testing and its mocking framework. I have a mock for a method:</p>

<pre><code>    $myProcessor
        -&gt;expects($this-&gt;once())
        -&gt;method(""myMockedMethodName"");
</code></pre>

<p>I would like to validate one of the arguments passed to it. </p>

<p>For example, my function takes arg1, arg2, arg3. I would like to check only for the arg2. </p>

<p>How to do with PHP mocks?</p>
",https://stackoverflow.com/questions/48775328/php-method-mock-check-for-an-argument-passed-to-the-method,"['php', 'mocking', 'phpunit']",104,TRUE,2,1
Unit tests - How to use Spring MockMVC to call soap service,"<p>I am unit testing my rest service using the code listed below and the request is successfully hitting the service.</p>

<pre><code>     import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;

     private MockMvc mvc;

     private URI = ""/order/1""

     this.mvc.perform(
            post(URI).headers(headers)
                    .contentType(MediaType.APPLICATION_JSON_UTF8)
                    .content(mapper.writeValueAsString(request))
                    .accept(MediaType.APPLICATION_JSON_UTF8))
            .andExpect(result -&gt; {
                response[0] = result.getResponse().getContentAsString();
                statusCode[0] = result.getResponse().getStatus();
            });
</code></pre>

<p>I am trying to test my soap service (<a href=""http://localhost:8080/OrderService/13.08.wsdl"" rel=""nofollow noreferrer"">http://localhost:8080/OrderService/13.08.wsdl</a>) using similar code. The endpoint seems to be up when I hit via browser , but seeing 404 in the result -</p>

<pre><code>import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;

     private MockMvc mvc;

     private URI = ""http://localhost:8080/OrderService/13.08.wsdl"";

     this.mvc.perform(
            post(URI).headers(headers)
                    .contentType(MediaType.TEXT_XML)
                    .content(request.toString())
                    .accept(MediaType.TEXT_XML))
            .andExpect(result -&gt; {
                response[0] = result.getResponse().getContentAsString();
                statusCode[0] = result.getResponse().getStatus();
            });
</code></pre>
",https://stackoverflow.com/questions/48310929/unit-tests-how-to-use-spring-mockmvc-to-call-soap-service,"['java', 'spring', 'spring-boot', 'junit', 'spring-mvc-test']",6470,TRUE,2,2
Check fallback key testing in enzyme,"<p>I'm doing unit-testing for component props in reactjs with jest and enzyme library.</p>

<p>Here all I need to test, <em>undefined key of JSON data</em> &amp; fallback for that keys written or not...</p>

<p>Here are pseudo code:</p>

<pre><code>    export class ActivityItem extends React.Component {
      render() {
        const { activity } = this.props;
        return (
          &lt;div className='item'&gt;
            &lt;p&gt;{activity.item}&lt;/p&gt;
          &lt;/div&gt;)
        }
     }
</code></pre>

<p>JSON Date: </p>

<pre><code>[{""id"": 1,
  ""item"": ""Rose""},
{ ""id"": 2,
  ""item"": ""Susain""}]
</code></pre>

<p>Testing cases</p>

<pre><code>  describe('check fallback for text key', () =&gt; {
    it('has value in text key', () =&gt; {
      wrapper = wrapper.find('ActivityItem')
      expect(wrapper.find('p').length).toBeGreaterThan(1);
    })
  })
</code></pre>

<p>Here I could not find <code>&lt;p&gt;</code> tag to check its value for test...</p>
",https://stackoverflow.com/questions/53815094/check-fallback-key-testing-in-enzyme,"['javascript', 'reactjs', 'unit-testing', 'jestjs', 'enzyme']",146,FALSE,0,1
"Flask application runs, but fails initial unit test","<p>I just started unit testing my flask application and it fails to return a 200 status code when I test it, even though it works perfectly.</p>

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

<pre><code># dev-environment/test_basic.py

import unittest
from application import application, db

TEST_DB = ""test.db""

class BasicTests(unittest.TestCase):
    def setUp(self):
        application.config['TESTING'] = True
        application.config['DEBUG'] = False
        application.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + TEST_DB
        self.application = application.test_client()
        db.drop_all()
        db.create_all()

        self.assertEqual(application.debug, False)

    def tearDown(self):
        pass

    def test_main_page(self):
        response = self.application.get(""/welcome"", follow_redirects=True)
        self.assertEqual(response.status_code, 200)


if __name__ == ""__main__"":
    unittest.main()
</code></pre>

<p>And here is my ""/welcome"" view in application.py:</p>

<pre><code># dev-environment/application.py

@application.route(""/welcome"")
def welcome():
    return render_template(""welcome.html"")
</code></pre>

<p>I get the following stack trace when I run the unit test file:</p>

<pre><code>======================================================================
FAIL: test_main_page (__main__.BasicTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File ""test_basic.py"", line 22, in test_main_page
    self.assertEqual(response.status_code, 200)
AssertionError: 404 != 200

----------------------------------------------------------------------
Ran 1 test in 0.475s

FAILED (failures=1)
</code></pre>
",https://stackoverflow.com/questions/51252936/flask-application-runs-but-fails-initial-unit-test,"['python', 'testing', 'flask']",433,FALSE,0,0
Is it possible to build .NET Standard + .NET Core class/library to .NET Standard only?,"<p>I have a class/library project using .NET Standard 2.0, and I want to add unit testing to it inside the project directly (so it's easier to spot and more coupled). But, because every test framework needs to specific platform, I have no choice but to add another framework such as .NET Core.</p>

<p>I need to build this project to .NET Standard only because I need to use it in another project (Unity project, where the framework chosen is .NET Standard 2.0).</p>

<p>Can I add .NET Core to the project so that I can use a unit testing framework, but build the final dll using .NET Standard only?</p>

<p>Or should I just give up and do it with another project referencing this project instead? Because it's more comfortable if the unit test is embedded within the project directly as to not forget to update the unit test when something change.</p>
",https://stackoverflow.com/questions/53353071/is-it-possible-to-build-net-standard-net-core-class-library-to-net-standard,"['c#', '.net']",317,TRUE,1,1
How to split a name in two parts after 2 white space?,"<p>Looking for one solution like. I had a word with three white space.so I want to split it into two line after 2nd white space.</p>

<p>Example : - </p>

<p><strong>Coding and Unit Testing</strong> </p>

<p>I want that in two line after and like this</p>

<p>1st Line</p>

<pre><code>  Coding and
</code></pre>

<p>2nd Line </p>

<pre><code>  Unit Testing
</code></pre>

<p>How can I do it in javascript?</p>

<p>Thanks inadvance </p>
",https://stackoverflow.com/questions/50159519/how-to-split-a-name-in-two-parts-after-2-white-space,['javascript'],99,TRUE,-3,1
jasmine unit test &quot;An error was thrown in afterAll&quot;,"<p>I'm just unit testing whether the component is created or not. Below is my spec file</p>

<pre><code>import { async, ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing';
import { CUSTOM_ELEMENTS_SCHEMA, DebugElement } from '@angular/core';
import { RouterTestingModule } from '@angular/router/testing';
import { MatTableModule } from '@angular/material';
import { HttpClientModule, HttpXhrBackend } from '@angular/common/http';
import { MockBackend } from '@angular/http/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';

import { ReleaseListComponent } from './release-list.component';
import { ReleaseService } from '../release.service';

describe('ReleaseListComponent', () =&gt; {
  let component: ReleaseListComponent;
  let fixture: ComponentFixture&lt;ReleaseListComponent&gt;;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
      imports: [RouterTestingModule, MatTableModule, HttpClientModule ],
      declarations: [ReleaseListComponent],
      providers: [ReleaseService]
    })
      .compileComponents();
  });

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(ReleaseListComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () =&gt; {
    expect(component).toBeDefined();
  });
</code></pre>

<p><strong>My component</strong></p>

<pre><code>import { Component, OnInit, ViewChild } from '@angular/core';
import { ReleaseService } from '../release.service';
import { MatPaginator, MatSort, MatTableDataSource } from '@angular/material';

@Component({
  selector: 'bw-release-list',
  templateUrl: './release-list.component.html'
})
export class ReleaseListComponent implements OnInit {
  title = 'Release notes';
  displayedColumns = ['title'];
  dataSource;

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

  constructor( private releaseNotes: ReleaseService ) { }

  ngOnInit() {
    this.releaseNotes.getReleaseNotes()
      .subscribe(data =&gt; {
        this.dataSource = new MatTableDataSource(data.results);
        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;
      });
  }
  applyFilter(filterValue: string) {
    filterValue = filterValue.trim();
    filterValue = filterValue.toLowerCase();
    this.dataSource.filter = filterValue;
  }
}
</code></pre>

<p>I'm getting <code>An error was thrown in afterAll</code>  I'm trying to debug for hours but no luck.</p>

<p>I tried <code>beforeEach</code> in both <code>async</code> and <code>sync</code>, I've also imported all the dependency file into the spec file. still throwing the same error. </p>

<p>please suggest me on how to resolve this issue.</p>
",https://stackoverflow.com/questions/52868272/jasmine-unit-test-an-error-was-thrown-in-afterall,"['angular', 'jasmine', 'karma-jasmine']",13487,TRUE,3,1
How to write Unit test for Controller method with two parameters and what scenarios are required to test?,"<p>I am new in Unit testing.  I would like to write unit tests for the Delete controller action. I want to use NSubstitute to mock all the dependencies. The current implementation is using an interface IRepository to abstract out calls to the underlying data source.</p>

<p>Controller</p>

<pre class=""lang-cs prettyprint-override""><code>public ActionResult Delete(string fileName, bool isPublic)
{
    try
    {
        repo.DeleteDocument(new PortalDocument
        {
            Path = fileName,
            IsPublic = isPublic
        });
    }
    catch (Exception e)
    {
        EventLog.Logger.LogCritical(e, e.Message);            
    }
    return RedirectToAction(IndexViewName);
}
</code></pre>

<p>Interface for repository.</p>

<pre class=""lang-cs prettyprint-override""><code>public interface IRepository&lt;out T&gt; where T: 
    CloudBlobContainer
{
    bool DeleteDocument(PortalDocument document);
}
</code></pre>

<p>PortalDocument Class</p>

<pre class=""lang-cs prettyprint-override""><code>public class PortalDocument
{
    public bool IsPublic { get; set; }
}
</code></pre>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/50277473/how-to-write-unit-test-for-controller-method-with-two-parameters-and-what-scenar,"['c#', 'asp.net-mvc', 'xunit', 'nsubstitute']",1752,TRUE,1,1
Jest test breaks on ngx-bootstrap BsModalService,"<p>I am switching to Jest for unit testing and have an angular 6 project using ngx-bootstrap. I get the error down below when running npm test.</p>

<p>I have a project to demonstrate this issue here: <a href=""https://github.com/ronlawrence3/ngx-bootstrap-example"" rel=""nofollow noreferrer"">https://github.com/ronlawrence3/ngx-bootstrap-example</a> (jasmine branch works, master jest test does not). </p>

<p>Can anyone tell me what I'm missing here? </p>

<p>Error:</p>

<pre><code>$ npm test

&gt; ngx-bootstrap-example@0.0.0 test /home/ron/p/ngx-bootstrap-example-jasmine
&gt; jest

 FAIL  src/app/app.component.spec.ts
  AppComponent
    ✕ should create the app (428ms)
    ✕ should have as title 'app' (9ms)

  ● AppComponent › should create the app

    Can't resolve all parameters for BsModalService: (?, ?).

      at syntaxError (../../../../execroot/angular/packages/compiler/src/util.ts:100:17)
      at CompileMetadataResolver.Object.&lt;anonymous&gt;.CompileMetadataResolver._getDependenciesMetadata (../../../../execroot/angular/packages/compiler/src/metadata_resolver.ts:959:27)
      at CompileMetadataResolver.Object.&lt;anonymous&gt;.CompileMetadataResolver._getTypeMetadata (../../../../execroot/angular/packages/compiler/src/metadata_resolver.ts:839:20)
      at CompileMetadataResolver.Object.&lt;anonymous&gt;.CompileMetadataResolver._getInjectableTypeMetadata (../../../../execroot/angular/packages/compiler/src/metadata_resolver.ts:1091:17)
      at CompileMetadataResolver.Object.&lt;anonymous&gt;.CompileMetadataResolver.getProviderMetadata (../../../../execroot/angular/packages/compiler/src/metadata_resolver.ts:1102:16)
      at ../../../../execroot/angular/packages/compiler/src/metadata_resolver.ts:1023:38
          at Array.forEach (&lt;anonymous&gt;)
      at CompileMetadataResolver.Object.&lt;anonymous&gt;.CompileMetadataResolver._getProvidersMetadata (../../../../execroot/angular/packages/compiler/src/metadata_resolver.ts:983:15)
      at ../../../../execroot/angular/packages/compiler/src/metadata_resolver.ts:532:36
          at Array.forEach (&lt;anonymous&gt;)
      at CompileMetadataResolver.Object.&lt;anonymous&gt;.CompileMetadataResolver.getNgModuleMetadata (../../../../execroot/angular/packages/compiler/src/metadata_resolver.ts:524:43)
      at JitCompiler.Object.&lt;anonymous&gt;.JitCompiler._loadModules (../../../../execroot/angular/packages/compiler/src/jit/compiler.ts:127:49)
      at JitCompiler.Object.&lt;anonymous&gt;.JitCompiler._compileModuleAndAllComponents (../../../../execroot/angular/packages/compiler/src/jit/compiler.ts:115:32)
      at JitCompiler.Object.&lt;anonymous&gt;.JitCompiler.compileModuleAndAllComponentsAsync (../../../../execroot/angular/packages/compiler/src/jit/compiler.ts:69:33)
      at CompilerImpl.Object.&lt;anonymous&gt;.CompilerImpl.compileModuleAndAllComponentsAsync (../../../../execroot/angular/packages/platform-browser-dynamic/src/compiler_factory.ts:68:27)
      at TestingCompilerImpl.Object.&lt;anonymous&gt;.TestingCompilerImpl.compileModuleAndAllComponentsAsync (../../../../execroot/packages/platform-browser-dynamic/testing/src/compiler_factory.ts:57:27)
      at TestBed.Object.&lt;anonymous&gt;.TestBed.compileComponents (../../../../execroot/packages/core/testing/src/test_bed.ts:335:27)
      at Function.Object.&lt;anonymous&gt;.TestBed.compileComponents (../../../../execroot/packages/core/testing/src/test_bed.ts:116:66)
      at src/app/app.component.spec.ts:16:9
      at ZoneDelegate.Object.&lt;anonymous&gt;.ZoneDelegate.invoke (node_modules/zone.js/dist/zone.js:388:26)
      at AsyncTestZoneSpec.Object.&lt;anonymous&gt;.AsyncTestZoneSpec.onInvoke (node_modules/zone.js/dist/async-test.js:106:39)
      at ProxyZoneSpec.Object.&lt;anonymous&gt;.ProxyZoneSpec.onInvoke (node_modules/zone.js/dist/proxy.js:125:39)
      at ZoneDelegate.Object.&lt;anonymous&gt;.ZoneDelegate.invoke (node_modules/zone.js/dist/zone.js:387:32)
      at Zone.Object.&lt;anonymous&gt;.Zone.runGuarded (node_modules/zone.js/dist/zone.js:151:47)
      at runInTestZone (node_modules/zone.js/dist/async-test.js:234:29)
      at node_modules/zone.js/dist/async-test.js:168:17
      at ZoneDelegate.Object.&lt;anonymous&gt;.ZoneDelegate.invoke (node_modules/zone.js/dist/zone.js:388:26)
      at ProxyZoneSpec.Object.&lt;anonymous&gt;.ProxyZoneSpec.onInvoke (node_modules/zone.js/dist/proxy.js:128:39)
      at ZoneDelegate.Object.&lt;anonymous&gt;.ZoneDelegate.invoke (node_modules/zone.js/dist/zone.js:387:32)
      at Zone.Object.&lt;anonymous&gt;.Zone.run (node_modules/zone.js/dist/zone.js:138:43)
      at Object.testBody.length.done (node_modules/jest-zone-patch/index.js:51:29)
</code></pre>
",https://stackoverflow.com/questions/51250688/jest-test-breaks-on-ngx-bootstrap-bsmodalservice,"['angular', 'jestjs', 'ngx-bootstrap']",671,FALSE,2,0
Mass Transit Test Harness,"<p>I have been working on unit testing a Mass Transit Project using <code>InMemoryTestHarness</code>.</p>

<p>I have referred to the following github code to work with it </p>

<p><a href=""https://github.com/MassTransit/MassTransit/blob/master/src/MassTransit.Tests/Testing/ConsumerTest_Specs.cs"" rel=""nofollow noreferrer""><code>ConsumerTest_Specs.cs</code></a></p>

<p>Could someone please explain what the following properties </p>

<ul>
<li><code>Sent</code></li>
<li><code>Published</code></li>
<li><code>Consumed</code></li>
</ul>

<p>to the <code>InMemoryTestHarness _harness</code> object actually mean.</p>

<p>Although the code has a Test Method associated with each, I'ld like a bit more explanation to it. </p>

<p>Thanks. </p>
",https://stackoverflow.com/questions/53431756/mass-transit-test-harness,"['.net', 'rabbitmq', 'masstransit']",1591,TRUE,2,1
Testing a method which uses another method from the same class,"<p>Recently I have gotten into unit testing my applications and have found myself at a bit of a difficult spot design wise in one of my classes.</p>

<p>I have a repository class which connects to the database, which looks a bit like this.</p>

<pre><code>public interface Repository {
  ...
  void register(Account account)
  Account find(String email)
  ...
}
</code></pre>

<p>which, in implementation does this:</p>

<pre><code>public class RepositoryImpl implements Repository {
  ...
  public void register(Account account) {
    if (find(account.getEmail() != null) return;
    // Account with same email already exists.
    ...
  }
}
</code></pre>

<p>This works fine in a live setting, but when unit testing it's a different story.</p>

<p>I use Mockito for mocking my dependencies, but I cant seem to mock the <code>find</code> method in the implementation class.</p>

<p>So my first thought was to inject a <code>Repository</code> in the <code>register</code> method which I than can fake, but that seems a bit weird since I provide a method with a class which it is a member of itself.</p>

<p>After that I thought to just copy the <code>find</code> logic to the <code>register</code> method, but that violates the DRY principle.</p>

<p>So.. any ideas on solving this design problem? I guess it's a common problem since it's quite standard to have unique emails in a system.</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/48172663/testing-a-method-which-uses-another-method-from-the-same-class,"['java', 'unit-testing', 'mockito']",1511,TRUE,3,1
OnTearDown not being called in NUnit test,"<p>I am to unit testing with NUnit and FakeItEsay. I have an issue as I have initialised some objects in the OnTearDown of the test expecting these will be readily available for all the tests that I write.</p>

<p>I am getting error in the tests as the objects are not initialised in any tests.</p>

<p>Am I missing something?</p>

<pre><code>using FakeItEasy;
using NUnit.Framework;    
[TestFixture]
public classs A
{
   obj a;
}
[TearDown]
public void OnTearDown()
{
     a = new object();
}

[test]
public void testA()
{
   var x = a;
  // a, x are null here, why??
}
</code></pre>
",https://stackoverflow.com/questions/51875319/onteardown-not-being-called-in-nunit-test,"['c#', 'nunit']",57,TRUE,2,1
Validate Command Monolog Output in Symfony 4 Unit Test,"<p>In <a href=""https://symfony.com/doc/current/console.html#testing-commands"" rel=""nofollow noreferrer"">https://symfony.com/doc/current/console.html#testing-commands</a>
Users can see how to test Commands using Unit Testing.</p>

<p>The issue is that following this process, Console output made via Monolog can't be tested. </p>

<pre><code>$output = $commandTester-&gt;getDisplay();
# Returns ''
</code></pre>

<p>Therefore all asserts on the $output are false.</p>

<p>Anybody has any idea on how to unit test Monolog Outputs in Symfony Commands in Symfony 4?</p>
",https://stackoverflow.com/questions/53435318/validate-command-monolog-output-in-symfony-4-unit-test,"['php', 'unit-testing', 'command', 'symfony4', 'monolog']",1261,TRUE,2,1
Invalid interval format exception in hsqldb but query works in Postgres,"<p>I'm running a query in postgresql. It works fine in psql but for the purpose of unit testing I created a inmemory HSQLDB and executed the same query in it. But ""Invalid interval format"" exception is thrown.Since I'm new to hsqldb so I cant figure out the root cause of the problem.</p>

<p><strong>QUERY:</strong></p>

<pre><code>INSERT INTO microbatch_redrive
SELECT mii.*,(to_char(CURRENT_TIMESTAMP ,'yyyy-mm-ddThh:mi:ss.msZ')) FROM
(SELECT * FROM
  ( SELECT mi.*,me.extractid FROM
    (SELECT * FROM microbatch_info WHERE
        ((numattempts&lt;= ${maxNumOfAttempts})
        AND (starttime&gt;= '${starttime}') 
        AND (starttime&lt;= '${endtime}')))
    AS mi LEFT OUTER JOIN microbatch_extract_info AS me ON mi.microbatchid = me.microbatchid) 
    AS mime WHERE((mime.raverunstatus='SUCCEEDED' AND mime.extractid is null)
    OR (mime.starttime &lt; to_char(CURRENT_TIMESTAMP,'yyyy-mm-ddThh:mi:ss.msZ') AND mime.raverunstatus='NOT_STARTED')
    OR (mime.raverunstatus = 'FAILED')
    OR (mime.raverunstatus='STARTED' AND mime.starttime&lt; (to_char(CURRENT_TIMESTAMP - INTERVAL '1 hour' * ${extractTimeIntervalInHour},'yyyy-mm-ddThh:mi:ss.msZ')))
    )
) AS mii LEFT OUTER JOIN
(SELECT microbatchid FROM microbatch_redrive WHERE raverunstatus='REDRIVE_SUCCEEDED') AS mr ON mii.microbatchid=mr.microbatchid WHERE mr.microbatchid IS NULL;
</code></pre>

<p><strong>ERROR:</strong></p>

<pre><code> Caused by: org.hsqldb.HsqlException: data exception: invalid interval format
[junit]     at org.hsqldb.error.Error.error(Unknown Source)
[junit]     at org.hsqldb.error.Error.error(Unknown Source)
[junit]     at org.hsqldb.types.IntervalType.getIntervalType(Unknown Source)
[junit]     at org.hsqldb.ParserBase.readIntervalType(Unknown Source)
[junit]     at org.hsqldb.ParserBase.readDateTimeIntervalLiteral(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadSimpleValueExpressionPrimary(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesValueExpressionPrimary(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesPrimary(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesFactor(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesTerm(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesCommonValueExpression(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.readExpression(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.readSQLFunction(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.readFunction(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.readColumnOrFunctionExpression(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadSimpleValueExpressionPrimary(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesValueExpressionPrimary(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesPrimary(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesFactor(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesTerm(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesCommonValueExpression(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadValueExpression(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadRowElementList(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesValueExpressionPrimary(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesPrimary(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesFactor(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesTerm(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesCommonValueExpression(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadRowOrCommonValueExpression(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadRowValuePredicand(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadPredicateRightPart(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesValueExpressionPrimary(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesPrimary(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesFactor(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesTerm(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesCommonValueExpression(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadValueExpression(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadRowElementList(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesValueExpressionPrimary(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesPrimary(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesFactor(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesTerm(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadAllTypesCommonValueExpression(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadBooleanPrimaryOrNull(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadBooleanTestOrNull(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadBooleanFactorOrNull(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadBooleanTermOrNull(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadBooleanValueExpression(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadBooleanPrimaryOrNull(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadBooleanTestOrNull(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadBooleanFactorOrNull(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadBooleanTermOrNull(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadBooleanValueExpression(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.readWhereGroupHaving(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadTableExpression(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadQuerySpecification(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadSimpleTable(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadQueryPrimary(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadQueryTerm(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadQueryExpressionBody(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadQueryExpression(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadSubqueryTableBody(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadSubqueryTableBody(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadTableSubqueryOrNull(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.readTableOrSubquery(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadTableReference(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadFromClause(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadTableExpression(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadQuerySpecification(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadSimpleTable(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadQueryPrimary(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadQueryTerm(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadQueryExpressionBody(Unknown Source)
[junit]     at org.hsqldb.ParserDQL.XreadQueryExpression(Unknown Source)
[junit]     at org.hsqldb.ParserDML.compileInsertStatement(Unknown Source)
[junit]     at org.hsqldb.ParserCommand.compilePart(Unknown Source)
[junit]     at org.hsqldb.ParserCommand.compileStatements(Unknown Source)
[junit]     at org.hsqldb.Session.executeDirectStatement(Unknown Source)
[junit]     at org.hsqldb.Session.execute(Unknown Source)
</code></pre>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/50735105/invalid-interval-format-exception-in-hsqldb-but-query-works-in-postgres,"['sql', 'hsqldb', 'intervals']",947,TRUE,2,1
Laravel phpUnit,"<p>When I run 
<code>phpunit</code> command it throws all info from phpunit help with PHPUnit 3.7.21 by Sebastian Bergmann. So I suggest it should work, but not yet;</p>

<p>when I run </p>

<pre><code>phpunit ExampleTest.php
PHP Fatal error:  Class 'Tests\TestCase' not found in C:\xampp7\htdocs\projects\heroes\tests\Feature\ExampleTest.php on line 8
</code></pre>

<p>In Laravel I've got 'tests' folder with</p>

<pre><code>TestCase.php
&lt;?php

namespace Tests;

use Illuminate\Foundation\Testing\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase
{
    use CreatesApplication;
}
</code></pre>

<p>folder 'Feature' with</p>

<pre><code>ExampleTest.php

&lt;?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;

class ExampleTest extends TestCase
{
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testBasicTest()
    {
        $response = $this-&gt;get('/');

        $response-&gt;assertStatus(200);
    }
}
</code></pre>

<p>and folder 'Unit' </p>

<p>In Laravel root folder I've got </p>

<pre><code>composer.json




  {
    ""name"": ""laravel/laravel"",
    ""description"": ""The Laravel Framework."",
    ""keywords"": [""framework"", ""laravel""],
    ""license"": ""MIT"",
    ""type"": ""project"",
    ""require"": {
        ""php"": ""^7.1.3"",
        ""fideloper/proxy"": ""^4.0"",
        ""laravel/framework"": ""5.6.*"",
        ""laravel/tinker"": ""^1.0"",
        ""laravelcollective/html"": ""^5.4.0"",
        ""laravelcollective/html"": ""~5.0""
    },
    ""require-dev"": {
        ""filp/whoops"": ""^2.0"",
        ""fzaninotto/faker"": ""^1.4"",
        ""mockery/mockery"": ""^1.0"",
        ""nunomaduro/collision"": ""^2.0"",
        ""phpunit/phpunit"": ""^7.0""
    },
    ""autoload"": {
        ""classmap"": [
            ""database/seeds"",
            ""database/factories""
        ],
        ""psr-4"": {
            ""App\\"": ""app/""
        }
    },
    ""autoload-dev"": {
        ""classmap"": [
            ""tests/TestCase.php""
        ],
        ""psr-4"": {
            ""Tests\\"": ""tests/""
        }
    },
    ""extra"": {
        ""laravel"": {
            ""dont-discover"": [
            ]
        }
    },
    ""scripts"": {
        ""post-root-package-install"": [
            ""@php -r \""file_exists('.env') || copy('.env.example', '.env');\""""
        ],
        ""post-create-project-cmd"": [
            ""@php artisan key:generate""
        ],
        ""post-autoload-dump"": [
            ""Illuminate\\Foundation\\ComposerScripts::postAutoloadDump"",
            ""@php artisan package:discover""
        ]
    },
    ""config"": {
        ""preferred-install"": ""dist"",
        ""sort-packages"": true,
        ""optimize-autoloader"": true
    },
    ""minimum-stability"": ""dev"",
    ""prefer-stable"": true
}
</code></pre>

<p>I just simply need to start unit testing</p>
",https://stackoverflow.com/questions/50197845/laravel-phpunit,"['php', 'laravel', 'unit-testing', 'composer-php']",1301,TRUE,2,4
npm test failed while testing react js application,"<p>Here, I am doing unit testing on some component in my reactjs application through enzyme.But after firing npm test command it gives an error and I don't know what is that error and how can solve it. Please help me to solve this error. Here, I attach test.js file and console output.</p>

<p><strong>NavigationItems.test.js:</strong></p>

<pre><code>import React from 'react';
import { configure, shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import NavigationItems from './NavigationItems';
import NavigationItem from './NavigationItem/NavigationItem';
configure({adapter: new Adapter()});
describe('&lt;NavigationItems /&gt;', () =&gt; {
let wrapper;
beforeEach(() =&gt; {
    wrapper = shallow(&lt;NavigationItems /&gt;);
});
it('should render two &lt;NavigationItem /&gt; elements if not authenticated', () =&gt; {        
    expect(wrapper.find(NavigationItem)).toHaveLength(2);
});
it('should render three &lt;NavigationItem /&gt; elements if authenticated', () =&gt; {
    //const wrapper = shallow(&lt;NavigationItems isAuthenticated /&gt;);
    wrapper.setProps({isAuthenticated: true});
    expect(wrapper.find(NavigationItem)).toHaveLength(3);
}); });
</code></pre>

<p><strong>Console Output:</strong></p>

<pre><code>abc-17@abc17-B250M-D2V:~/bb1$ npm test

&gt; burger-builder@0.1.0 test /home/abc-17/bb1
&gt; node scripts/test.js --env=jsdom

fs.js:1384
    throw error;
    ^

Error: watch /home/abc-17/bb1/node_modules/lodash.uniq ENOSPC
    at _errnoException (util.js:1022:11)
    at FSWatcher.start (fs.js:1382:19)
    at Object.fs.watch (fs.js:1408:11)
    at NodeWatcher.watchdir (/home/abc-17/bb1/node_modules/sane/src/node_watcher.js:150:20)
    at Walker.&lt;anonymous&gt; (/home/abc-17/bb1/node_modules/sane/src/node_watcher.js:374:12)
    at emitTwo (events.js:126:13)
    at Walker.emit (events.js:214:7)
    at /home/abc-17/bb1/node_modules/walker/lib/walker.js:69:16
    at go$readdir$cb (/home/abc-17/bb1/node_modules/graceful-fs/graceful-fs.js:149:14)
    at FSReqWrap.oncomplete (fs.js:135:15)
npm ERR! Test failed.  See above for more details.
</code></pre>
",https://stackoverflow.com/questions/52113195/npm-test-failed-while-testing-react-js-application,"['javascript', 'reactjs', 'testing', 'npm']",221,FALSE,0,0
How to unit test `viewDidLoad()`,"<p>What is everybody's favourite way of injecting dependencies when unit testing <code>UIViewController.viewDidLoad()</code> method on iOS?</p>

<p>Given my implementation is:</p>

<pre><code>class MyViewController: UIViewController {

    var service: Service = Service()

    override func viewDidLoad() {
        super.viewDidLoad()
        service.load()
    }
}
</code></pre>

<p>And my test class is something along this:</p>

<pre><code>class MyViewController Tests: XCTestCase {

     var vc: MyViewController!
     var serviceMock = ServiceMock()

    override func setUp() {
       super.setUp()
       let storyboard = UIStoryboard(name: ""Main"", bundle: nil)
       vc = storyboard.instantiateViewController(withIdentifier: ""MyViewController"") as! MyViewController
       vc.service = serviceMock
    }
}

func testThatServiceIsCalled() {

       XCTAssertTrue(serviceMock.loadCalled)
 }
</code></pre>

<p>The obvious problem here is that <code>viewDidLoad()</code> is called at the moment I instantiate the viewController and the test fails as the mock is not injected properly.</p>

<p>Any solution?</p>
",https://stackoverflow.com/questions/49100331/how-to-unit-test-viewdidload,"['ios', 'swift', 'dependency-injection', 'uiviewcontroller', 'xctest']",4102,TRUE,0,2
How can I unit test a function that validates a datetime is in a specific ISO format?,"<p>I'm new to unit testing and I would like some guidance on this topic. The function validates if a datetime is a string first and if so then validates if it is in the right ISO format.</p>

<pre><code>if not isinstance(timestamp,str):
    raise ValueError(""timestamp must be a string"")
try:
    datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S')
    return True
except ValueError:
    return True
</code></pre>

<p>How can I determine what to include in my unit test and what should I be on the lookout for?</p>
",https://stackoverflow.com/questions/51792216/how-can-i-unit-test-a-function-that-validates-a-datetime-is-in-a-specific-iso-fo,"['python', 'unit-testing', 'datetime']",373,TRUE,1,1
"Apparently, CLLocation objects cannot be archived / unarchived precisely","<p>In my app (only relevant code shown), I have a class <code>Test</code> with a property  </p>

<pre><code>var location: CLLocation  
</code></pre>

<p>I archive it using  </p>

<pre><code>public func encode(with aCoder: NSCoder) {
    aCoder.encode(location, forKey: ""location"")
}  
</code></pre>

<p>And it is unarchived using  </p>

<pre><code>required convenience public init?(coder aDecoder: NSCoder) {
    let unarchivedLocation = aDecoder.decodeObject(forKey: ""location"") as! CLLocation
    self.init(location: unarchivedLocation)
}  
</code></pre>

<p>Unit testing is done using  </p>

<pre><code>func test_archiningUnarchiving() {
    // given
    let location = CLLocation.init(latitude: 0.0, longitude: 0.0)
    let test = Test(location: location)
    // when
    let data = NSKeyedArchiver.archivedData(withRootObject: test)
    let unarchivedTest = NSKeyedUnarchiver.unarchiveObject(with: data) as? Test
    // then
    XCTAssertEqual(unarchivedTest!.location, location, ""location was not correctly unarchived"")
}  
</code></pre>

<p>This test fails:  </p>

<pre><code>XCTAssertEqual failed: (""&lt;+0.00000000,+0.00000000&gt; +/- 0.00m (speed -1.00 mps / course -1.00) @ 1/19/18, 3:30:50 PM Central European Standard Time"") is not equal to (""&lt;+0.00000000,+0.00000000&gt; +/- 0.00m (speed -1.00 mps / course -1.00) @ 1/19/18, 3:30:50 PM Central European Standard Time"") - location was not correctly unarchived
</code></pre>

<p>The log shows twice exactly the same data for the original and the unarchived location.<br>
Any idea what could have gone wrong anyway??</p>
",https://stackoverflow.com/questions/48343477/apparently-cllocation-objects-cannot-be-archived-unarchived-precisely,"['ios', 'unit-testing', 'cllocation', 'nskeyedarchiver', 'nskeyedunarchiver']",138,TRUE,0,1
"How to get css values of a dom element using Jest, Enzyme or any other unit testing library/framework?","<p>Is it possible to get any css value out of the DOM element being tested using Jest, Enzyme, Chai, etc.? From what I have seen so far, you can only get those css values that are mentioned in the code as style objects. But I'm not finding a way to get any other css value that the element can have in DOM.
For example, if in the code using style object you provide an element a width of 50%, in unit testing its not possible to get the actual pixel value of that percentage width value. Or if you have not even mentioned width, height, etc., can you extract the derived css values that the element receives after being mounted in the DOM?</p>

<p>My assumption is, because unit testing happens in a node environment simulating a DOM-like environment but not an actual browser, its not possible to get the actual DOM values in some cases.</p>
",https://stackoverflow.com/questions/49250366/how-to-get-css-values-of-a-dom-element-using-jest-enzyme-or-any-other-unit-test,"['unit-testing', 'enzyme', 'jestjs', 'chai-enzyme']",3105,TRUE,2,1
Dagger2 Injection Unit Tests is null,"<p>Hi i have used dagger for dependency injections of Network Module, ApplicationModule, DatabaseModule, Presenters and interactor in my app.
I want to use these same classes and Module during unit testing.</p>

<p>As unit testing reference, i have created AndroidTestAppComponent using following code:</p>

<pre><code>@Singleton
@Component(modules = {
        AndroidSupportInjectionModule.class,
        AndroidTestAppModule.class,
        NetworkModule.class
})
public interface AndroidTestAppComponent extends AndroidInjector&lt;AndroidTestApplication&gt; {
    @Component.Builder
    abstract class AndroidTestAppComponentBuilder extends Builder&lt;AndroidTestApplication&gt; {
    }
}
</code></pre>

<p>Giving all module is out of scope for this question, consider <code>AndroidTestAppModule.java below</code>:</p>

<pre><code>public class AndroidTestAppModule {
    @Provides
    @Singleton
    Context provideContext(AndroidTestApplication application) {
        return application.getApplicationContext();
    }

    @Singleton
    @Provides
    KeyguardManager provideKeyguardManager(Context context) {
        return (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
    }

    @Singleton
    @Provides
    FingerprintManagerCompat providerFingerPrintManager(Context context) {
        return FingerprintManagerCompat.from(context);
    }
}
</code></pre>

<p>I am able to generate <code>DaggerAndroidTestAppComponent</code>.
My Application class is as below:</p>

<pre><code>public class AndroidTestApplication extends DaggerApplication implements HasActivityInjector {
    @Inject
    DispatchingAndroidInjector&lt;Activity&gt; dispatchingActivityInjector;

    AndroidInjector&lt;AndroidTestApplication&gt; androidInjector;

    @Override
    public void onCreate() {
        super.onCreate();
        androidInjector.inject(this);
    }

    @Override
    protected AndroidInjector&lt;? extends DaggerApplication&gt; applicationInjector() {
        androidInjector = DaggerAndroidTestAppComponent.builder().create(this);
        return androidInjector;
    }

    @Override
    public DispatchingAndroidInjector&lt;Activity&gt; activityInjector() {
        return dispatchingActivityInjector;
    }
}
</code></pre>

<p>Some other <code>AppPref.java</code> class</p>

<pre><code>@Singleton
public class AppPref {

    private SharedPreferences preferences;

    @Inject
    AppPref(Context context) {
        preferences = context.getSharedPreferences(""somefile"", Activity.MODE_PRIVATE);
    }
}
</code></pre>

<p>As read from documentation: <code>AndroidInjection#inject(T t)</code> t here takes core android module, so when i call this in my Activity <code>AndroidInjection.inject(activity_reference_usually__this__)</code> it works(Normal scenario, real build and no testing app)</p>

<p>Without changing much code how can i use these Classes in AndroidInstrumentationTest, because i will only change test implementation in <code>Test**DaggerModules</code> inside test package.</p>

<p>Sample code for instrumentation is given below:</p>

<pre><code>@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {


    AndroidTestApplication application;

    @Inject
    AppPref appPref;


    @Before
    public void setUp() throws IllegalAccessException, InstantiationException, ClassNotFoundException {
        Context appContext = InstrumentationRegistry.getTargetContext();
        application = (AndroidTestApplication) Instrumentation.newApplication(AndroidTestApplication.class, appContext);
        DaggerAndroidTestAppComponent.builder().create(application).inject(application);
    }

    @Test
    public void useAppContext() {
        // Context of the app under test.
        Context appContext = InstrumentationRegistry.getTargetContext();

        assertEquals(""com.a.b"", appContext.getPackageName());
    }

    @Test
    public void testPreNotNUll() {
        Assert.assertNotNull(appPref);
    }

}
</code></pre>

<p>Ideally, apppref is alwyas null, becuase in <code>setUp</code> method i have injected AndroidTestApplication class and not in <code>ExampleInstrumentedTest</code> how can i edit my dagger2 code so that @Inject works fine and i get valid appPref object. 
Thank you.</p>
",https://stackoverflow.com/questions/53099513/dagger2-injection-unit-tests-is-null,"['android', 'dagger-2', 'android-instrumentation', 'dagger']",1622,TRUE,2,2
How to start Spring Boot app without depending on Pivotal GemFire cache,"<p>I have a Spring Boot app with a Pivotal GemFire <code>ClientCache</code> instance configured and its corresponding domain objects. I am also using Spring Boot Test for unit testing. For every test case execution, either through class or Maven build, Spring <code>ApplicationContext</code> fails to load if the GemFire cache is down.</p>

<p>How to start Spring Boot application without depending on GemFire cache?</p>
",https://stackoverflow.com/questions/51510520/how-to-start-spring-boot-app-without-depending-on-pivotal-gemfire-cache,"['java', 'spring', 'spring-boot', 'geode', 'spring-data-gemfire']",725,TRUE,1,2
How do i test for http status code 500 in sinon?,"<p>I have the following code in my main class in nodejs. </p>

<p>I am doing unit testing using sinon. </p>

<p>How do I test for this portion of the code 
<code>res.status(error.status || 500);</code></p>

<p>I am able to test the error.status portion by call an invalid url which leads to the error handling above, 404, but how do i get to the <code>500</code> flow?</p>

<p><strong>main.js:</strong></p>

<pre><code>...
//importing route
var routes = require('./api/rest/webservRest'); 

//register the route
routes(app); 

//reached here throw error 404, means no routes to handle inc. request
app.use((req, res, next) =&gt; {
    const error = new Error('Not found');
    error.status = 404;

    next(error);
});

// catch errors
app.use((error, req, res, next) =&gt; {

    log.error(""ERROR - "" + req.url + "" - "" + error.message);

    res.status(error.status || 500);
    res.json({
        error: {
            message: error.message
        }
    }); 
});

//start application
module.exports = app.listen(port, () =&gt; {
    log.info('Module - RESTful API server started on: ' + port);    
});
</code></pre>
",https://stackoverflow.com/questions/53295913/how-do-i-test-for-http-status-code-500-in-sinon,"['node.js', 'unit-testing', 'sinon']",562,FALSE,1,1
Mocking a tcp server using a PCAP file in python,"<p>I have python code that will connect to a server and continuously retrieve data for storing/setting. I used TCP dump to capture what normal traffic looks like and I want to mock this test server for unit testing. </p>

<p>Does anyone know how to mock a TCP server using a pcap file of normal traffic in python? </p>
",https://stackoverflow.com/questions/52393056/mocking-a-tcp-server-using-a-pcap-file-in-python,"['python', 'mocking', 'pcap']",243,FALSE,1,0
Boost 1.64 Unit Test compilation failure,"<p>I'm starting to go through the tutorial for boost unit testing presented <a href=""https://www.boost.org/doc/libs/1_54_0/libs/test/doc/html/tutorials/new-year-resolution.html"" rel=""nofollow noreferrer"">here</a>.</p>

<p>Using my initial code:</p>

<pre><code>#define BOOST_TEST_MODULE my_first test
#include &lt;boost/test/unit_test.hpp&gt;
</code></pre>

<p>when I compile it I receive the following error:</p>

<pre><code>Error   C2143   syntax error: missing ',' before '&lt;'    c:\boost_1_64_0\boost\test\utils\basic_cstring\compare.hpp
</code></pre>

<p>I've compiled boost myself and I'm using version 1.64 due to other dependency constraints. I'm also using Visual Studio 2017 Community.</p>

<p>How do I solve this problem please?</p>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/52905288/boost-1-64-unit-test-compilation-failure,"['c++', 'boost-unit-test-framework']",126,FALSE,1,1
Visual Studio code coverage for a referenced library,"<p><a href=""https://i.stack.imgur.com/77ZGn.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/77ZGn.png"" alt=""enter image description here""></a>In my solution there is library (Project) that I have built.</p>

<p>Then there is the project for unit testing. </p>

<p>When I run the code coverage, it only displays the Unit test libraries coverage. But I want to run the unit tests against the library and see the coverage of the library. </p>

<p>How can I do that? </p>

<p>Please see attached</p>
",https://stackoverflow.com/questions/50492099/visual-studio-code-coverage-for-a-referenced-library,"['c#', '.net']",155,FALSE,1,0
junit test : java.lang.ClassCastException,"<p>I am trying to implement junit testing with spring data jpa application. On controller level I am trying to implement unit testing. But I am getting Test failure class cast exception error. </p>

<p><strong>DepartmentController.java</strong></p>

<pre><code>@RestController
@RequestMapping(""/api.spacestudy.com/SpaceStudy/Control/SearchFilter"")
public class DepartmentController {

    @Autowired
    DepartmentService depService;

    @CrossOrigin(origins = ""*"")
    @GetMapping(""/loadDepartments"")
    public ResponseEntity&lt;Set&lt;Department&gt;&gt; findDepName() {

        Set&lt;Department&gt; depname = depService.findDepName();
        return ResponseEntity.ok(depname);
    }
}
</code></pre>

<p><strong>Junit test class</strong></p>

<pre><code>@RunWith(SpringRunner.class)
@WebMvcTest(DepartmentController.class)
public class SpaceStudyControlSearchFilterApplicationTests {

    @Autowired
    DepartmentController depController;

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    DepartmentService depService;

    @SuppressWarnings(""unchecked"")
    Set&lt;Department&gt; mockDepartment = (Set&lt;Department&gt;) new Department(21629, ""170330"", ""Administrative Computer"");


    @Test
    public void findDepNameTest() throws Exception {

        Mockito.when(depService.findDepName()).thenReturn( mockDepartment);
        RequestBuilder requestBuilder = MockMvcRequestBuilders.get(
                ""/api.spacestudy.com/SpaceStudy/Control/SearchFilter/loadDepartments"").accept(
                MediaType.APPLICATION_JSON);
        MvcResult result = mockMvc.perform(requestBuilder).andReturn();

        System.out.println(result.getResponse());
        String expected = ""{nDeptId: 21629}"";

        JSONAssert.assertEquals(expected, result.getResponse().getContentAsString(), false);

    }
}
</code></pre>

<p><strong>Junit failure</strong></p>

<pre><code>java.lang.ClassCastException: com.spacestudy.model.Department cannot be cast to java.util.Set
    at com.spacestudy.SpaceStudyControlSearchFilterApplicationTests.&lt;init&gt;(SpaceStudyControlSearchFilterApplicationTests.java:39)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
</code></pre>

<p>I am new to junit testing. Can any one tell me what I am doing wrong in test?</p>
",https://stackoverflow.com/questions/49704055/junit-test-java-lang-classcastexception,"['unit-testing', 'junit', 'spring-data-jpa']",2718,TRUE,1,1
Best way to unit test promisified functions with Tape JS?,"<p>I'm writing unit tests for promisified code. What's the ""right"" way to go about unit testing async code like this? It seems like using timeouts and waiting some arbitrary amount of time for calls to go through is a bad idea for robust testing.</p>

<p>Below is some example code for the functions I want to write tests for. 
Thanks!</p>

<pre><code>function getAllItems(){
return createRequest(URLS[""a""],{}, itemsCB);
}

function itemsCB(response){
var items = JSON.parse(response).objects;
Items.append(items);
}

function createRequest(url, body, callback){
var XMLHttpRequest = require(""xmlhttprequest"").XMLHttpRequest;
return new Promise(function(resolve, reject) {
    var xhr = new XMLHttpRequest();
    xhr.onload = function(){
        if(xhr.status == 200){
            if(callback != null){
                callback(xhr.responseText);
            }
            resolve(xhr.responseText);
        }
        else{
            reject(xhr.statusText);
        }
    }
    xhr.onerror = function() {
        reject(Error(""Network Error""));
    };

    xhr.open(""GET"", url);
    xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
    xhr.send('');
});
</code></pre>

<p>}</p>
",https://stackoverflow.com/questions/48084388/best-way-to-unit-test-promisified-functions-with-tape-js,"['javascript', 'unit-testing', 'asynchronous', 'testing']",82,FALSE,1,0
c++/catch2: reference code from seperate test dir,"<p>Before trying to do any unit testing, I had a directory like</p>

<pre><code>mything.h
mything.cpp
mything2.h
mything2.cpp
driver.cpp  // contains main()
Makefile
</code></pre>

<p>Then I would <code>make</code> and run the produced executable; this executable was produced in the root directory (call it <code>runme</code>).  </p>

<p>Now I'm trying to use Catch2 <a href=""https://github.com/catchorg/Catch2/blob/master/docs/Readme.md#top"" rel=""nofollow noreferrer"">https://github.com/catchorg/Catch2/blob/master/docs/Readme.md#top</a>) which also says to have one testing file with a main (they have a define for it). So I reorganized my code as </p>

<pre><code>src/
  mything.h
  mything.cpp
  mything2.h
  mything2.cpp
  driver.cpp  // contains main()
test/
  catch2.hpp // downloaded off their website in single header option
  sometest.cpp // also contains a main per catch2
Makefile
</code></pre>

<p>I made some dummy tests that don't reference my actual code. Now I do <code>make tester</code> and <code>./tester</code> which runs all the tests. And I can do <code>make</code> and <code>./runme</code> to run my original application. </p>

<p>My question now is, how do I actually call my source code from the test code? Do I need to convert this <code>src</code> dir into a library? That is, how test code references src code in c++ is a bit unclear to me. </p>

<p>For full disclosure, I'm coming from the python/pytest world, and wondering how you actually structure c++ code w.r.t. unit testing or proper project structure. </p>
",https://stackoverflow.com/questions/52615327/c-catch2-reference-code-from-seperate-test-dir,"['c++', 'catch2']",771,FALSE,2,0
how to test private function using mocha?,"<p>As i am new to unit testing , I want to  test my javascript code  its very confusing .. i really want some ones help who could tell the solution for my problem .??</p>

<pre class=""lang-js prettyprint-override""><code>if (!Notification) {
 Notification = {};
  else {
    if (typeof Notification != ""object"") {
      throw new Error("" already exists "");
    }
  }
 Notification.admin = function() {
    var res = {};
    var prevent = """";

    var DefaultValue = function(ans, type, commnon, status) {
      var notify = type.concat(common);
      if ($(""#method"").val() == ""false"" &amp;&amp; type == ""Text"") {
        if (status) {
          return data = '&lt;label class=""checkbox-label""&gt;&lt;input data-role=""ux-checkbox"" type=""checkbox"" disabled=""disabled"" data-type=""' + notify + '"" class=""grid-checkbox""&gt;&amp;nbsp;&amp;nbsp&lt;/label&gt;';
        } else {
          return data = '&lt;label class=""checkbox-label""&gt;' + '&lt;span class=""no-checkbox-label"" &gt;' + ""-"" + '&lt;/span&gt;' + '&lt;/label&gt;';
        }
      } else if (status) {
        if (ans) {
          return data = '&lt;label class=""checkbox-label""&gt;&lt;input data-role=""ux-checkbox"" checked=checked type=""checkbox"" data-type=""' + notify + '"" class=""grid-checkbox ""&gt;&amp;nbsp;&amp;nbsp&lt;/label&gt;';
        } else {
          return data = '&lt;label class=""checkbox-label""&gt;&lt;input data-role=""ux-checkbox"" type=""checkbox"" data-type=""' + notify + '"" class=""grid-checkbox""&gt;&amp;nbsp;&amp;nbsp&lt;/label&gt;';
        }
      } else {
        return data = '&lt;label class=""checkbox-label""&gt;' + '&lt;span class=""no-checkbox-label"" &gt;' + ""-"" + '&lt;/span&gt;' + '&lt;/label&gt;';
      }
    };
    this.init = function() {


    };}; Notification.Obj = new Notification.admin();

  $(document).ready(function() {

Notification.Obj.init();

  });
</code></pre>

<p>This is my  private function which i want to unit test as i am using mocha and chai .. </p>

<p>i am not able to unit test this function</p>
",https://stackoverflow.com/questions/50095556/how-to-test-private-function-using-mocha,"['javascript', 'jquery', 'unit-testing', 'mocha.js', 'chai']",1313,TRUE,1,1
How to test class method using rspec,"<p>Hi i am working on RoR project with ruby-2.5.0 and rails 5.0. I have a model forgot_password where a class method is defined to create a record as follows:-</p>

<pre><code>forgot_password.rb
# frozen_string_literal: true

class ForgotPassword &lt; ApplicationRecord
  before_create :create_token

  def self.create_record
    self.create!(expiry: Time.zone.now +
                 ENV['VALIDITY_PERIOD'].to_i.hours)
  end

  private

  def create_token
    self.token = SecureRandom.urlsafe_base64(nil, false)
  end
end
</code></pre>

<p>I want to write unit testing for it using stub or factory_girl gem.</p>

<pre><code>spec/models/forgot_password_spec.rb
# frozen_string_literal: true

require 'rails_helper'

describe ForgotPassword do
  let(:forgot_password) do
    described_class.new()
  end

  describe 'create_record' do
    context 'with forgot_password class' do
      subject { forgot_password.create_record.class }

      it { is_expected.to eq ForgotPassword }
    end
  end
end
</code></pre>

<p>But its throwing error <code>undefined method create_record for #&lt;ForgotPassword:0x000000000622bc98&gt;</code> Please help me how can i test my model. Thanks in advance.</p>
",https://stackoverflow.com/questions/49538966/how-to-test-class-method-using-rspec,"['ruby-on-rails', 'unit-testing', 'rspec']",3229,TRUE,1,2
Proper way to test POST method in Spring MVC Controller,"<p>I've got simple app based on SpringMVC and Hibernate, trying to test a <code>POST</code> method which saves a Customer <code>Customer.class</code> to the database. Don't want to test database yet, only simple unit testing. Got the test green, but feel is still not enough, how can I refactor it to make it as it supposed to be?</p>

<p>CustomerController.class:</p>

<pre><code>@Controller
@RequestMapping(""/customer"")
public class CustomerController {

  @Autowired
    private CustomerService customerService;

  @PostMapping(""/saveCustomer"")
    public String saveCustomer(@ModelAttribute(""customer"") Customer theCustomer) {
        customerService.saveCustomer(theCustomer);

        return ""redirect:/customer/list"";
    }}
</code></pre>

<p>CustomerServiceImpl.class:</p>

<pre><code>@Service
public class CustomerServiceImpl implements CustomerService {
  @Override
  @Transactional
    public void saveCustomer(Customer theCustomer) {
        customerDAO.saveCustomer(theCustomer);
    }
}
</code></pre>

<p>CustomerDAOImpl.class:</p>

<pre><code>@Repository
public class CustomerDAOImpl implements CustomerDAO {
  @Override
    public void saveCustomer(Customer theCustomer) {

        Session currentSession = sessionFactory.getCurrentSession();

        currentSession.saveOrUpdate(theCustomer);

    }
}
</code></pre>

<p>CustomerControllerTest.class:</p>

<pre><code>public class CustomerControllerTest {


@InjectMocks
CustomerController controller;

@Mock
CustomerService mockCustomerService;

@Mock
View mockView;


MockMvc mockMvc;

@Before
public void setUp() throws Exception {

    MockitoAnnotations.initMocks(this);

    mockMvc = MockMvcBuilders.standaloneSetup(controller)
            .setSingleView(mockView)
            .build();
}
     @Test
        public void testSaveCustomer() throws Exception {

        mockMvc.perform(post(""/customer/saveCustomer""))
                .andExpect(status().isOk())
                .andExpect(view().name(""redirect:/customer/list""));

    }}
</code></pre>
",https://stackoverflow.com/questions/48963706/proper-way-to-test-post-method-in-spring-mvc-controller,"['java', 'unit-testing', 'model-view-controller', 'junit', 'mockito']",1643,FALSE,1,1
Enzyme/Jest Testing Error - Invariant Violation: Target container is not a DOM element,"<p>I'm new to doing unit testing and I keep getting the error: Invariant Violation: Target container is not a DOM element. I think it has to do with the way my app.js is structured because it keeps referencing this line ReactDOM.render(, document.getElementById('app'));.  Here's how it's structured now:</p>

<pre><code>import React from 'react';
import ReactDOM from 'react-dom';
import HomePage from './HomePage';

class App extends React.Component {
  render() {
    return (

      &lt;div&gt;
        &lt;HomePage /&gt;
      &lt;/div&gt;
    )
  }
}

ReactDOM.render(&lt;App /&gt;, document.getElementById('app'));
</code></pre>

<p>Does this need to be restructured for testing purposes? </p>
",https://stackoverflow.com/questions/48860492/enzyme-jest-testing-error-invariant-violation-target-container-is-not-a-dom-e,"['javascript', 'reactjs', 'testing', 'enzyme', 'jestjs']",1108,TRUE,1,1
XUnit InlineData with Objects?,"<p>Recently we have been trying Unit Testing in a new project, now that we want to pass a Object to our test method with <code>[InlineData]</code>, so we can utilize the same test method multiple times with multiple different data inputs.</p>

<p><code>[ClassData]</code> and <code>[MemberData]</code> are also available, but do not seem to offer a solution, as to my understanding.</p>

<p>Basically, is there a way to pass Objects with XUnit, like so:</p>

<pre><code>[Theory]
[InlineData(new Object { Attribute = 1 })]
public void Test(Object obj) 
{
    // Assert
    Xunit.Assert.NotNull(obj.Attribute);
}
</code></pre>

<p>Or is this not the correct convention or usage?</p>

<p>Passing <code>int</code>'s and <code>string</code>'s works fine using <code>[InlineData]</code></p>
",https://stackoverflow.com/questions/51540009/xunit-inlinedata-with-objects,"['c#', 'asp.net-mvc', 'unit-testing', 'xunit.net']",19447,FALSE,19,0
Sinon js AssertError: expected stub to be called once but was called 0 times,"<p>I have been learning Sinon JS for unit testing, and I am trying to get this example code working.  I have a simple ""external"" library created: </p>

<pre><code>class MyLib {

   simpleMethod () {
      return 'some response';
   }

   static handler() {
      const myLib = new MyLib();
      myLib.simpleMethod();
   }
}

module.exports = MyLib;
</code></pre>

<p>Then, I have a simple test suite: </p>

<pre><code>const chai = require('chai');
const sinon = require('sinon');
const MyLib = require('./my-lib');

describe ('sinon example tests', () =&gt; {

  it ('should call simpleMethod once', () =&gt; {
     let stubInstance = sinon.stub(MyLib, 'simpleMethod');

     MyLib.handler();

     sinon.assert.calledOnce(stubInstance);
  });

});
</code></pre>

<p>But I am returned with the error ""AssertError: expected stub to be called once but was called 0 times"".  I know this is probably obvious, but why is <code>simpleMethod</code> not being called?</p>
",https://stackoverflow.com/questions/50690733/sinon-js-asserterror-expected-stub-to-be-called-once-but-was-called-0-times,"['javascript', 'node.js', 'unit-testing', 'sinon', 'sinon-chai']",7335,TRUE,6,1
JUnit &amp; Mockito,"<p>can you guys give me a quick, straight to the point explanation of JUnit and Mockito unit testing? I've been searching and it's not have been clear to me.</p>

<p>Also, what kind of unit tests can i make for a Rest server and client?</p>

<p>Here is my rest server code for example:</p>

<pre><code>@JsonIgnoreProperties(ignoreUnknown = true)
</code></pre>

<p>@Path(""/calculator"")
public class RESTServer {</p>

<pre><code>private final Logger log = LoggerFactory.getLogger(RESTServer.class);

private ObjectMapper mapper = new ObjectMapper();

/**
 * Function that converts a String parameter into a Request object
 * @param json is the String of the request received from the client
 * @return return an Request object with all the fields containning data from the json String
 * @throws IOException
 */

private Request convertToObj(final String json) throws IOException {

    final Request request;
    log.debug(""Processing request: {}"", json);

    request = mapper.readValue(json, Request.class);

    return request;
}

/**
 * Function that converts a Answer object into a JSON String where all the data is written in conformity with JSON conventions
 * @param answerObject is the object with all the data about the answer to retrieve to the client
 * @param json is the String that contains the request, only for logging purposes
 * @return return a JSON String with all the data contained in the object
 * @throws JsonProcessingException
 */

private String convertToJson(final Answer answerObject, final String json) throws JsonProcessingException {
    String answer;

    answer = mapper.writeValueAsString(answerObject);

    log.debug(""Retrieving answer {} for request: {}"", answer, json);

    return answer;
}

/**
 * Function that calculates the result of the operation specified in the request from the client
 * @param request is the Request object that contains all the data from the client request
 * @return return the value resultant from the operation made
 */

public double calculator(final Request request){

    log.debug(""Processing number: {} and number: {}  with operation: {}"", request.getValue1(), request.getValue2(), request.getOperation());

    Calculate calculate = (value1, value2, operation) -&gt; {

        if (operation.compareToIgnoreCase(""add"") == 0) return value1 + value2;
        else if (operation.compareToIgnoreCase(""mult"") == 0) return value1 * value2;
        else if (operation.compareToIgnoreCase(""div"") == 0) return value1 / value2;
        else if (operation.compareToIgnoreCase(""avg"") == 0) return (value1 + value2)/2;
        else return 0;
    };

    return calculate.obtainResult(request.getValue1(),request.getValue2(),request.getOperation());
}

private interface Calculate{
    double obtainResult(double value1, double value2, String operation);
}

/**
 *Function that builds the answer to send to the client, merge the result of the calculation of the operation, the date and hour of the operation and the operation made
 * @param operation is the operation made
 * @param result is the result of the operation
 * @return returns a Answer object that contains all the data referent to the treatment of the request from the client
 */

private static Answer buildAnswer(final String operation, final double result){

    String date;
    Answer answerObject;

    date = new SimpleDateFormat(""dd/MM/yyyy HH:mm:ss"").format(new Date());

    answerObject = new Answer(operation, result, date);

    return answerObject;
}

@POST
@Path(""/calc"")
@Produces(MediaType.APPLICATION_JSON)
public Response postRequest(final String json) throws IOException {

    final double result;
    final String answer;
    final Request request;
    final Answer answerObject;

    request = convertToObj(json);

    result = calculator(request);

    answerObject = buildAnswer(request.getOperation(),result);

    answer = convertToJson(answerObject, json);

    return Response.status(Response.Status.OK).entity(answer).build();
}
</code></pre>

<p>}</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/52556873/junit-mockito,"['junit', 'mockito']",46,FALSE,0,0
&quot;Moment cannot be found by angular-moment&quot; when trying to test with karma &amp; jasmine - AngularJS,"<p><strong>My app runs correctly and the AngularMoment works perfectly with MomentJS.</strong></p>

<p>Lately I tried to implement <strong>unit-testing</strong> into my app on <code>grunt watch</code>, using Karma and Jasmine. All the modules seem to load fine, but only the <code>moment</code> can not be found by <code>angular-moment</code>. <em>(error message below):</em></p>

<pre><code>Error during loading: Uncaught Error: Moment cannot be found by 
angular-moment! Please reference to: https://github.com/urish/angular- 
moment in js/libs/angular-moment.js line 27
</code></pre>

<p>All the dependencies are loaded into the <code>karma.config.js</code> and still it doesn't work.</p>
",https://stackoverflow.com/questions/51265253/moment-cannot-be-found-by-angular-moment-when-trying-to-test-with-karma-jasm,"['angularjs', 'gruntjs', 'momentjs', 'karma-jasmine', 'angular-moment']",628,TRUE,0,1
how to stubbing nested promise in JS,"<p>hi StackOverflow community
im having problems stub this piece of code for unit testing
it is a nested promise call to mongo to create user then retrieve the user from database </p>

<p><code>return database.collection('users').insertOne(request.body)
        .then(response =&gt; database.collection('users')
        .find({_id:response.insertedId })
            .limit(1)
            .next());</code></p>

<p>can you please tell tell me the best way of going about this 
is it best i separate calls into their own functions or... </p>

<p>thanks</p>
",https://stackoverflow.com/questions/53496554/how-to-stubbing-nested-promise-in-js,"['node.js', 'mongodb', 'promise', 'mocking', 'stub']",130,FALSE,0,2
How to access an element in react native which is loaded when a certain state of the component is true?,"<p>I am using jest for unit testing in React native. A part of my UI inside a component is loaded only when a particular state of the component (noRecord) is true.
Here is the code snippet:</p>

<pre><code>{this.state.noRecord ? 
&lt;View&gt;
&lt;TouchableOpacity id=""navEnqtrn"" onPress={() =&gt; this.navEnqtrn()}&gt;
&lt;Text style={styles.courseEnquiry}&gt; Learning enquiry &lt;/Text&gt;
&lt;/TouchableOpacity&gt;
&lt;View&gt; : &lt;View&gt; &lt;Text&gt;Some other view here..&lt;/Text&gt;&lt;/View&gt;
}
</code></pre>

<p>Here is my unit test case:</p>

<pre><code>it('checks navEnqtrn' , () =&gt; {
const wrapper = shallow(&lt;Online navigation = {navigation}/&gt;);
wrapper.state.noRecord = true;
const instance = wrapper.instance();
const navEnqtrnSpy = jest.spyOn(instance,""navEnqtrn"");
wrapper.find('#navEnqtrn').simulate('press');
expect(navEnqtrnSpy).toBeCalled();
});
</code></pre>

<p>I am getting the following error:</p>

<pre><code>Method “simulate” is only meant to be run on a single node. 0 found instead.

  at ShallowWrapper.single (node_modules/enzyme/build/ShallowWrapper.js:1618:17)
  at ShallowWrapper.simulate (node_modules/enzyme/build/ShallowWrapper.js:929:21)
  at Object.&lt;anonymous&gt; (__tests__/online-test.js:100:28)
  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
  at flush (node_modules/asap/raw.js:50:29)
  at _combinedTickCallback (internal/process/next_tick.js:131:7)
  at process._tickCallback (internal/process/next_tick.js:180:9)
</code></pre>

<p>How do I simulate the press event in this case?</p>
",https://stackoverflow.com/questions/50578915/how-to-access-an-element-in-react-native-which-is-loaded-when-a-certain-state-of,"['javascript', 'react-native', 'jestjs', 'enzyme']",162,FALSE,0,1
CPPUnit ASSERT for C function which returns multiple parameters,"<p>I have to use CPPUnit in my project which includes both C++ and C codes. How do I CPPUNIT_ASSERT the following function for unit testing:</p>

<pre><code>void readData(char* locationOfData,int* sizeT, int* sizeW,double* values);
</code></pre>

<p>INPUT: locationOfData - path to data file</p>

<p>OUTPUTS: sizeT, sizeW, values(array)</p>

<p>For simple functions like finding minimum of three numbers, we can use:</p>

<pre><code>CPPUNIT_ASSERT(1==minValue(2,3,1));
</code></pre>

<p>How do I unit test the function readData above?</p>
",https://stackoverflow.com/questions/50794823/cppunit-assert-for-c-function-which-returns-multiple-parameters,"['c++', 'c', 'unit-testing', 'assert', 'cppunit']",228,FALSE,0,0
How do I unit test the scheduled logics?,"<p>This question is regarding unit testing the scheduled methods.</p>

<p>I am using <code>FluentScheduler</code> to achieve the scheduled job execution.</p>

<p>Here is my <code>Execute</code> method</p>

<pre><code>public void Execute()
{
   var provisioningRepo = _containerFactory.GetInstance&lt;IProvisioningRepo&gt;();
   var discounts = provisioningRepo.GetDiscounts();
   if (discounts.Count == 0)
     return;

   foreach (var discount in discounts)
   {
       //doing some logics
   }    
}
</code></pre>

<p>Here is my `app.config' entry for scheduler. </p>

<pre><code>      &lt;add key=""myMinitueSchedule"" value=""60"" /&gt;
</code></pre>

<p>Question 1: How do I test method executed at right time? that is every 60 seconds?</p>

<p>Question 2: Logic inside execute need to be tested independent to scheduler?</p>
",https://stackoverflow.com/questions/51471581/how-do-i-unit-test-the-scheduled-logics,"['c#', 'unit-testing', 'integration-testing', 'fluentscheduler']",569,TRUE,0,1
How do I mock a function being used by my React Component in Jest testing?,"<p>So I have something like the following:</p>

<pre><code>function calculate = (value) =&gt; { return value + somecalculations }

class MyComponent extends React.Component {

   ...

   render() {
       if (calcuate(this.props.value) === 1) {
          return(&lt;MyComponentVersion1 /&gt;)
       } else {
          return &lt;MyComponentVersion2 /&gt;
       }
   }
}
</code></pre>

<p>My question is, when doing jest unit testing, I want to be able to mock the function calculate().   But the function is global to that file, and is not part of my react component.  Is there a way to mock this function so it always returns say 1?  Thanks</p>
",https://stackoverflow.com/questions/53601770/how-do-i-mock-a-function-being-used-by-my-react-component-in-jest-testing,"['reactjs', 'jestjs']",155,TRUE,0,2
Regarding the #include preprocessor directive for vector cast environment,"<p>As per my code in filename.c, </p>

<pre><code>#include ""FOUNDATION/FOUNDATION.h""
</code></pre>

<p>Actually I have to run the vector cast (unit testing tool) for the filename.c.
so since the ""FOUNDATION.h"" is not present in the corresponding path mentioned,
vector cast compilation provides the error like no such file/directory.<br>
can we replace </p>

<pre><code>#include ""FOUNDATION/FOUNDATION.h""
</code></pre>

<p>with my specified path where actually the ""FOUNDATION.h"" is present.</p>
",https://stackoverflow.com/questions/52620530/regarding-the-include-preprocessor-directive-for-vector-cast-environment,"['unit-testing', 'vector', 'c-preprocessor']",739,FALSE,0,0
"How to test my jQuery plugin with Gulp, Jasmine and NodeJS?","<p>I created a <a href=""https://github.com/yegor256/colorizejs/blob/master/gulpfile.js"" rel=""nofollow noreferrer"">simple jQuery plugin</a>, which modifies the HTML according to some simple rules, using jQuery. Now I need to test that it works. I use Gulp for build automation. I decided to use Jasmine for unit testing. My question is how do I run my plugin from the <code>test.js</code> and validate the result? I have node.js installed at the build server.</p>
",https://stackoverflow.com/questions/51809750/how-to-test-my-jquery-plugin-with-gulp-jasmine-and-nodejs,"['jquery', 'gulp', 'jasmine']",1139,TRUE,3,3
MobileFirst Adapters and Unit Test,"<p>IBM MobileFirst offers out of the box the possibility to invoke REST Services by server components written in plain Javascript, so called 'Adapters'. Since my app contains a lot of business logic inside them, I  need to test it by Unit Test. 
Could somebody suggest me a good framework how to create Unit Testing for 'server side' Javascript ? 
Thanks.</p>
",https://stackoverflow.com/questions/51031537/mobilefirst-adapters-and-unit-test,"['unit-testing', 'ibm-mobilefirst']",64,TRUE,0,1
How to achieve asynchronous task dependency with XCTestCases?,"<p>I am writing some test cases for asynchronous operations where I have two operations on which unit test need to be performed.</p>

<p>Suppose I have some login webservice that need to called and on response of that another profile webservice should be called.</p>

<p>Is it possible to test above scenario using unit-testing in iOS?</p>

<p>Thank you in advance.</p>
",https://stackoverflow.com/questions/48824961/how-to-achieve-asynchronous-task-dependency-with-xctestcases,"['swift', 'xcode', 'xctestcase']",99,TRUE,0,2
Assert sorted array of objects,"<p>I'm doing unit testing using javascript testing framework (mocha, chai, etc). How can I assert my array of objects using its name?</p>

<p>I can successfully sort this using localeCompare but I'm not getting what I wanted on my test. It just returns <code>1</code> or <code>-1</code>.</p>

<p>Here's my a sample of what I want to sort.</p>

<pre><code>var Stuffs = [
     { name: ""PWE"", address: ""1234567890"" },
     { name: ""NSA"", address: ""1234567890"" },
     { name: ""AVE"", address: ""1234567890"" },
     { name: ""QRE"", address: ""1234567890"" },
  ]
</code></pre>

<p>How can I assert this to <code>[""AVE"", ""NSA"", ""PWE"", ""QRE""]</code> ?</p>
",https://stackoverflow.com/questions/50273621/assert-sorted-array-of-objects,"['javascript', 'sorting', 'chai', 'assertions', 'karma-mocha']",1978,TRUE,0,4
How to get unit tests in Vue to stop going up the import hierarchy,"<p>I'm just starting out with unit testing in Vue, and have already hit a roadblock on my first component. </p>

<p>This is my test:</p>

<pre><code>import { shallowMount } from '@vue/test-utils';
import GeoframeLibrary from '@/views/GeoframeLibrary.vue';

describe('GeoframeLibrary', () =&gt; {
  const wrapper = shallowMount(GeoframeLibrary);

  it('renders', () =&gt; {
    expect(wrapper.element).toMatchSnapshot();
  });
});
</code></pre>

<p>The problem is that <code>GeoframeLibrary.vue</code> imports a file, which imports another file, which imports my Vuex store init, and then:</p>

<pre><code> FAIL  tests/unit/GeoframeLibrary.spec.ts
  ● Test suite failed to run

    TypeError: Cannot read property 'use' of undefined

       8 | import { AuthState } from './modules/auth';
       9 | 
    &gt; 10 | Vue.use(Vuex);
         |     ^
      11 | 
      12 | const vuexPersist = new VuexPersistence({
      13 |   key: 'onspot',

      at Object.&lt;anonymous&gt; (src/store/index.ts:10:5)
      at Object.&lt;anonymous&gt; (src/adonis-api/api-call.ts:7:1)
      at Object.&lt;anonymous&gt; (src/adonis-api/auth.ts:1:1)
      at Object.&lt;anonymous&gt; (src/adonis-api/index.ts:1:1)
      at src/views/GeoframeLibrary.vue:55:1
      at Object.&lt;anonymous&gt; (src/views/GeoframeLibrary.vue:66:3)
      at Object.&lt;anonymous&gt; (tests/unit/GeoframeLibrary.spec.ts:3:1)
</code></pre>

<p>Most of the Vue unit testing tutorials out there are overly simplistic and don't cover these real-world scenarios. I need my component to import other code to carry out specialized routines. How do I fix this and get my test to either <em>not</em> follow imports, or somehow just mock <code>Vue.use</code> to do absolutely nothing? Vuex is actually not part of my component at all, it just happens to show up in the error because it's being imported.</p>

<p>EDIT: It is indeed a strange edge case. Here's the reproduction repo:
<a href=""https://github.com/ffxsam/repro-jest-importing"" rel=""nofollow noreferrer"">https://github.com/ffxsam/repro-jest-importing</a></p>

<p>If you comment out line 17 in <code>src/adonis-api/crud-factory.ts</code>, the test runs fine. <em>Very</em> strange. Oh, and if you comment out line 8 in <code>src/adonis-api/api-call.ts</code>, it also fixes the test.</p>
",https://stackoverflow.com/questions/51661909/how-to-get-unit-tests-in-vue-to-stop-going-up-the-import-hierarchy,"['unit-testing', 'vue.js', 'jestjs']",242,FALSE,0,1
Testcafe wont recognise React,"<p>I'm trying to run my first testcafe test but it's proving arduous. </p>

<blockquote>
  <p>testcafe -e chrome client/routes/Lookup/components/testcafe/lookup-test.js</p>
</blockquote>

<pre><code>SyntaxError: client/routes/Lookup/components/Lookup.js: Unexpected token (60:8)
  58 |     if (error.status &amp;&amp; error.status !== 404) {
  59 |       return (
&gt; 60 |         &lt;NetworkIssues code={error.status} /&gt;
     |         ^
  61 |       );
  62 |     }
  63 |
at Object.&lt;anonymous&gt; (client/routes/Lookup/components/testcafe/lookup-test.js:1:1)
</code></pre>

<p>lookup-test.js </p>

<pre><code>import Lookup from '../Lookup';
import React from 'react';
import { waitForReact } from 'testcafe-react-selectors';


fixture('Lookup Component').page('http://localhost:3000/web/lookup').beforeEach(async () =&gt; {
  await waitForReact();
});

test('foo', async (x) =&gt; {
  await x
    .typeText('customerName', '07450118811')
    .expect('customerName.value').contains('07450118811');
});
</code></pre>

<p>My code doesn't have any errors. It compiles and works fine and passes all my jest and enzyme unit testing. But I can't find any guidance online for this. As you can see the ignore errors flag is used to no avail.</p>

<p>Cheers.</p>
",https://stackoverflow.com/questions/51859863/testcafe-wont-recognise-react,"['javascript', 'reactjs', 'automated-tests', 'e2e-testing', 'testcafe']",1145,TRUE,5,3
Mock interface method so that all classes that implement that interface use that implementation,"<p>I have an interface that is implemented in multiple classes. That interface has a method which returns a bool and I'm trying to mock that method so that it always returns true for unit testing purposes.</p>

<p>Example:</p>

<pre><code>public interface IBase
{
}

public interface IParent
{
    bool IsValid(int number);
    ChildTypeEnum Type { get; }
}

public class A: IBase, IParent
{
    public bool IsValid(int number){...}
    ChildTypeEnum Type { get { return ...; } }
    //other methods
}

public class B: IBase, IParent
{
    public bool IsValid(int number){...}
    ChildTypeEnum Type { get { return ...; } }
    //other methods
}

public class C: IBase, IParent
{
    public bool IsValid(int number){...}
    ChildTypeEnum Type { get { return ...; } }
    //other methods
}

public class D: IBase
{
    //other methods
}
</code></pre>

<p>Is there any way to mock the IParent.IsValid() method so that I can invoke the mocked method when trying to test the ChildsEngine.ValidateParent() method?</p>

<pre><code>public class ChildsEngine 
{
    private readonly IChildsLoader childsLoader;

    //Constructor for mocking
    public ScheduleRulesEngine(IChildsLoader childsLoader)
    {
        this.childsLoader = childsLoader;
    }


    public ParentValidation ValidateParent(int number, List&lt;ChildTypeEnum&gt; filterChilds = null)
    {
        var invalidChilds = new List&lt;ChildTypeEnum&gt;();

        var childs = childsLoader.Childs.OfType&lt;IParent&gt;();

        if (filterChilds != null)
            childs = childs.Where(x =&gt; filterChilds .Contains(x.Type)).ToList();

        foreach (var child in childsLoader)
        {
            if (!child.IsValid(number))
            {
                invalidChilds.Add(child.Type);
            }
        }

        return new ParentValidation (invalidChilds);
     }
   }
</code></pre>

<p>Some extra information:</p>

<ul>
<li>I've multiple child classes and not all of them implement the IParent interface</li>
<li>The list of childs that the IChildsLoader returns includes any child that implements IBase</li>
<li>On my unit testing i'm making assertions based on the ParentValidation returned by the method ChildsEngine.ValidateParent() (ex. validate if only the filter childs were considered) </li>
</ul>

<p>The only ""hack"" that I've found is to set the IsValid method as virtual on the child classes, but this forces me to mock the concrete class instead of the interface, meaning that my tests are susceptible to changes if the constructor of the classes suffers changes. </p>
",https://stackoverflow.com/questions/50977763/mock-interface-method-so-that-all-classes-that-implement-that-interface-use-that,"['c#', 'unit-testing', 'mocking', 'moq']",2742,TRUE,0,2
How to properly design a Spring component?,"<p>What basic recommendations for designing a Spring component?</p>

<p>Main purposes:</p>

<ul>
<li>avoid NullPointerExceptions</li>
<li>flexibility for unit-testing</li>
<li>thread-safety</li>
</ul>

<p>IMHO (based on Spring 4 official doc <a href=""https://docs.spring.io/spring/docs/4.2.x/spring-framework-reference/html/beans.html#beans-constructor-injection"" rel=""nofollow noreferrer"">https://docs.spring.io/spring/docs/4.2.x/spring-framework-reference/html/beans.html#beans-constructor-injection</a> (“constructor-based or setter-based DI?”)):</p>

<ul>
<li><em>Optional fields</em> should have <strong>default values</strong>. If required they should have annotations <strong>@Value</strong> (for simple types like int, String, etc) or <strong>@Autowired</strong> for complex objects.</li>
<li><em>Required fields</em> should be <strong>final</strong> and declared in a sole contsructor with <strong>@Autowired</strong> annotation. If number of required fields more than 5, it is recommended to redesign classes. Every parameter in the constructor should be annotated with <strong>@Nonnull</strong> (e.g. javax.annotation.Nonnull) with null-checks inside. </li>
<li>(?) <strong>Set</strong> methods are not recommended. Though for unit-testing you can add some (but maybe better to add this field to constructor). Also, <strong>@Nonnull</strong>  and null-checks should be used.</li>
<li>(?) <strong>Get</strong> methods are not recommended as well (why to open transitive access for internal fields?)</li>
</ul>

<p>Example:</p>

<pre><code>@Controller
@RequestMapping(""/api/clients"")
public final class ClientApiController {
    // optional field with a default value (simple type)
    @Value(""${random.string.size}"")
    private final int randomStringSize = 256;

    // optional field with a default value (complex type)
    @Autowired
    private final Charset defaultCharset = Charset.forName(""UTF-8"");

    // required field
    private final ClientService clientService;

    // sole constructor with required fields and NULL check
    @Autowired
    public ClientApiController(@Nonnull ClientService clientService) {
        Objects.requireNonNull(clientService, ""clientService is null"");
        this.clientService = clientService;
    }

    // no Set and Get methods
}
</code></pre>
",https://stackoverflow.com/questions/53138203/how-to-properly-design-a-spring-component,"['java', 'spring', 'design-patterns']",799,TRUE,0,2
Mock logging handler in unit test,"<p>I have the following logger setup:</p>

<pre><code>logger = logging.getLogger(__name__)
logger.setLevel(logging.ERROR)
file_handler = logging.FileHandler('foo.log')
formatter = logging.Formatter('%(asctime)s: %(message)s')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
</code></pre>

<p>How do I stop the logger from actually writing an entry to disk while unit testing? I am currently checking that <code>logger.error</code> is called as follows:</p>

<pre><code>@mock.patch('mymodule.logger')
def test_error_is_logged(self, mock_logger):
    mymodule.func() # this causes an error to be logged
    self.assertTrue(mock_logger.error.called)
</code></pre>

<p>The above test works correctly, however the log file <code>foo.log</code> is created on disk which I want to avoid. All I want to know is if <code>logger.error</code> is called, while mocking the file creation.</p>
",https://stackoverflow.com/questions/53007488/mock-logging-handler-in-unit-test,"['python', 'unit-testing']",1244,TRUE,2,1
Mock random generator in Go,"<p>For my tests purpose, I would like to mock random numbers in Go. So I created the Random interface. During unit testing I return the identity function, while for implementation I generate a random number with rand package.</p>

<p>It is the right way for mocking random numbers in Go? Any help appreciated.</p>

<p>Go Playground: <a href=""https://play.golang.org/p/bibNnmY2t1g"" rel=""nofollow noreferrer"">https://play.golang.org/p/bibNnmY2t1g</a></p>

<p>main:</p>

<pre><code>package main

import (
    ""time""
    ""math/rand""
    ""fmt""
)

func init() {
    rand.Seed(time.Now().UnixNano())
}

type Random interface {
    Uint(_ uint) uint
}

type rndGenerator func(n uint) uint

type Randomizer struct {
    fn rndGenerator
}

func NewRandomizer(fn rndGenerator) *Randomizer {
    return &amp;Randomizer{fn: fn}
}

func (r *Randomizer) Uint(n uint) uint {
    return r.fn(n)
}

func fakeRand(n uint) uint { return n }
func realRand(_ uint) uint { return uint(rand.Uint64()) }

func main() {
    fakeRnd := NewRandomizer(fakeRand).Uint
    fmt.Println(fakeRnd(1))
    fmt.Println(fakeRnd(2))

    realRnd := NewRandomizer(realRand).Uint
    fmt.Println(realRnd(0))
    fmt.Println(realRnd(0))
}
</code></pre>

<p>test:</p>

<pre><code>package main

import (
    ""testing""
    ""math/rand""
    ""reflect""
)

func TestNewRandomizer(t *testing.T) {
    fn := func(n uint) uint { return n }

    type args struct {
        fn rndGenerator
    }
    tests := []struct {
        name string
        args args
        want *Randomizer
    }{
        {
            ""test"",
            args{fn},
            &amp;Randomizer{fn},
        },
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            if got := NewRandomizer(tt.args.fn); reflect.TypeOf(got) != reflect.TypeOf(tt.want) {
                t.Errorf(""NewRandomizer() = %v, want %v"", got, tt.want)
            }
        })
    }
}

func TestRandomer_Uint(t *testing.T) {
    rnd := uint(rand.Uint64())

    type fields struct {
        fn rndGenerator
    }
    type args struct {
        n uint
    }
    tests := []struct {
        name   string
        fields fields
        args   args
        want   uint
    }{
        {
            ""test"",
            fields{func(n uint) uint { return n }},
            args{rnd},
            rnd,
        },
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            r := &amp;Randomizer{
                fn: tt.fields.fn,
            }
            if got := r.Uint(tt.args.n); got != tt.want {
                t.Errorf(""Randomizer.Uint() = %v, want %v"", got, tt.want)
            }
        })
    }
}

func Test_fakeRand(t *testing.T) {
    rnd := uint(rand.Uint64())

    type args struct {
        n uint
    }
    tests := []struct {
        name string
        args args
        want uint
    }{
        {
            ""test"",
            args{rnd},
            rnd,
        },
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            if got := fakeRand(tt.args.n); got != tt.want {
                t.Errorf(""fakeRand() = %v, want %v"", got, tt.want)
            }
        })
    }
}

func Test_realRand(t *testing.T) {
    type args struct {
        in0 uint
    }
    tests := []struct {
        name string
        args args
        want bool
    }{
        {
            ""test"",
            args{0},
            true,
        },
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            if got := realRand(tt.args.in0); got &lt; 1 {
                t.Errorf(""realRand() = %v, want %v"", got, tt.want)
            }
        })
    }
}
</code></pre>
",https://stackoverflow.com/questions/48360260/mock-random-generator-in-go,"['unit-testing', 'go', 'random']",5683,FALSE,2,2
Jest moduleNameMapper to change the module everywhere,"<p>When I try to map a module for unit testing with jest to a local file, it says module not found.</p>

<p>For example,</p>

<p><strong>package.json:</strong></p>

<pre><code>""moduleNameMapper"": {
    ""something"": ""&lt;rootDir&gt;/mockModulesJest/jest/ExtensionStringsModule.js""
},
</code></pre>

<p><strong>Somemodule.ts:</strong></p>

<pre><code>import * as a from 'something';
</code></pre>

<p>It shows module '<code>something</code>' not found when I try to run jest.</p>

<p>How do I solve this?
I want to mock some modules from other (my module)file as those modules do ajax calls internally with my implementation.</p>
",https://stackoverflow.com/questions/52665241/jest-modulenamemapper-to-change-the-module-everywhere,"['jestjs', 'spfx']",647,FALSE,2,0
How do I do integration testing and end to end testing?,"<p>We recently started TDD approach in our .NET project and we have done good unit testing so far but we are stuck with the question of integration and end to end tests. Say I have three objects whose constructors are as following</p>

<pre><code>constructor(kafka, sql, filesystem); // MOQ all the three
constructor(mongo, webservice, kafka); // MOQ all the three
constructor(googlemaps, sql); // MOQ all the two
</code></pre>

<p>Here we have 6 external components to be integrated into our application. We can do unit testing for the three objects by mocking all their dependencies in constructor injection and We can also do end to end testing by having real time set up for all the 6 external components.</p>

<p>My question is how do we deal with integration testing? does Integration testing deal with object testing? I believe unit testing deals with object testing, so integration must deal with external component testing. If we want to write integrate testing, How do I go with?</p>

<pre><code>// Setup kafka real and other objects must still be mocked
constructor(kafka, sql, filesystem); MOQ sql, filesystem but kafka is real
constructor(mongo, webservice, kafka); MOQ mongo, webservice but kafka is real
constructor(googlemaps, sql); MOQ all the two   
</code></pre>

<p>Write tests by making kafka component as real setup and all other objects as mocked. If we go this way, we end up with repetitive code similar to Unit test but instead of mock objects, we typically end up with real environment setup but the test cases will still be same right?</p>

<p>Can we just have unit tests and end to end tests only? because end to end test does integration test for all objects at once. If end to end tests does all the real time objects testing then why does we still do integration tests? What are some best practices for doing integration tests. When we should we go with doing integration tests. Any help is greatly appreciated.</p>
",https://stackoverflow.com/questions/48308908/how-do-i-do-integration-testing-and-end-to-end-testing,"['c#', 'unit-testing', 'testing', 'tdd', 'integration-testing']",4914,TRUE,0,1
What is the difference between Nightwatch and Capybara?,"<p>I'm using a Vue front-end with a Rails back-end and I'm looking at options for unit testing and integration tests. I'm considering Jest for unit tests, but I'm a little confused on the options for integration tests. What is the difference between Nightwatch and Capybara? Is it just that Nightwatch runs in Node and Capybara runs in Ruby?</p>
",https://stackoverflow.com/questions/49522346/what-is-the-difference-between-nightwatch-and-capybara,"['testing', 'vue.js', 'capybara', 'integration', 'nightwatch.js']",178,FALSE,1,0
using Microsoft.VisualStudio.TestTools.UnitTesting;,"<p>Simply trying to add 
using Microsoft.VisualStudio.TestTools.UnitTesting;
to an existing VS Community 2017 project so I can implement Unit testing.</p>

<p>I've googled and the solution seems to be to right click your project and 'Add>Reference'</p>

<p>But when I do so I see the attached under Assemblies 
<a href=""https://imgur.com/a/gJiV4JP"" rel=""nofollow noreferrer"">https://imgur.com/a/gJiV4JP</a></p>

<p>(No Framework Assemblies were found on the machine.</p>

<p>Can any VS gurus help?</p>
",https://stackoverflow.com/questions/53473200/using-microsoft-visualstudio-testtools-unittesting,['visual-studio'],3197,TRUE,1,1
Setting up test environment for cordova android plugin,"<p>I have a Cordova plugin which is connecting to an aar library in android java. I want to perform unit testing in this plugin using JUnit or whichever is best</p>

<p>I am a bit confused on how to set up the test environment for this. </p>

<p>MyappLauncherPlugin.java</p>

<pre><code>public class MyappLauncherPlugin extends CordovaPlugin {
    private static final String TAG = ""MyappLauncherPlugin"";

    @Override
    public void initialize(CordovaInterface cordova, CordovaWebView webView) {
        super.initialize(cordova, webView);

        Log.d(TAG, ""Initializing MyappLauncherPlugin"");
    }

    @Override
    public void onNewIntent(Intent intent){
        //Need to write code on receiving the intent

    }

    @Override
    public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
        final JSONArray methodArgs = args;
        final CallbackContext callback = callbackContext;
        final Launcher launcher = new Launcher();
        if (action.equals(""set"")) {
            final JSONObject queryArgs = methodArgs.getJSONObject(0);
            final String userId = ""{}"";
            final String userInfo = queryArgs.getString(""userInfo"");
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    launcher.setUser(userId, userInfo, cordova.getActivity(), new LauncherServerCallback() {
                        @Override
                        public void onSuccess(String response) {
                            callback.success(response);
                        }

                        @Override
                        public void onError(Throwable t) {
                            callback.error(t.getMessage());
                        }
                    });
        }
        else if(action.equals(""launch"")){
            final JSONObject queryArgs = methodArgs.getJSONObject(0);
            final String packageName = queryArgs.getString(""packageName"");
            final String appName = queryArgs.getString(""appName"");
            final String auxName = queryArgs.getString(""auxName"");
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    launcher.launchApp(appName, packageName, auxName, cordova.getActivity(), new LauncherServerCallback() {
                        @Override
                        public void onSuccess(String response) {
                            callback.success(response);
                        }

                        @Override
                        public void onError(Throwable t) {
                            callback.error(t.getMessage());
                        }
                    });
            });

}
</code></pre>

<p>The folder structure for this project is as</p>

<p><a href=""https://ibb.co/vJW8nCW"" rel=""nofollow noreferrer"">click here</a></p>

<p>Please help me with this.</p>
",https://stackoverflow.com/questions/53928241/setting-up-test-environment-for-cordova-android-plugin,"['java', 'android', 'cordova-plugins']",138,FALSE,1,0
ModuleNotFoundError issue for pytest,"<p>I want to use pytest to do unit testing for the scripts in another folder called <code>src</code>. Here is my directory structure:</p>

<pre><code>src      
  __init__.py
  script1.py
  script2.py
test
  test_fun.py
</code></pre>

<p>However, when I try to run <code>pytest</code> in the <code>test</code> folder through command line, I saw the following error</p>

<blockquote>
  <p>from script2 import fun2<br>
  E ModuleNotFoundError: No module named 'script2'</p>
</blockquote>

<p>In each script, I have the following contents</p>

<p><strong>script2.py</strong>:</p>

<pre><code>def fun2():
return('result_from_2')
</code></pre>

<p><strong>script1.py</strong>:</p>

<pre><code>from script2 import fun2

def fun1():
    return(fun2()+'_plus_something')
</code></pre>

<p><strong>test_fun.py</strong>:</p>

<pre><code>import sys
sys.path.append('../')
from src.script1 import fun1

def test_fun1():        
    output1 = fun1()

    # check output
    assert output1=='result_from_2_plus_something'
</code></pre>

<p>How can I run pytest with the directory provided above?</p>
",https://stackoverflow.com/questions/49605830/modulenotfounderror-issue-for-pytest,"['python', 'unit-testing', 'module', 'pytest']",6344,TRUE,7,4
Vue.js unit test cases with vue-test-utils and Jest failing,"<p>using vue-cli 3 , I starting to learn unit testing with Jest</p>

<p>I wrote my first spec for my initial Heading component</p>

<pre><code>import { shallowMount } from ""@vue/test-utils"";
import Heading from ""@/components/Home/Heading.vue"";

describe(""Heading.vue"", () =&gt; {
  it(""should contains default heading"", () =&gt; {
    // when
    const wrapper = shallowMount(Heading);
    // then
    const heading = wrapper.find('h1');
    expect(heading.text()).toContain('In the heart of Charentes...')
  });
});
</code></pre>

<p>but I get a syntax error in the  of y component (??,) </p>

<p>Invalid or unexpected token</p>

<pre><code>vue-cli-service test:unit

 FAIL  tests/unit/Heading.spec.js (16.815s)
  Heading.vue
    ✕ should contains default heading (215ms)

  ● Heading.vue › should contains default heading

    /Users/yves/Developments/WIP/VUE.JS-cli-3/3-chocha-home-content/chocha/src/assets/images/hero.jpeg:1    ({""Object.&lt;anonymous&gt;"":function(module,exports,require,__dirname,__filename,global,jest){����
                                                                                             ^

    SyntaxError: Invalid or unexpected token

      124 | .primaryInversed {
      125 |   background-color: white !important;
    &gt; 126 |   border-color: #464898 !important;
          |                                                                                                ^
      127 |   color: #464898 !important;
      128 |   .icon {
      129 |     color: #464898 !important;

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
</code></pre>

<p>I don't undertsand why ...   ( I am following the small tut from <a href=""https://blog.octo.com/en/vue-js-unit-test-cases-with-vue-test-utils-and-jest/"" rel=""nofollow noreferrer"">octo talks</a></p>

<p>here is my component</p>

<pre><code>&lt;template&gt;
      &lt;section id='heading'&gt;
        &lt;v-parallax :src=""require('@/assets/images/hero.jpeg')""&gt;
          &lt;v-layout column align-center justify-center&gt;
            &lt;img src=""@/assets/images/logo.png"" alt=""Logo-Choro-des-Charentes"" height=""200""&gt;
            &lt;h1 class=""mb-2 display-1 text-xs-center""&gt;{{ $t('lang.views.home.heading.header1') }}&lt;/h1&gt;
            &lt;h2 class=""mb-2 display-1 text-xs-center""&gt; {{ $t('lang.views.home.heading.header2') }}&lt;/h2&gt;
            &lt;div class=""subheading mb-3 text-xs-center""&gt;{{ $t('lang.views.home.heading.subheading') }}&lt;/div&gt;
            &lt;v-btn round v-if=""!listening"" @click=""startAudioPlayer()"" class=""primary"" large href=""#""&gt;{{ $t('lang.views.home.heading.btn__listen') }}
              &lt;v-icon right&gt;play_arrow&lt;/v-icon&gt;
            &lt;/v-btn&gt;
            &lt;v-btn round v-else @click=""stopAudioPlayer()"" class=""primaryInversed"" large href=""#""&gt;{{ $t('lang.views.home.heading.btn__stop') }}
              &lt;v-icon right&gt;pause_circle_outline&lt;/v-icon&gt;
            &lt;/v-btn&gt;
            &lt;audioplayer id=""audioplayer"" v-if=""audioPlayer"" :autoPlay=""shouldPlay"" :file=""audioFile"" :canPlay=""audioReady"" :ended=""audioFinish""&gt;&lt;/audioplayer&gt;
         &lt;/v-layout&gt;
        &lt;/v-parallax&gt;

        &lt;div id='content'&gt;
          &lt;v-layout row wrap class='my-5' &gt;
            &lt;v-flex xs12 sm4&gt;
              &lt;v-card class='elevation-0'&gt;
                &lt;v-card-text class=""text-xs-center""&gt;
                  &lt;v-icon x-large class=""""&gt;group&lt;/v-icon&gt;
                &lt;/v-card-text&gt;
                &lt;v-card-title primary-title class=""layout justify-center""&gt;
                  &lt;div class=""headline text-xs-center"" v-html=""$t('lang.views.home.heading.card1__title')""&gt;&lt;/div&gt;
                &lt;/v-card-title&gt;
                &lt;v-card-text v-html=""$t('lang.views.home.heading.card1__content')""&gt;&lt;/v-card-text&gt;
              &lt;/v-card&gt;
            &lt;/v-flex&gt;

            &lt;v-flex xs12 sm4&gt;
              &lt;v-card class='elevation-0'&gt;
                &lt;v-card-text class='text-xs-center'&gt;
                  &lt;v-icon x-large class=""""&gt;audiotrack&lt;/v-icon&gt;
                &lt;/v-card-text&gt;
                &lt;v-card-title primary-title class=""layout justify-center""&gt;
                  &lt;div class=""headline"" v-html=""$t('lang.views.home.heading.card2__title')""&gt;&lt;/div&gt;
                &lt;/v-card-title&gt;
                &lt;v-card-text v-html=""$t('lang.views.home.heading.card2__content')""&gt;&lt;/v-card-text&gt;
              &lt;/v-card&gt;
            &lt;/v-flex&gt;

            &lt;v-flex xs12 sm4&gt;
              &lt;v-card class='elevation-0'&gt;
                &lt;v-card-text class='text-xs-center'&gt;
                   &lt;v-icon x-large class=""""&gt;tap_and_play&lt;/v-icon&gt;
                &lt;/v-card-text&gt;
                &lt;v-card-title primary-title class=""layout justify-center""&gt;
                  &lt;div class=""headline text-xs-center"" v-html=""$t('lang.views.home.heading.card3__title')""&gt;&lt;/div&gt;
                &lt;/v-card-title&gt;
                &lt;v-card-text v-html=""$t('lang.views.home.heading.card3__content')""&gt;&lt;/v-card-text&gt;
              &lt;/v-card&gt;
            &lt;/v-flex&gt;
          &lt;/v-layout&gt;
        &lt;/div&gt;
      &lt;/section&gt;
&lt;/template&gt;

&lt;script&gt;
import AudioPlayer from ""@/components/Home/AudioPlayer.vue"";
// import { mapGetters } from 'vuex'
export default {
  name: ""Heading"",
  data() {
    return {
      listening: false,
      file: ""ultimo_desejo"",
      audioPlayer: false,
      audioPlayerShouldPlay: true // autoplay
    };
  },
  components: {
    audioplayer: AudioPlayer
  },
  computed: {
    // ...mapGetters(['webpSupport']),
    shouldPlay() {
      return this.audioPlayerShouldPlay;
    },
    audioFile() {
      return require(""@/assets/audio/"" + this.file + "".mp3"");
    }
  },
  methods: {
    audioReady() {
      // console.log('You see this means audio can start.')
    },
    audioFinish() {
      // console.log('You see this means audio finish.')
      this.listening = false;
      this.audioPlayer = false;
    },
    showAudioPlayer() {
      this.audioPlayer = true;
    },
    startAudioPlayer() {
      this.listening = true;
      this.audioPlayer = true;
    },
    stopAudioPlayer() {
      this.listening = false;
      this.audioPlayer = false;
    }
  },
  mounted() {
    // console.log('HEADING webp format support: ', this.webpSupport)
  },
  beforeMount() {
    this.playerAutoPlay = this.autoPlay; // save props data to itself's data and deal with it
  }
};
&lt;/script&gt;

&lt;!-- Add ""scoped"" attribute to limit CSS to this component only --&gt;
&lt;style scoped lang=""scss""&gt;
#audioplayer {
  display: none; // hide the autoplayer !
}
.btn__content .icon {
  color: white !important;
}
.primaryInversed {
  background-color: white !important;
  border-color: #464898 !important;
  color: #464898 !important;
  .icon {
    color: #464898 !important;
  }
}
&lt;/style&gt;
</code></pre>

<p>UPDATE</p>

<p>here is the complete console.log error output</p>

<pre><code>    &gt; vue-cli-service test:unit

     FAIL  tests/unit/Heading.spec.js (8.158s)
      Heading.vue
        ✕ should contains default heading (226ms)

      ● Heading.vue › should contains default heading

        /Users/yves/Developments/WIP/VUE.JS-cli-3/3-chocha-home-content/chocha/src/assets/images/hero.jpeg:1
        ({""Object.&lt;anonymous&gt;"":function(module,exports,require,__dirname,__filename,global,jest){����
                                                                                                 ^

        SyntaxError: Invalid or unexpected token

          124 | .primaryInversed {
          125 |   background-color: white !important;
        &gt; 126 |   border-color: #464898 !important;
              |                                                                                                ^
          127 |   color: #464898 !important;
          128 |   .icon {
          129 |     color: #464898 !important;

          at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:403:17)
          at Proxy.render (src/components/Home/Heading.vue:126:186)
          at VueComponent.Vue._render (node_modules/vue/dist/vue.runtime.common.js:4542:22)
          at VueComponent.updateComponent (node_modules/vue/dist/vue.runtime.common.js:2786:21)
          at Watcher.get (node_modules/vue/dist/vue.runtime.common.js:3140:25)
          at new Watcher (node_modules/vue/dist/vue.runtime.common.js:3129:12)

      console.error node_modules/vue/dist/vue.runtime.common.js:589
        [Vue warn]: Error in config.errorHandler: ""SyntaxError: Invalid or unexpected token""

      console.error node_modules/vue/dist/vue.runtime.common.js:1739
        /Users/yves/Developments/WIP/VUE.JS-cli-3/3-chocha-home-content/chocha/src/assets/images/hero.jpeg:1
        ({""Object.&lt;anonymous&gt;"":function(module,exports,require,__dirname,__filename,global,jest){����
                                                                                                 ^

        SyntaxError: Invalid or unexpected token
            at ScriptTransformer._transformAndBuildScript (/Users/yves/Developments/WIP/VUE.JS-cli-3/3-chocha-home-content/chocha/node_modules/jest-runtime/build/script_transformer.js:403:17)
            at ScriptTransformer.transform (/Users/yves/Developments/WIP/VUE.JS-cli-3/3-chocha-home-content/chocha/node_modules/jest-runtime/build/script_transformer.js:448:19)
            at Runtime._execModule (/Users/yves/Developments/WIP/VUE.JS-cli-3/3-chocha-home-content/chocha/node_modules/jest-runtime/build/index.js:640:53)
            at Runtime.requireModule (/Users/yves/Developments/WIP/VUE.JS-cli-3/3-chocha-home-content/chocha/node_modules/jest-runtime/build/index.js:376:14)
            at Runtime.requireModuleOrMock (/Users/yves/Developments/WIP/VUE.JS-cli-3/3-chocha-home-content/chocha/node_modules/jest-runtime/build/index.js:463:19)
            at Proxy.render (/Users/yves/Developments/WIP/VUE.JS-cli-3/3-chocha-home-content/chocha/src/components/Home/Heading.vue:126:186)
            at VueComponent.Vue._render (/Users/yves/Developments/WIP/VUE.JS-cli-3/3-chocha-home-content/chocha/node_modules/vue/dist/vue.runtime.common.js:4542:22)
            at VueComponent.updateComponent (/Users/yves/Developments/WIP/VUE.JS-cli-3/3-chocha-home-content/chocha/node_modules/vue/dist/vue.runtime.common.js:2786:21)
            at Watcher.get (/Users/yves/Developments/WIP/VUE.JS-cli-3/3-chocha-home-content/chocha/node_modules/vue/dist/vue.runtime.common.js:3140:25)
            at new Watcher (/Users/yves/Developments/WIP/VUE.JS-cli-3/3-chocha-home-content/chocha/node_modules/vue/dist/vue.runtime.common.js:3129:12)

      console.error node_modules/vue/dist/vue.runtime.common.js:589
        [Vue warn]: Error in render: ""SyntaxError: Invalid or unexpected token""

        found in

        ---&gt; &lt;Heading&gt;
               &lt;Root&gt;

      console.error node_modules/vue/dist/vue.runtime.common.js:1739
        /Users/yves/Developments/WIP/VUE.JS-cli-3/3-chocha-home-content/chocha/src/assets/images/hero.jpeg:1
        ({""Object.&lt;anonymous&gt;"":function(module,exports,require,__dirname,__filename,global,jest){����
                                                                                                 ^

        SyntaxError: Invalid or unexpected token
            at ScriptTransformer._transformAndBuildScript (/Users/yves/Developments/WIP/VUE.JS-cli-3/3-chocha-home-content/chocha/node_modules/jest-runtime/build/script_transformer.js:403:17)
            at ScriptTransformer.transform (/Users/yves/Developments/WIP/VUE.JS-cli-3/3-chocha-home-content/chocha/node_modules/jest-runtime/build/script_transformer.js:448:19)
            at Runtime._execModule (/Users/yves/Developments/WIP/VUE.JS-cli-3/3-chocha-home-content/chocha/node_modules/jest-runtime/build/index.js:640:53)
            at Runtime.requireModule (/Users/yves/Developments/WIP/VUE.JS-cli-3/3-chocha-home-content/chocha/node_modules/jest-runtime/build/index.js:376:14)
            at Runtime.requireModuleOrMock (/Users/yves/Developments/WIP/VUE.JS-cli-3/3-chocha-home-content/chocha/node_modules/jest-runtime/build/index.js:463:19)
            at Proxy.render (/Users/yves/Developments/WIP/VUE.JS-cli-3/3-chocha-home-content/chocha/src/components/Home/Heading.vue:126:186)
            at VueComponent.Vue._render (/Users/yves/Developments/WIP/VUE.JS-cli-3/3-chocha-home-content/chocha/node_modules/vue/dist/vue.runtime.common.js:4542:22)
            at VueComponent.updateComponent (/Users/yves/Developments/WIP/VUE.JS-cli-3/3-chocha-home-content/chocha/node_modules/vue/dist/vue.runtime.common.js:2786:21)
            at Watcher.get (/Users/yves/Developments/WIP/VUE.JS-cli-3/3-chocha-home-content/chocha/node_modules/vue/dist/vue.runtime.common.js:3140:25)
            at new Watcher (/Users/yves/Developments/WIP/VUE.JS-cli-3/3-chocha-home-content/chocha/node_modules/vue/dist/vue.runtime.common.js:3129:12)
</code></pre>
",https://stackoverflow.com/questions/51951790/vue-js-unit-test-cases-with-vue-test-utils-and-jest-failing,"['vue.js', 'jestjs', 'vuetify.js', 'vue-test-utils']",2266,TRUE,1,2
How to write unit tests for sequelize models with Chai,"<p>My tests are working and passing, but chai's done function is messing up. I've tried a few different methods, but I don't understand where I'm going wrong in these unit tests. I'm very new to unit testing and chai, so any help would be greatly appreciated</p>

<p>The places where the test is failing: line 40 (create), line 98 (update)</p>

<p>Any ideas?</p>

<pre><code>const chai = require('chai')
let should = chai.should()
let expect = chai.expect
let db = require('../app/models')
db.hosts.modelName = 'Hosts'
db.victims.modelName = 'Victims'
let models = [db.hosts, db.victims]

models.forEach(model =&gt; {
    describe(`${model.modelName} Model`, function (done) {
        var modelData = {
            guest_count: 3,
            start_date: ""2018-01-11T00:00:00.000Z"",
            end_date: ""2018-01-12T00:00:00.000Z"",
            location: {
                type: ""Point"",
                coordinates: [
                    -74.323564,
                    40.232323
                ]
            },
            first_name: ""Sean"",
            last_name: ""Destroyed"",
            phone: ""7325556677"",
            address: ""123 main street, red bank, nj"",
            email: ""test@gmail.com"",
        }

        it(`should create a new ${model.modelName}`, function () {

            model.create(modelData).then(function (user) {
                //victim name should be equivalent to the fake submission we are using
                expect(user.first_name).to.equal(""Sean""); 
                //remove the entry from the database
                model.destroy({
                    where: {
                        id: user.id
                    }
                })
                done()
            })


        });

        it(`should delete a ${model.modelName} from the database`, function () {
            model.create(modelData).then(function (user) {
                //victim name should be equivalent to the fake submission we are using
                //remove the entry from the database
                model.destroy({
                    where: {
                        id: user.id
                    }
                })

                try {
                    model.findOne({
                        where: {
                            id: user.id
                        }
                    })
                } catch (err) {
                    expect(user.first_name).to.undefined; 
                    if (err) {
                        done()
                    }
                }

            })
        })

          it(`should update the ${model.modelName} entry in the database`, function () {
            model.create(modelData).then(function (user) {
                //after user is created, then update a value
                modelData.guest_count = 12

                model.update(modelData, {
                    where: {
                        id: user.id
                    }
                }).then(function(data) {
                    model.findOne({
                        where: {
                            id: user.id
                        }
                    }).then(function (data) {
                        expect(data.guest_count).to.equal(12);
                    }).then(function () {
                        model.destroy({
                            where: {
                                id: user.id
                            }
                        })
                    }).then(function() {
                        done()
                    })
                })

            })
        })
    })    
});
</code></pre>
",https://stackoverflow.com/questions/48967567/how-to-write-unit-tests-for-sequelize-models-with-chai,"['node.js', 'sequelize.js', 'chai']",8581,TRUE,1,2
How to generate mocha test case report and show using Jenkins?,"<p>I am doing mocha unit testing for my JavaScript functions. I am running mocha in a browser not using Node. I am using require.js to load files. </p>

<p>When I do mocha.run() it shows reports in the browser. </p>

<p>Now I want to make a Jenkins job to display the report. </p>

<p>So how do I generate the report file so that I can provide it to Jenkins?</p>
",https://stackoverflow.com/questions/52758352/how-to-generate-mocha-test-case-report-and-show-using-jenkins,"['testing', 'jenkins', 'mocha.js']",3884,TRUE,4,3
Firebase Cloud Function - Unit Testing - Please supply a Firebase app in the constructor for DataSnapshot in order to use the .ref method,"<p>I am trying to setup <code>Unit Testing</code> for Firebase cloud functions. I was following these links:</p>

<ul>
<li><a href=""https://firebase.google.com/docs/functions/unit-testing"" rel=""nofollow noreferrer"">https://firebase.google.com/docs/functions/unit-testing</a></li>
<li><a href=""https://github.com/firebase/functions-samples/blob/4663b4ddfae3ed8f8a110156d60e71f028680ee7/quickstarts/uppercase/functions/test/test.online.js"" rel=""nofollow noreferrer"">https://github.com/firebase/functions-samples/blob/4663b4ddfae3ed8f8a110156d60e71f028680ee7/quickstarts/uppercase/functions/test/test.online.js</a></li>
</ul>

<p>I am trying to make the sample code run. Code is as follows:</p>

<pre><code>const chai          =   require('chai');
const sinon                     =   require('sinon');
const admin                     =   require('firebase-admin');
const projectConfig             =   {
    databaseURL                 :   'https://gr-automation-5e65c.firebaseio.com',
    storageBucket               :   'gr-automation-5e65c.appspot.com',
    projectId                   :   'gr-automation-5e65c',
};

const test                      =   require('firebase-functions-test')(projectConfig, '../gr-automation-5e65c-firebase-adminsdk-jkdtf-849f3d0f65.json');

test.mockConfig( /* removed for Clarity */ );

const assert                    =   chai.assert;

describe('Cloud Functions', () =&gt; {
    let myFunctions;
    adminInitStub               =   sinon.stub(admin, 'initializeApp');
    admin.initializeApp();

    //console.log(test);

    before(() =&gt; {
        myFunctions             =   require('../lib/index.js');
        //console.log(myFunctions);
        //console.log(admin);
    });

    after(() =&gt; {
        test.cleanup();
        admin.database().ref('messages').remove();
    });

    describe('makeUpperCase', () =&gt; {

    it('should upper case input and write it to /uppercase', () =&gt; {
        const snap = test.database.makeDataSnapshot('input', 'messages/11111/original');

        const wrapped = test.wrap(myFunctions.makeUppercase);

        return wrapped(snap).then(() =&gt; {
        return admin.database().ref('messages/11111/uppercase').once('value').then((createdSnap) =&gt; {
            assert.equal(createdSnap.val(), 'INPUT');
        });
        });
    })

    });

});
</code></pre>

<p>When I run the test, I get the following error:</p>

<pre><code>  Cloud Functions
    makeUpperCase
Uppercasing undefined input
      1) should upper case input and write it to /uppercase
    2) ""after all"" hook


  0 passing (364ms)
  2 failing

  1) Cloud Functions
       makeUpperCase
         should upper case input and write it to /uppercase:
     Error: Please supply a Firebase app in the constructor for DataSnapshot in order to use the .ref method.
      at DataSnapshot.get ref [as ref] (node_modules/firebase-functions/lib/providers/database.js:186:19)
      at Function.exports.makeUppercase.functions.database.ref.onCreate [as run] (lib/index.js:135:21)
      at wrapped (node_modules/firebase-functions-test/lib/main.js:53:30)
      at Context.it (test/index.test.js:46:13)

  2) Cloud Functions
       ""after all"" hook:
     Error: The default Firebase app does not exist. Make sure you call initializeApp() before using any of the Firebase services.
      at FirebaseAppError.FirebaseError [as constructor] (node_modules/firebase-admin/lib/utils/error.js:39:28)
      at FirebaseAppError.PrefixedFirebaseError [as constructor] (node_modules/firebase-admin/lib/utils/error.js:85:28)
      at new FirebaseAppError (node_modules/firebase-admin/lib/utils/error.js:119:28)
      at FirebaseNamespaceInternals.app (node_modules/firebase-admin/lib/firebase-namespace.js:105:19)
      at FirebaseNamespace.app (node_modules/firebase-admin/lib/firebase-namespace.js:372:30)
      at FirebaseNamespace.ensureApp (node_modules/firebase-admin/lib/firebase-namespace.js:388:24)
      at FirebaseNamespace.fn (node_modules/firebase-admin/lib/firebase-namespace.js:283:30)
      at Context.after (test/index.test.js:31:15)
</code></pre>

<p>Any hint on what am I doing wrong?</p>
",https://stackoverflow.com/questions/50754070/firebase-cloud-function-unit-testing-please-supply-a-firebase-app-in-the-con,"['node.js', 'unit-testing', 'firebase', 'firebase-realtime-database', 'google-cloud-functions']",858,TRUE,1,1
Msbuild with bitbucket pipeline,"<p>We have multiple dotnet projects(dot net framework 4.7.1) in our own bitbucket repository. We like to implement continous integration so that every check in the the repository should run automatic unit testing and create build and upload the build to an AWS S3 bucket. I could not find any useful information for this.</p>

<p>We are not using dotnet core. And we need to use MSBuild.</p>
",https://stackoverflow.com/questions/50756693/msbuild-with-bitbucket-pipeline,"['.net', 'msbuild', 'continuous-integration', 'bitbucket']",3819,TRUE,4,1
Using MatrixCursor in unit test,"<p>Im trying to test a helper class I wrote that interacts with cursor objects. I've written the test using a <code>MatrixCursor</code> to construct the cursor used for the tests but since <code>MatrixCursor</code> is built into the android framework it's not compatible with unit testing and needs to be mocked or used in an instrumented test. Is there any workaround? Is it possible to import <code>MatrixCursor</code> as a gradle test dependency?</p>
",https://stackoverflow.com/questions/49741667/using-matrixcursor-in-unit-test,"['android', 'android-testing']",171,FALSE,4,0
Why do you count the number of times a function gets called in unit test,"<p>My new colleague incessantly insist me to count the number of times functions inside a unit test gets called when doing backend unit testing. I can see why it can be helpful at times but for most part I feel that it is redundant and unnecessary. From my perspective, it should not matter what function gets called and how many times it gets called. What matters is what goes in and comes out to check the expected behavior. </p>

<p>Unit testing should be more like a black box as in it doesnt matter how you get the answer, but matters if the answer is correct or not. If I am always validating the number of times some functions gets called, it creates a lot of overhead cost. It also means that everytime I change the approach to solve the problem, my unit test would break and I will need to fix it every single time. I feel like this approach limits the flexibility of coders. </p>

<p>Can anyone please tell me why these sort of unit testing should be performed? Thank you.</p>

<p>To be more specific, the code is in java and the overview of the structure is as follows: the controllers handles api calls and make calls to relevant facade, which in turn calls services to fetch the data. The facade is combination of services and the services talk to the database. These ""unit tests"" need to be performed for all three layers. Eg. checking the number of times each facade in the controllers gets called. And checking if each services inside the facade gets called and how many times it gets called.</p>
",https://stackoverflow.com/questions/49194186/why-do-you-count-the-number-of-times-a-function-gets-called-in-unit-test,"['unit-testing', 'testing']",1323,TRUE,3,2
Observable&lt;Observable&lt;GridDataResult&gt;&gt; vs Observable&lt;GridDataResult&gt; in kendo UI for angular,"<p>kendo UI for angular uses <code>Observable&lt;Observable&lt;GridDataResult&gt;&gt;</code> as return type for grid data</p>

<pre><code>  getData(model: State): Observable&lt;Observable&lt;GridDataResult&gt;&gt; {
return this.mainService.post(`http://localhost:41689/api/Data/GetData`, model);
}
</code></pre>

<p>then to call this </p>

<pre><code>  public view: Observable&lt;GridDataResult&gt; | undefined;
  public gridState: State = {
  sort: [],
  skip: 0,
  take: 10
  };

public getData() {
return this.sampleTypeService.getData(this.gridState).subscribe(
  res =&gt; {
    this.view = res;
  }
);
}
</code></pre>

<p>this works . but in unit test I cannot get data in <code>view</code> because it is an observable.</p>

<p>if I change </p>

<pre><code>public view: Observable&lt;GridDataResult&gt; | undefined;
</code></pre>

<p>to</p>

<pre><code>public view: GridDataResult | undefined;
</code></pre>

<p>and getData to </p>

<pre><code>getData(model: State): Observable&lt;GridDataResult&gt; {
return this.mainService.post(`http://localhost:41689/api/Data/GetData`, model);
}
</code></pre>

<p>it works. And now I can do unit testing on returned data. </p>

<p>I want to know what is the difference between these two</p>
",https://stackoverflow.com/questions/51817859/observableobservablegriddataresult-vs-observablegriddataresult-in-kendo-ui,"['angular', 'observable', 'karma-jasmine', 'kendo-ui-angular2']",1075,FALSE,0,0
Css rules unit test in react material-ui,"<p>For a react component built using material-ui(next), material-ui styling solution can be used to create a style sheet and inject it.</p>

<pre><code>const styleSheet = theme =&gt; {
  return{
   default: {
     color: theme.palette.primary.contrastText
   },
 }
</code></pre>

<p>How can we add unit tests for the same? What i am interested is in unit testing the css rules applied, not the classname. For eg in this case default class should have a color property and its value should be equal to <code>theme.palette.primary.contrastText</code></p>
",https://stackoverflow.com/questions/50018507/css-rules-unit-test-in-react-material-ui,"['reactjs', 'material-ui', 'jestjs', 'enzyme']",142,FALSE,3,0
Interdependence of unit tests,"<p>Since recently, I am trying out unit testing to get acquainted with the practice, and to ultimately write better code. I have started on one of my big projects, with a rather large untested code base, but am only unit testing utility classes, that don't have many dependencies and are quite easy to test.</p>

<p>I have read quite a bit of introductory material to unit testing in general, and what often comes up is that unit tests should always test the smallest possible unit of behaviour. That is to say, that whether a test passes or fails should only depend on a very specific piece of code, such as a small method.</p>

<p>However, I am already finding problems to put this idea into practice. Consider for example :</p>

<pre><code>@Test
public void testSomethingWithFoo() {
    Foo foo = new Foo(5);

    Bar result = foo.bar(); //Suppose this returns new Bar(42) for some reason.

    Bar expected = new Bar(42);
    Assert.assertEquals(expected, result); // Implicitly calls Bar.equals, which returns true if both Bars' constructor parameters are equal.
}
</code></pre>

<p>Clearly, this test depends on two elements : the foo.bar() method, but also the bar.equals(otherBar) method, which is implicitly called by the assertion.</p>

<p>Now, I could write an other test, which asserts that this bar.equals() method works correctly. However, say it fails. Now, my first test also should fail, but for a reason beyond its scope.</p>

<p>My point is that, for this particular example, nothing really is problematic; I could maybe check for equality without using equals at all. However, I feel like this sort of issue will become a real problem with more complex behaviours, where avoiding existing methods because they might not work would involve rewriting large amounts of code just for tests.</p>

<p><strong>How to translate these requirements into code, without making unit tests interdependent ?</strong></p>

<p><strong>Is it even possible ? If not, should I stop bothering about this issue, and assume all methods not under the current test work ?</strong></p>
",https://stackoverflow.com/questions/48632157/interdependence-of-unit-tests,"['java', 'unit-testing', 'junit']",1032,TRUE,2,2
How to mock a File as a prop in jest?,"<p>I'm busy getting into unit testing with React, Jest and Enzyme.</p>

<p>I've got a component that takes a PDF <code>File</code> as a prop, see this interface:</p>

<pre><code>interface IProps {
  file: File;
}
</code></pre>

<p>I'm trying to do a straight up basic test just to make sure the component renders without crashing using it's required props (i.e. the <code>File</code>).</p>

<p>Here's my test case:</p>

<pre><code>describe('MyComponent', () =&gt; {
  const props = {
    file: /* How do I mock this file? */
  };

  it('renders without crashing', () =&gt; {
    mount(&lt;MyComponent {...props} /&gt;);
  });
});
</code></pre>

<p>How do I mock a <code>File</code> for the <code>file</code> prop?</p>
",https://stackoverflow.com/questions/52893385/how-to-mock-a-file-as-a-prop-in-jest,"['reactjs', 'unit-testing', 'mocking', 'jestjs', 'enzyme']",1536,TRUE,0,1
How to avoid methods exceeded maximum allowed ABC complexity (1),"<p>Hi I am working on RoR project with ruby-2.5.0 and Rails 5. I have a method in which i find date and time with regex as follows:-</p>

<pre><code>def find_date_time(params)
    date_pattern = %r{\d{1,2}/\d{1,2}/\d{4}|\d{1,2}\/\d{1,2}\/\d{2}}
    time_pattern = /(\d{2}\:\d{2}:\d{2}|\d{2}\:\d{2})/
    date = params.to_s[date_pattern]
    return unless date
    date_array = date.split('/')
    if date_array.last.length == 2
      date = date_array.replace([date_array.first,
                                 date_array.second,
                                 '20' + date_array.third])
                       .join('/')
    end
    time = params.to_s.scan(time_pattern)
    Time.strptime(date +
                  ' ' +
                  (time.present? ? time.uniq.flatten.last : ''),
                  (time.present? ? '%d/%m/%Y %H:%M' : '%d/%m/%Y'))
  end
</code></pre>

<p>Its works fine but when i run my unit testing <code>RAILS_ENV=test bundle exec rake</code> it returns an error <code>Methods exceeded maximum allowed ABC complexity (1)</code> I am using rubocop-rspec. Please help me how can i reduce the complexity of my code. Thanks in advance.</p>
",https://stackoverflow.com/questions/49808823/how-to-avoid-methods-exceeded-maximum-allowed-abc-complexity-1,['ruby-on-rails'],289,FALSE,0,0
Dagger 2 - cannot be provided without an @Inject constructor or an @Provides-annotated method,"<p>I have a problem with Dagger 2 dependency injection. I'm using it in Android project but in a java-library module and in unit testing.</p>

<p>ApiTestModule.kt</p>

<pre><code>@Module
class ApiTestModule {

    @Provides
    @Named(""testDatasource"")
    fun provideGithubTestDatasource(): GithubDatasourceImpl {
        return GithubDatasourceImpl(Mockito.mock(GithubService::class.java))
    }
}
</code></pre>

<p>TestComponent.kt</p>

<pre><code>@Singleton
@Component(modules = [ApiTestModule::class])
interface TestComponent {
    fun inject(test: GithubDatasourceImplTest)
}
</code></pre>

<p>GithubDatasourceImplTest.kt</p>

<pre><code>class GithubDatasourceImplTest {

    @set:[Inject Named(""testDatasource"")]
    lateinit var datasource: GithubDatasourceImpl

    @Before
    fun setUp() {
        val component = DaggerTestComponent.builder()
                .apiTestModule(ApiTestModule())
                .build()
        component.inject(this)
    }

    @Test
    fun test_create() {
        checkNotNull(datasource)
    }
}
</code></pre>

<p>module build.gradle</p>

<pre><code>apply plugin: 'java-library'
apply plugin: 'kotlin'
apply plugin: 'kotlin-kapt'

kapt {
    generateStubs = true
}

dependencies {
    rootProject.ext.apiGithubDependencies.each {
        add(it.configuration, it.dependency)
    }
}

sourceCompatibility = ""1.7""
targetCompatibility = ""1.7""
</code></pre>

<p>My error</p>

<p>error: </p>

<pre><code>[Dagger/MissingBinding] hr.thekarlo95.api.github.GithubDatasourceImpl cannot be provided without an @Inject constructor or an @Provides-annotated method.
    public abstract void inject(@org.jetbrains.annotations.NotNull()
                         ^
      hr.thekarlo95.api.github.GithubDatasourceImpl is injected at
          hr.thekarlo95.api.github.GithubDatasourceImplTest.setDatasource(p0)
      hr.thekarlo95.api.github.GithubDatasourceImplTest is injected at
          hr.thekarlo95.api.github.di.TestComponent.inject(hr.thekarlo95.api.github.GithubDatasourceImplTest)
</code></pre>

<p>I cannot get this to work and error message doesn't really help. If I remove <code>fun inject(test: GithubDatasourceImplTest)</code> from <code>TestComponent</code> everything compiles but then I cannot inject dependencies to my unit test.</p>
",https://stackoverflow.com/questions/51217520/dagger-2-cannot-be-provided-without-an-inject-constructor-or-an-provides-ann,"['java', 'android', 'kotlin', 'dagger-2']",390,FALSE,0,0
Unit test hangs forever if `DoFn` resets event timers,"<p>I'm unit testing (with <code>TestStream</code> and <code>PAssert</code>) a <code>DoFn</code> that resets event timers. Test hangs forever if <code>DoFn</code> resets timers and this behavior seems specific to event domain timers.</p>

<p>Is this a bug in beam testing facilities or expected timer behavior?</p>

<p>Here is a toy example that I can reproduce this behavior with beam 2.3 SDK.</p>

<pre class=""lang-java prettyprint-override""><code>static class KeyElements extends DoFn&lt;String, KV&lt;String, String&gt;&gt; {
    @ProcessElement
    public void processElement(ProcessContext context) {
        final String[] parts = context.element().split("":"");
        if (parts.length == 2) {
            context.output(KV.of(parts[0], parts[1]));
        }
    }
}

static class TimerDoFn extends DoFn&lt;KV&lt;String, String&gt;, KV&lt;String, String&gt;&gt; {
    @TimerId(""expiry"")
    private final TimerSpec timerSpec = TimerSpecs.timer(TimeDomain.EVENT_TIME);

    @ProcessElement
    public void processElement(ProcessContext context, @TimerId(""expiry"") Timer timer) {
        timer.set(context.timestamp().plus(Duration.standardHours(1)));
        final KV&lt;String, String&gt; e = context.element();
        context.output(KV.of(e.getKey(), e.getValue() + ""_output""));
    }

    @OnTimer(""expiry"")
    public void onExpiry(OnTimerContext context) {
        // do nothing
    }
}

@Rule
public TestPipeline p = TestPipeline.create();

@Test
public void testTimerDoFn() {
    TestStream&lt;String&gt; stream = TestStream
            .create(StringUtf8Coder.of())
            .addElements(
                    TimestampedValue.of(""a:0"", new Instant(0)),
                    TimestampedValue.of(""a:1"", new Instant(1)),
                    TimestampedValue.of(""a:2"", new Instant(2)),
                    TimestampedValue.of(""a:3"", new Instant(3)))
            .advanceWatermarkToInfinity();

    PCollection&lt;KV&lt;String, String&gt;&gt; result = p
            .apply(stream)
            .apply(ParDo.of(new KeyElements()))
            .apply(ParDo.of(new TimerDoFn()));

    PAssert.that(result).containsInAnyOrder(
            KV.of(""a"", ""0_output""),
            KV.of(""a"", ""1_output""),
            KV.of(""a"", ""2_output""),
            KV.of(""a"", ""3_output""));

    p.run();
}
</code></pre>

<p>The above test would halt if input elements are <code>a:1, b:2, c:3, d:4</code>.</p>
",https://stackoverflow.com/questions/49266481/unit-test-hangs-forever-if-dofn-resets-event-timers,"['google-cloud-dataflow', 'apache-beam']",247,FALSE,0,0
Mock pyodbc connection,"<p>I have the following snippet for my class.</p>

<pre><code>class Sql_Workflow_Connector():

def __init__(self, server, database, username, password, sql_driver):
    self.server = server
    self.database = database
    self.username = username
    self.password = password
    self.conn = pyodbc.connect(driver=sql_driver, server=self.server,
                               port=1433, database=self.database, uid=self.username, pwd=self.password)
    self.cursor = self.conn.cursor()
</code></pre>

<p>I would like to start unit testing using pytest for this.</p>

<p>I need to mock out the connection and the cursor.
How do I go about doing this? As I would like to test <strong>init</strong> and the following calls sql functions using the mock connection and cursor.</p>

<p>Currently I my implemtation is </p>
",https://stackoverflow.com/questions/53733226/mock-pyodbc-connection,"['python', 'mocking', 'pyodbc']",3139,TRUE,0,1
"Picocli: how to access subcommands after parseWithHandler(new RunAll(), args)?","<p>I have a command with subcommands, which are registered declaratively, and I'm interested in using this style of command line processing:</p>

<pre class=""lang-java prettyprint-override""><code>List&lt;Object&gt; parsed = commandLine.parseWithHandler(new RunAll(), args);
</code></pre>

<p>However, for unit testing purposes, I want to access the subcommand object to see if it has the correct options set, etc. Is there a way to access the subcommand object when using <code>RunAll</code>?</p>

<p><em>(See also <a href=""https://github.com/remkop/picocli/issues/489"" rel=""nofollow noreferrer"">https://github.com/remkop/picocli/issues/489</a> )</em></p>
",https://stackoverflow.com/questions/52444725/picocli-how-to-access-subcommands-after-parsewithhandlernew-runall-args,"['command-line-interface', 'command-line-arguments', 'picocli']",266,FALSE,0,1
How to mock Instance DAO methods using PowerMock+EasyMock+Junit+Java,"<p>I am new to Unit Testing, got some requirement to mock DAO layer but not getting how to do it.
Below is my sample DAO code which is doing some transactional activities.</p>

<pre><code> Class DAOList{
 public Object getRows(Map mapObj, Object error) {
    Session session = HibernateSessionManager.getSessionFactory().openSession();
    try {
        Query query = session.createSQLQuery(""select * from some_table "").addEntity(SomeObject.class);
        Object getObj = query.uniqueResult();
        return getObj;
    }

    catch (HibernateException exc) {
        exc.printStackTrace();
        logger.error(""Exception occurred: "" + exc.getMessage());
    }

    finally {
        session.close();
    }
    return null;
}   }
</code></pre>

<p>I tried writing test case like below but I am getting Runtime exception</p>

<pre><code>    @TestSubject 
    Session sessionn;

    @Mock 
    Transaction transaction;

    @MockSession 
    session;

    @MockSQLQuery
    mockQuery;

    @Test
public void testSomeSuccessCheck() throws Exception {
    HashMap map = new HashMap();

    EasyMock.expect(HibernateSessionManager.getSessionFactory().openSession()).andReturn(sessionn);
    EasyMock.expect(session.beginTransaction()).andReturn(transactionn);
    EasyMock.expect(session.createSQLQuery(EasyMock.anyString()).addEntity(VehicleDetails.class)).andReturn(query);
    EasyMock.expect((SomeObject) query.uniqueResult()).andReturn(someObj);

    SomeObject respObj = vehDao.someMethod(map, errs);
    assertNotNull(respObj);
}
</code></pre>

<p>Complete Error Trace which I got:</p>

<p>java.lang.RuntimeException: Invoking the beforeTestMethod method on PowerMock test listener org.powermock.api.extension.listener.AnnotationEnabler@5c87bfe2 failed.</p>

<pre><code>Caused by: java.lang.NullPointerException: Have you forgotten to instantiate connection?
at org.easymock.internal.Injector.injectMocks(Injector.java:81)
at org.easymock.EasyMockSupport.injectMocks(EasyMockSupport.java:528)
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.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:790)
at org.powermock.reflect.Whitebox.invokeMethod(Whitebox.java:466)
at org.powermock.api.extension.listener.AnnotationEnabler.beforeTestMethod(AnnotationEnabler.java:73)
at org.powermock.tests.utils.impl.PowerMockTestNotifierImpl.notifyBeforeTestMethod(PowerMockTestNotifierImpl.java:82)
</code></pre>
",https://stackoverflow.com/questions/48949504/how-to-mock-instance-dao-methods-using-powermockeasymockjunitjava,"['java', 'junit', 'dao', 'powermock', 'easymock']",638,FALSE,-1,1
Getting connection string of db connection,"<p>I'm trying to test this function:</p>

<pre><code>//OpenConnection opens a connection to a MySQL database by `connStr`
// or returns error. If `connStr` is empty, error is returned.
//
// Parameters:
// - `connStr`: the URL of the database to connect to
// - `interpolateParams` : should we interpolate parameters?
//
// Returns:
// - pointer to the database connection
// - any errors that happened during this process
func OpenConnection(connStr string, interpolateParams bool) (*sql.DB, *errors.ErrorSt) {
    if connStr == """" {
        return nil, errors.Database().ReplaceMessage(""No database connection string."")
    }
    connStr = connStr + ""?parseTime=true&amp;multiStatements=true""
    if interpolateParams {
        connStr += ""&amp;interpolateParams=true""
    }

    db, err := sql.Open(""mysql"", connStr)
    if err != nil {
        return nil, errors.Database().AddDetails(err.Error(), connStr)
    }
    return db, nil
}
</code></pre>

<p>for the case of <code>interpolateParams</code>. I'm sifting through <a href=""https://golang.org/pkg/database/sql"" rel=""nofollow noreferrer"">the official documentation</a> and see no simple way to get the connection string from an <code>sql.DB</code>. Since this is unit testing, I am, of course, hitting the function with a fake connection URL. </p>

<p><strong>Is there a way to get the connection URL from <code>sql.DB</code> to check for the interpolation query string?</strong></p>
",https://stackoverflow.com/questions/51952530/getting-connection-string-of-db-connection,"['unit-testing', 'go']",2595,FALSE,0,1
Can JMockit mock constructors with any argument?,"<p>I am replacing PowerMock with JMockit in old unit testing case.
Below is the PowerMock sample code which mock  the File.class  constructors with  any argument .</p>

<p>Can JMockit   mock  constructors  with  any argument like it ?</p>

<p>The situation is this:myFile is a mock. And  I want to simulate returning myFile when calling any constructor in the File class..So What  is the code like.</p>

<pre><code>// PowerMock
  whenNew(File.class).withAnyArguments().thenReturn(myfile);

// JMockit
 new Expectations() {{
        new File(anyString);
        result = myfile;
        minTimes = 0;
    }};
</code></pre>
",https://stackoverflow.com/questions/53646563/can-jmockit-mock-constructors-with-any-argument,"['unit-testing', 'powermock', 'jmockit']",173,FALSE,0,0
MSCRM QueryExpression returning null in UnitTest,"<p>I am trying to return the first entity that has a value within a value. The only way I can test it is via Unit Testing and they fail every time because its returning null. Not an empty EntityCollection but null. What am I doing wrong here. I just can't see it? ec = null and throws an error when trying to get FirstOrDefault</p>

<pre><code>QueryExpression query = new QueryExpression()
{
    EntityName = ""myentity"",
    ColumnSet = new ColumnSet(true),
    Criteria = new FilterExpression
    {
        FilterOperator = LogicalOperator.And,
        Conditions = 
        {
            new ConditionExpression(""myattribute"", ConditionOperator.Like, ""%"" +somevalue+ ""%"")
        }
    }
};

EntityCollection ec = service.RetrieveMultiple(query);
return ec.Entities.FirstOrDefault();
</code></pre>
",https://stackoverflow.com/questions/50788553/mscrm-queryexpression-returning-null-in-unittest,"['c#', 'dynamics-crm']",284,TRUE,0,1
AssertError: expeced to be called once but was called 0 times,"<p>I am using nodejs and sinon.</p>

<p>Current, when I run my application, i.e. UpdateTask class, it is working fine, even errors.</p>

<p>However when I start doing my unit testing, I faced the following issue.</p>

<pre><code>AssertError: expected updateBook to be called once but was called 0 times
</code></pre>

<p>I don't get it why it is called 0 times where it is supposed to once.</p>

<p>Is there anything wrong that I have done in my code?</p>

<p>UpdateTask Class:</p>

<pre><code>function updateInfo() {

    let updateCountParams = [];
    let updateParams = [];

    let idsToUpdateList = null;

    tempTable.getBookForUpdateCount(updateCountParams, function (results) {

        if (results[0].RECCOUNT &gt; 0) {

            tempTable.getBookForUpdate(updateParams, function (results) {

                idsToUpdateList = results;

                for (var i = 0; i &lt; idsToUpdateList.length; i++) {
                    let id = idsToUpdateList[i].id;

                    let param = [];
                    param.push(id);

                    let request = api.sendRequest(id);

                    // Invoke asynchronous call
                    request
                        .buffer(true)
                        .end(function (err, res) {

                            if (err) {

                                tempTable.updateBook(param, function (updateBookResult) {

                                });

                                return console.error(err.status + "" - "" + err.message);
                            }

                            let data = {
                                body: res.body,
                                text: res.text
                            };

                            let bkData = data.text;

                            if (bkData == undefined || bkData == null) {

                                tempTable.updateBook(param, function (updateBookResult) {

                                });

                                return console.error(""DATA NOT FOUND"".red);
                            }

                            //success flow business logic here
                            ...


                        }); //end asynchronous call
                }
            });
        }
        else {
            //no record to be processed.
            return;
        }
    });
}
</code></pre>

<p>test case:</p>

<pre><code>    describe('Update Task', () =&gt; { 
    beforeEach(() =&gt; {

    });

    afterEach(() =&gt; {
        sinon.restore();
    });


    it('3. API Call - Errror: 404 - Not found', (done) =&gt; {

        let getTempTableForUpdateCountSpy = sinon.stub(TempTableDao, ""getBookForUpdateCount"").yields(jsonResult.count.success.result);
        let getTempTableForUpdateSpy = sinon.stub(TempTableDao, ""getBookForUpdate"").yields(jsonResult.single.failure.result);
        let getTempTableUpdateSpy = sinon.stub(TempTableDao, ""updateBook"");

        let test = nock('https://test.api.com/id')
                .get('/ID125125/')
                .reply(404, {

                 });

        updateTask.updateInfo();

        sinon.assert.calledOnce(getTempTableForUpdateCountSpy);
        sinon.assert.calledOnce(getTempTableForUpdateSpy);
        test.interceptors[0].statusCode.should.be.equal(404);
        sinon.assert.calledOnce(getTempTableUpdateSpy);

        done();
    });
</code></pre>
",https://stackoverflow.com/questions/53220383/asserterror-expeced-to-be-called-once-but-was-called-0-times,"['node.js', 'unit-testing', 'sinon']",5556,TRUE,3,1
TypeError: _this.handler.handle is not a function error,"<p>I am getting this error that this.handler.handle is not a function in my unit testing in Angular 6 using karma/jasmine. This error comes up in my command line when I type the 'ng test' command in my project folder. </p>

<pre><code>Chrome 67.0.3396 (Windows 10.0.0) AppComponent should create FAILED    
Failed: _this.handler.handle is not a function
TypeError: _this.handler.handle is not a function
</code></pre>

<p>for a test that should create AppComponent here is my .spec file</p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { FormsModule, FormBuilder } from '@angular/forms';
import { HttpClientModule, HttpClient, HttpHandler } from '@angular/common/http';
describe('AppComponent', () =&gt; {
  let component: AppComponent;
  let fixture: ComponentFixture&lt;AppComponent&gt;;
  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [FormsModule, RouterTestingModule, HttpClientModule],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
      declarations: [AppComponent],
      providers: [HttpClientModule, HttpClient, HttpHandler]
    }).compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', async(() =&gt; {
    expect(component).toBeTruthy();
  }));
});
</code></pre>

<p>And here is my app.component.ts file </p>

<pre><code>import { Component, ViewChild, OnInit } from '@angular/core';
import { AuthorizationService } from 'src/app/authorization.service';
import { Router } from '@angular/router';
import { MdcDrawer } from '@angular-mdc/web';
import { tap, catchError } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  @ViewChild(MdcDrawer) sidenav: MdcDrawer;
  flip = false;

  constructor(private router: Router, private authorizationService: AuthorizationService) {
    this.authorizationService.getAuthorization().subscribe();
  }

  toggleState() {
    if (this.flip) {
      this.flip = false;
    } else {
      this.flip = true;
    }
  }

  goToPage(route: String) {
    this.router.navigate([route]).catch(err =&gt; {
      console.log(err);
    });
    this.sidenav.close();
  }

  close() {
    console.log('CLOSE');
    this.sidenav.close();
  }
}
</code></pre>

<p>And here is my app.module.ts file: </p>

<pre><code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { HttpModule } from '@angular/http';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { LayoutModule } from '@angular/cdk/layout';
import * as MATERIAL_MODULES from '@angular/material/';
import * as MDC_MODULES from '@angular-mdc/web';
import { TrackUpdateComponent } from './track-update/track-update.component';
import { TrackUpdatePromptComponent } from './track-update-prompt/track-update-prompt.component';
import { NavigationBarComponent } from './navigation-bar/navigation-bar.component';
import { ActionToolbarComponent } from './action-toolbar/action-toolbar.component';
import { SaveButtonToolbarComponent } from './save-button-toolbar/save-button-toolbar.component';
import { HttpClientModule, HttpClient, HTTP_INTERCEPTORS } from '@angular/common/http';
import { EquipmentCardComponent } from './equipment-card/equipment-card.component';
import { EquipmentCardListComponent } from './equipment-card-list/equipment-card-list.component';
import { ListOptionsComponent } from './list-options/list-options.component';
import { EquipmentCardLoadingComponent } from './equipment-card-loading/equipment-card-loading.component';
import { GoToTopComponent } from './go-to-top/go-to-top.component';
import { TapActionListComponent } from './tap-action-list/tap-action-list.component';
import { JumpActionComponent } from './jump-action/jump-action.component';
import { GlobalErrorsComponent } from './global-errors/global-errors.component';
import { SwitchActionListComponent, AssignTrackForm } from './switch-action-list/switch-action-list.component';
import { AddActionComponent } from './add-action/add-action.component';
import { ErrorHandler } from './global-errors/error_handler';
import { RequestInterceptor } from './global-errors/http_interceptor';
import { ActionService } from './action.service';
import { TrackIdService } from './track-id-service.service';
import { TrackInquiryService } from './track-inquiry.service';
import { UserPreferenceService } from './user-preference.service';
import { AuthorizationService } from './authorization.service';
import { EquipmentInsertCardComponent } from './equipment-insert-card/equipment-insert-card.component';
import { LoadingIconComponent } from './loading-icon/loading-icon.component';

@NgModule({
  declarations: [
    AppComponent,
    TrackUpdatePromptComponent,
    NavigationBarComponent,
    TrackUpdateComponent,
    ActionToolbarComponent,
    SaveButtonToolbarComponent,
    EquipmentCardComponent,
    EquipmentCardListComponent,
    ListOptionsComponent,
    EquipmentCardLoadingComponent,
    GoToTopComponent,
    TapActionListComponent,
    JumpActionComponent,
    GlobalErrorsComponent,
    SwitchActionListComponent,
    AssignTrackForm,
    AddActionComponent,
    EquipmentInsertCardComponent,
    LoadingIconComponent
  ],
  entryComponents: [GlobalErrorsComponent, AssignTrackForm],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    LayoutModule,
    FormsModule,
    ReactiveFormsModule,
    HttpClientModule,
    MDC_MODULES.MdcButtonModule,
    MDC_MODULES.MdcCheckboxModule,
    MDC_MODULES.MdcFormFieldModule,
    MDC_MODULES.MdcToolbarModule,
    MDC_MODULES.MdcIconModule,
    MDC_MODULES.MdcListModule,
    MDC_MODULES.MdcSelectModule,
    MDC_MODULES.MdcAppBarModule,
    MDC_MODULES.MdcIconToggleModule,
    MDC_MODULES.MdcDrawerModule,
    MDC_MODULES.MdcTextFieldModule,
    MDC_MODULES.MdcDialogModule,
    MATERIAL_MODULES.MatButtonModule,
    MATERIAL_MODULES.MatCheckboxModule,
    MATERIAL_MODULES.MatMenuModule,
    MATERIAL_MODULES.MatIconModule,
    MATERIAL_MODULES.MatTableModule,
    MATERIAL_MODULES.MatCardModule,
    MATERIAL_MODULES.MatInputModule,
    MATERIAL_MODULES.MatSelectModule,
    MATERIAL_MODULES.MatToolbarModule,
    MATERIAL_MODULES.MatListModule,
    MATERIAL_MODULES.MatTooltipModule,
    MATERIAL_MODULES.MatSortModule,
    MATERIAL_MODULES.MatDialogModule,
    MATERIAL_MODULES.MatSlideToggleModule,
    MATERIAL_MODULES.MatSidenavModule,
    MATERIAL_MODULES.MatAutocompleteModule,
    MATERIAL_MODULES.MatSnackBarModule,
    MATERIAL_MODULES.MatExpansionModule
  ],
  providers: [
    HttpModule,
    HttpClientModule,
    HttpClient,
    ErrorHandler,
    ActionService,
    TrackIdService,
    TrackInquiryService,
    UserPreferenceService,
    AuthorizationService,
    {
      provide: HTTP_INTERCEPTORS,
      useClass: RequestInterceptor,
      multi: true
    }
  ],
  bootstrap: [AppComponent],
  schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class AppModule {}
</code></pre>

<p>Can someone please help with this? I would appreciate it. </p>
",https://stackoverflow.com/questions/51364455/typeerror-this-handler-handle-is-not-a-function-error,"['angular', 'karma-jasmine', 'httphandler']",12680,TRUE,9,3
How can I unit test the method having else condition?,"<p>I am new to unit testing. I want to test a method which uploads a profile picture for the user. I want to know how can I test <strong>else path</strong> in the following method:</p>

<pre><code>[HttpPost]
[Route(""profilePicture"")]
public async Task&lt;IActionResult&gt; UpsertUserProfilePictureAsync([FromForm]IFormFile file)
{
    var postedFile = Request.Form.Files.FirstOrDefault();
    if (user.ProfilePictureUrl == null)
    {
        await _contentUploadService.UploadProfilePictureAsync(postedFile.ContentType, user, postedFile.OpenReadStream());
    }
    else
    {
        var existingImageUrl = user.ProfilePictureUrl;
        await _contentUploadService.UploadProfilePictureAsync(postedFile.ContentType, user, postedFile.OpenReadStream());
        var blob = new CloudBlockBlob(new Uri(existingImageUrl), _storageCredentials);
        await blob.DeleteAsync();
    }
    return StatusCode(StatusCodes.Status204NoContent);
}
</code></pre>

<p>I am using a mock file but I don't know how to check <strong>else part</strong> of the file. Can any body help me in this case...</p>
",https://stackoverflow.com/questions/52549457/how-can-i-unit-test-the-method-having-else-condition,"['c#', 'unit-testing']",159,FALSE,0,2
Use Rhino Mocking to unit test delete functionality,"<p>I am using Rhino mocking for unit testing to test a method that deletes  a transport.However I am unsure how to test it. Below is what I have but it is failing (Assert.AreEqual is failing as result comes back with an exception object reference not set to instance of an object )</p>

<pre><code>    /// &lt;summary&gt;
   /// Test Case: to
   /// &lt;/summary&gt;
    [TestMethod]
    public void Should_DeleteTransload()
    {
        //expect
        mockTransloaderRepository.Expect(r =&gt; r.GetOneAsync(x =&gt; x.Id == ostTransloader5.Id)).IgnoreArguments().Return(Task.FromResult(ostTransloader5));
        mockOstTransloaderService = MockRepository.GenerateMock&lt;OstTransloaderService&gt;(mockTransloaderRepository, mockAuditContext);
        mockTransloaderRepository.Expect(r =&gt; r.AddAsync(ostTransloader5)).IgnoreArguments().Return(Task.Run(() =&gt; true));
        mockTransloaderRepository.Expect(r =&gt; r.AddAsync(ostTransloader4)).IgnoreArguments().Return(Task.Run(() =&gt; true));
        List&lt;OstTransloader&gt; ostTransloaders = new List&lt;OstTransloader&gt;() { ostTransloader4 };

        mockTransloaderRepository.Expect(t =&gt; t.DeleteAsync(ostTransloader5)).IgnoreArguments().Return(Task.Run(() =&gt; true));
        ////act
        var result = mockOstTransloaderService.PurgeTransloadShipmentMaterial(transloadIds);
        //// assert
        Assert.IsNotNull(result);
        Assert.AreEqual(ostTransloaders, result);           

    }
</code></pre>

<p>How do I test that the correct transload has been deleted?</p>
",https://stackoverflow.com/questions/52977355/use-rhino-mocking-to-unit-test-delete-functionality,"['c#', 'unit-testing', 'rhino-mocks']",85,TRUE,0,1
overloading operator == for pods,"<p>I am working on some low level code with high level interfaces and felt need for comparisons operator for unit testing for plain old data types(like FILETIME struct) but since C++ doesn't even provide memberwise comparisons, so I wrote this:</p>

<pre><code>template &lt;typename Type&gt;
std::enable_if_t&lt;std::is_pod&lt;Type&gt;::value, bool&gt; operator==(const Type&amp; a,
                                                            const Type&amp; b) {
  return std::memcmp(&amp;a, &amp;b, sizeof(Type)) == 0;
}
</code></pre>

<p>So my question is, is this a good way or there are some hidden demons which will give me trouble later down the development cycle but it's kinda working for now.</p>
",https://stackoverflow.com/questions/50667027/overloading-operator-for-pods,"['c++', 'templates', 'memory', 'template-meta-programming', 'memcmp']",648,TRUE,9,2
cloudstorage&#39;s copy2 method throwing No api proxy found for service &quot;memcache&quot;,"<p>I am NOT doing unit testing.</p>

<p>I am just running following 2 commands on my Windows10 machine with Python2.7 and I am getting the infamous assertion error: </p>

<blockquote>
  <p>No api proxy found for service ""memcache""</p>
</blockquote>

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

<pre><code>import cloudstorage as cstorage
cstorage.copy2(""/nosuchbucket/nosuchfile1"",""/nosuchbucket/nosuchfile2"")
</code></pre>

<p>Any pointers on what could be wrong?</p>

<p>Environment:</p>

<ul>
<li>Google Cloud SDK 202.0.0</li>
<li>app-engine-python 1.9.70</li>
<li>app-engine-python-extras 1.9.69</li>
<li>Python 2.7.14</li>
</ul>
",https://stackoverflow.com/questions/50525036/cloudstorages-copy2-method-throwing-no-api-proxy-found-for-service-memcache,"['python-2.7', 'google-cloud-platform', 'google-app-engine-python', 'cloud-storage']",209,TRUE,0,2
How to call ResolveCustomer and GetEntitlements from aws-marketplace using aws-sdk-go?,"<p>I need to call ResolveCustomer and GetEntitlements services using aws-sdk-go. There is no code samples available on how to configure the aws clients for such calls.</p>

<p>Can someone help with the go code examples?</p>

<p>It will be helpful if someone has done unit testing for such calls; in terms of how to mock the ResolveCustomer and GetEntitlements API calls in golang?</p>
",https://stackoverflow.com/questions/49329996/how-to-call-resolvecustomer-and-getentitlements-from-aws-marketplace-using-aws-s,"['aws-sdk-go', 'aws-marketplace']",350,FALSE,0,1
Junit test case fail 400 bad request,"<p>I am using <code>junit</code> for unit testing in <code>spring data jpa</code> application. I am trying to write junit test cases for controller class unclaimedRoomAssign() . I am using <code>mockito</code> for creating mock object. </p>

<p>I tried to write test like below but I am getting test fail 400 bad request. can any one tell me what I am missing in test cases</p>

<p><strong>RoomDepartmentMappingController  class</strong></p>

<pre><code>   public class RoomDepartmentMappingController {

    @Autowired
    RoomDepartmentMappingService rdmService;

    @PostMapping(""/assignUnclaimedRooms"")
    public ResponseEntity&lt;String&gt; unclaimedRoomAssign(@NotNull  @RequestParam(name=""nDeptId"", required= true) Integer nDeptId,
                                                      @NotNull  @RequestParam(name=""nRoomId"" , required = true) Integer nRoomId,
                                                      @Nullable @RequestParam(name=""nSubDeptId"" , required = false) Integer nSubDeptId){

        return ResponseEntity.ok(rdmService.unclaimedRoomAssign(nDeptId, nRoomId,nSubDeptId ));

}
</code></pre>

<p><strong>TestRoomDepartmentMappingController class</strong></p>

<pre><code>@RunWith(SpringRunner.class)
@ContextConfiguration(classes = RoomDepartmentMappingController.class)
@WebMvcTest(value = RoomDepartmentMappingController.class)
public class TestRoomDepartmentMappingController {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    RoomDepartmentMappingService roomDepartmentMappingService;

    @Value(""${InstituteIdentifier}"")
    String instituteIdentifier;

    @Test
    public void UnclaimedRoomAssignTest() throws Exception {

        String stringUrl=""/spacestudy/""+ instituteIdentifier+""/asset/room/assignUnclaimedRooms"";

        String stringResult = ""Room assign sucessfully"";        

        Department dep = new Department();
        dep.setnDeptId(1);


        RoomDepartmentMapping rdmObj = new RoomDepartmentMapping();     
                              rdmObj.setnRoomAllocationId(587050);
                              rdmObj.setnDeptId(1);
                              rdmObj.setnRoomId(1215783);

        String inputInJson = mapToJson(rdmObj);     

        Mockito.when(roomDepartmentMappingService.unclaimedRoomAssign(1, 1215783, 0)).thenReturn(stringResult);         

        mockMvc.perform(post(stringUrl)
               .accept(MediaType.APPLICATION_JSON)
               .content(inputInJson)
               .contentType(MediaType.APPLICATION_JSON))
               .andExpect(status().isOk());


     Mockito.verify(roomDepartmentMappingService).unclaimedRoomAssign(1, 1215783, 0);
    }

    private String mapToJson(Object object) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(object);

    }
}
</code></pre>

<p><strong>Console</strong></p>

<pre><code> MockHttpServletRequest:
          HTTP Method = POST
          Request URI = /spacestudy/vcufy2010/asset/room/assignUnclaimedRooms
           Parameters = {}
              Headers = {Content-Type=[application/json], Accept=[application/json]}
                 Body = &lt;no character encoding set&gt;
        Session Attrs = {}

    Handler:
                 Type = com.spacestudy.controller.RoomDepartmentMappingController
               Method = public org.springframework.http.ResponseEntity&lt;java.lang.String&gt; com.spacestudy.controller.RoomDepartmentMappingController.unclaimedRoomAssign(java.lang.Integer,java.lang.Integer,java.lang.Integer)

    Resolved Exception:
                 Type = org.springframework.web.bind.MissingServletRequestParameterException


    MockHttpServletResponse:
               Status = 400
        Error message = Required Integer parameter 'nDeptId' is not present
</code></pre>
",https://stackoverflow.com/questions/52558302/junit-test-case-fail-400-bad-request,"['spring-data-jpa', 'mockito', 'junit4']",9118,TRUE,0,1
Specflow Editor not working in Feature file after the latest,"<p>We are using Visual Studio 2017 and using Specflow as unit testing tool.
We have added ""Specflow for Visual Studio 2017"" as extension so that we have the editor in feature file.</p>

<p>Everything was working fine as expected and we were able to edit feature file. However after there was some upgrade from Specflow side, the editor is now not working</p>

<p>Any inputs ?</p>
",https://stackoverflow.com/questions/49569613/specflow-editor-not-working-in-feature-file-after-the-latest,['specflow'],223,FALSE,0,0
Getting Errors on ng test command ( KARMA - JASMINE unit tests),"<p>In my Application, I was integrating Angular cli as first it was not there!</p>

<p>I want to test my Application with karma and jasmine.</p>

<p>When I run the command <code>ng test</code>, I get errors:</p>

<h3><code>package.json</code>:</h3>

<pre><code>@angular/cli: 1.1.0
node: 7.10.1
os: linux x64
@angular/animations: 4.4.6
@angular/common: 4.4.6
@angular/compiler: 4.4.6
@angular/core: 4.4.6
@angular/forms: 4.4.6
@angular/http: 4.4.6
@angular/platform-browser: 4.4.6
@angular/platform-browser-dynamic: 4.4.6
@angular/router: 4.4.6
@angular/service-worker: 1.0.0-beta.16
@angular/cli: 1.1.0
@angular/compiler-cli: 4.4.6
@angular/language-service: 4.4.6
@angular/platform-server: 4.4.6
</code></pre>

<h3>Observed behavior</h3>

<pre><code>ERROR in /repo/node_modules/@angular/core/src/di/reflective_provider.d.ts (87,123): Cannot find name 'Map'.

ERROR in /repo/node_modules/@angular/core/src/di/reflective_provider.d.ts (87,165): Cannot find name 'Map'.

ERROR in /repo/node_modules/rxjs/Observable.d.ts (58,60): 'Promise' only refers to a type, but is being used as a value here.

ERROR in /repo/node_modules/rxjs/Observable.d.ts (73,59): 'Promise' only refers to a type, but is being used as a value here.

ERROR in /repo/node_modules/@angular/core/src/change_detection/differs/iterable_differs.d.ts (15,48): Cannot find name 'Iterable'.

ERROR in /repo/node_modules/@angular/core/src/change_detection/differs/keyvalue_differs.d.ts (23,18): Cannot find name 'Map'.

ERROR in /repo/node_modules/@angular/core/src/change_detection/differs/default_iterable_differ.d.ts (28,32): Cannot find name 'Iterable'.

ERROR in /repo/node_modules/@angular/core/src/change_detection/differs/default_keyvalue_differ.d.ts (24,16): Cannot find name 'Map'.

ERROR in /repo/node_modules/@angular/core/src/change_detection/differs/default_keyvalue_differ.d.ts (32,16): Cannot find name 'Map'.

ERROR in /repo/src/client/app/iterm-extended/component/get-a-quote.component.ts (32,14): Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning.
</code></pre>

<h3>Desired behavior</h3>

<p>I want to see on the browser for <strong>UNIT TESTING</strong>.</p>

<p>Because of these errors, I can't Test.</p>

<p>Even on StackOverflow, I did not find anything related to these ERRORS. </p>

<h3>tsconfig.json</h3>

<pre><code>{
  ""compilerOptions"": {
    // ""module"": ""es2015"",
    ""moduleResolution"": ""node"",
    ""target"": ""es5"",
    ""noImplicitAny"": false,
    ""sourceMap"": true,
    ""emitDecoratorMetadata"": true,
    ""experimentalDecorators"": true,
    ""lib"": [
      ""es2017"",
      ""dom""
    ],
    ""typeRoots"": [
      ""node_modules/@types""
    ],
    ""skipLibCheck"": true
  },
  ""include"": [
    ""src/client/**/*.ts""
  ],
  ""exclude"": [
    ""node_modules"",
    ""src/client/main-prod.ts""
  ],
  ""compileOnSave"": false
}
</code></pre>

<h3>karma.config.js</h3>

<pre><code>module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular/cli'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular/cli/plugins/karma')
    ],
    files: [
      ""src/client/test-cases/iterm-extended/**/*.spec.ts"",
      { pattern: 'node_modules/**', included: false, watched: false },
      { pattern: 'src/client/app/iinvest/**', included: false, watched: false },
      { pattern: 'src/client/app/imax/**', included: false, watched: false },
      { pattern: 'src/client/app/iterm/**', included: false, watched: false },
      { pattern: 'src/client/app/itermPlus-extended/**', included: false, watched: false },
      { pattern: 'src/client/app/pages/**', included: false, watched: false },
      { pattern: 'src/client/app/shared/**', included: false, watched: false }
    ],
    client: {
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    coverageIstanbulReporter: {
      reports: ['html', 'lcovonly'],
      fixWebpackSourcePaths: true
    },
    angularCli: {
      environment: 'dev'
    },
    reporters: ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
  });
};
</code></pre>
",https://stackoverflow.com/questions/49645368/getting-errors-on-ng-test-command-karma-jasmine-unit-tests,"['angular', 'unit-testing', 'typescript', 'angular-cli', 'karma-jasmine']",810,FALSE,3,0
Check if two objects have equal content in Pytest,"<p>I'm learning how to use Pytest (and unit testing in general) and I would like to write a test to check if two objects of the same class have identical attributes.</p>

<p>Example:</p>

<pre><code>class Something(object):
    def __init__(self, a, b):
        self.a, self.b = a, b

    def __repr__(self):
        return 'Something(a={}, b={})'.format(self.a, self.b)

def test_equality():
    obj1 = Something(1, 2)
    obj2 = Something(1, 2)
    assert obj1.a == obj2.a
    assert obj1 == obj2
</code></pre>

<p>This test fails with AssertionError on third assert:</p>

<pre><code>    def test_equality():
        obj1 = Something(1, 2)
        obj2 = Something(1, 2)
        assert obj1.a == obj2.a
        assert obj1.b == obj2.b                                                                                                                                                                                                               
&gt;       assert obj1 == obj2                                                                                                                                                                                                                   
E       assert Something(a=1, b=2) == Something(a=1, b=2)                                                                                                                                                                                     

tests/test_model.py:13: AssertionError
</code></pre>

<p>It is possible in Python or Pytest to use just <code>assert obj1 == obj2</code>? Should I implement ""rich comparison"" methods for each class I would like to test that way or there is some simpler way?</p>
",https://stackoverflow.com/questions/48753967/check-if-two-objects-have-equal-content-in-pytest,"['python', 'pytest']",18343,TRUE,8,1
How to test global.i18n.t,"<p>Google analytics has been added to the component in ReactJS and how to test since its giving undefined error while testing it.</p>

<pre><code>render() {
return (
  &lt;div className='form-wrapper'&gt;
    &lt;h2 className='register-form-title'&gt;{global.i18n.t('great_offers.title')}&lt;/h2&gt;
    &lt;OTPForm
      otpChange={this._otpChange}
      errorMessage={this.state.error}
      handleSubmit={this._handleSubmit}
      valid={this.state.valid}
    /&gt;
  &lt;/div&gt;
);
  }
</code></pre>

<p>In the above code while doing unit testing it says ""can't read property t of undefined"".So is there any way to initialize it to something in start.Moreover global.i18n.t isn't a valid variable name in JS ,so I can't initialize it also.</p>
",https://stackoverflow.com/questions/51820884/how-to-test-global-i18n-t,"['reactjs', 'jestjs', 'enzyme']",1067,TRUE,2,1
Verify method signatures before swizzling,"<p>I have been using method swizzling to swap implementations for unit testing. However, I am concerned that if the production code's method signatures change due to parameter changes, the unit tests will compile without error and testing run-time behavior could be unstable.</p>

<p>So, is there any compile-time or even run-time way to confirm that the signatures of two Objective-C methods are the same?</p>
",https://stackoverflow.com/questions/53732682/verify-method-signatures-before-swizzling,"['objective-c', 'method-signature', 'swizzling']",91,TRUE,2,1
Angular 7 karma test with importing external JS modules,"<p>I am testing a Angular 7 component which has importing JS modules like:</p>

<p>component.ts</p>

<pre><code>import * as classA from '../../classA'; // Imported JS modules
export class component implements OnInit {
  public a = new classA(10); // Instantiate
  ...
}
</code></pre>

<p>classA.js</p>

<pre><code>class classA {
  constructor (a) {
    this.max = a;
    ...
}

if (typeof module !== 'undefined' &amp;&amp; typeof module.exports !== 'undefined') {
    module.exports = classA;
}
</code></pre>

<p>component.spec.ts</p>

<pre><code>import * as classA from '../../classA';
</code></pre>

<p>I am importing classA as what I did in component.ts. </p>

<p>Component.ts is working perfectly but when I am running ng test, it gives an error: <code>TypeError: classA is not a constructor</code></p>

<p>I tried to include it in karma.conf.js like:</p>

<pre><code>module.exports = function (config) {
  config.set({
    ...
    files: [
      ""../app/classA.js""
    ]
  });
};
</code></pre>

<p>But still get same error. Anyone has any idea how to import JS modules in unit testing? </p>
",https://stackoverflow.com/questions/53618055/angular-7-karma-test-with-importing-external-js-modules,"['javascript', 'angular', 'karma-jasmine', 'karma-runner', 'angular7']",1095,TRUE,1,2
Sinon how to unit test a non exported private functionality?,"<p>Im really new to unit testing, im trying to mock <code>aws.ses</code> method using <code>sinon.js</code>, but my concern is how im calling the <code>sesConstructor</code> method. Since it is not getting exported from <code>ses.js</code>, ive declared a <code>sesConstructor</code> method inside the test suite. </p>

<p>Would really appreciate if anyone could tell me whether this is a complete anti-pattern and whether there are any other better solution for this (without using 'rewire' module)</p>

<p>ses.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>let ses = {};

const sesConstructor = () =&gt; {
  AWS.config.update({
    accessKeyId: configurations.AWS_CONFIG.ACCESSKEYID,
    secretAccessKey: configurations.AWS_CONFIG.SECRECTACCESSKEY,
    region: configurations.AWS_CONFIG.REGION
  });
  ses = new AWS.SES({ apiVersion: ""2010-12-01"" });
};

export const sendTemplatedEmail = (emailTo, templateName, templateData) =&gt; {
  sesConstructor();

  const params = {
    Destination: {
      ToAddresses: emailTo
    },
    Source: process.env.emailSource,
    Template: templateName,
    TemplateData: JSON.stringify(templateData)
  };

  return ses.sendTemplatedEmail(params).promise();
};

export default { sendTemplatedEmail };</code></pre>
</div>
</div>
</p>

<p>ses.test.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>describe(""SES"", () =&gt; {
  const emailTo = [""test@gmail.com""];
  const templateName = ""template"";
  const templateData = ""test"";
  process.env.emailSource = ""test@gamil.com"";
  const sendEmail = sendTemplatedEmail(emailTo, templateName, templateData);

  it(""should return a promise"", () =&gt; {
    expect(sendEmail).to.be.a(""promise"");
  });

  describe(""sesConstructor"", () =&gt; {
    it(""should call AWS SES"", () =&gt; {
      const sesConstructor = data =&gt; {
        const ses = new AWS.SES(data); // eslint-disable-line no-unused-vars
      };

      const mockAWS = sinon.mock(AWS);

      mockAWS
        .expects(""SES"")
        .once()
        .withArgs({
          apiVersion: ""2010-12-01""
        })
        .returns(true);

      sesConstructor({ apiVersion: ""2010-12-01"" });

      mockAWS.verify();
      mockAWS.restore();
    });

   
  });
});</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/50147149/sinon-how-to-unit-test-a-non-exported-private-functionality,"['javascript', 'unit-testing', 'dependency-injection', 'sinon']",164,TRUE,1,1
How can I test a private or fileprivate function in project,"<p>I want to write some unit testing code for a manager class, the function I would write for is using some small <code>private</code> functions. I will prepare a lot if I testing the <code>public</code> function, so I want to test those <code>private</code> functions. But in test target I can't call the private function directly.</p>

<p>So I wanna ask, is there's a way to test them without change them from <code>private</code> to <code>internal</code> or <code>public</code>?</p>
",https://stackoverflow.com/questions/50040270/how-can-i-test-a-private-or-fileprivate-function-in-project,"['ios', 'swift', 'unit-testing']",3199,TRUE,4,4
How to test two redux related components?,"

<p>Suppose there are two components, one is action dispatching class, other one is a state receiving class.</p>

<p>Component1 has a method dispatch a action to change <code>props1</code> redux state, then Component2 receives the props1 from redux state passing it to Component3.</p>

<p>Component1 and Component2 are combined under SuperComponent.</p>

<pre class=""lang-js prettyprint-override""><code>// Component1.js
class Component1 extends React.component {
  method1 = () =&gt; {
    this.props.action1({ props1: something });
  }
  render() {
    return (
      ...
    )
  }
}

export default connect(
  state =&gt; ({ ... }),
  {action1}
)(Component1)


// Component2.js
class Component2 extends React.component {
  render() {
    return (
      &lt;Component3 props1={this.props.props1} /&gt;
    )
  }
}

export default connect(
  state =&gt; ({ props1: state.reducer1.props1 }),
  {}
)(Component2)

const Component3 = ({ props1 }) =&gt; (
  &lt;div props1={props1} &gt;
    ...
  &lt;/div&gt;
)


// SuperComponent
const SuperComponent = () =&gt; {
  &lt;div&gt;
    &lt;Component1&gt;
    &lt;Component2&gt;
  &lt;/div&gt;
}
</code></pre>

<p>How to test this logic by jest and enzyme? Using integrate testing or separated unit testing? Thanks in advance.</p>
",https://stackoverflow.com/questions/51770661/how-to-test-two-redux-related-components,"['reactjs', 'redux', 'react-redux', 'jestjs', 'enzyme']",42,TRUE,1,1
Make a class in Android library accessible only from test code,"<p>I'm about to release my first Android library. As part of that library I supply ""smart"" test double classes for easier unit testing.</p>

<p>Currently I just package the test doubles together with the production classes. However, it's ugly and feels unfriendly to the users.</p>

<p>How can I add classes to Android library that the clients will be able to use only in test code?</p>
",https://stackoverflow.com/questions/51870825/make-a-class-in-android-library-accessible-only-from-test-code,"['android', 'unit-testing', 'android-library']",41,TRUE,1,1
How do I test whether a DbContext is in memory?,"<p>I use <code>.Net Core 2.1.</code> My application uses <code>Entity Framework Core</code>, with a context <code>CoreDbContext</code> that derives from <code>DbContext</code>.</p>

<p>For unit testing, I use an in memory version of <code>CoreDbContext</code>, resulting in this code in my <code>Startup.cs</code>:</p>

<pre><code>if (useInMemoryDatabase)
{
    services.AddDbContext&lt;CoreDbContext&gt;(options =&gt; 
           options.UseInMemoryDatabase(""dbname""));
}
else
{
    services
      .AddDbContext&lt;CoreDbContext&gt;(options =&gt; 
           options.UseSqlServer(DefaultDbConnectionString));
}
</code></pre>

<p>I also have methods that access the database via the context. These sometimes need to know whether the context is in memory or not, because an in memory context behaves differently from a normal one:</p>

<pre><code>void AddRecordX(CoreDbContext context)
{
    bool contextIsInMemory = .....;

}
</code></pre>

<p>How can I test whether a context is in memory or associated with a real <code>SQL Server database</code>?</p>
",https://stackoverflow.com/questions/52848631/how-do-i-test-whether-a-dbcontext-is-in-memory,"['entity-framework', 'entity-framework-core', 'entity-framework-core-2.1']",5968,TRUE,10,2
Compile Conditionals - Best Practices,"<p>I'm unit testing with console apps.  So, anywhere I want to unit test i'm using compile conditionals like so</p>

<pre><code>#if UnitTest
                    Console.WriteLine(""Invoke: Method 1 Result"");
#endif
</code></pre>

<p>This works great, but it makes for messy and ugly code.  How bad would it be, how much of a resource hit would it be, for me to invoke something like below. </p>

<pre><code>    public static class UnitTest
    {
        public static void Add(string value)
        {
#if UnitTest
            Console.WriteLine(value);
#endif
        }
    }
</code></pre>

<p>and then, when ever I want to place a unit test, i simply call.</p>

<pre><code>UnitTest.Add(""Invoke: Method 1 Result"");
</code></pre>
",https://stackoverflow.com/questions/49698281/compile-conditionals-best-practices,"['c#', 'unit-testing']",235,TRUE,0,1
How to unit test code which makes use of ZoneId.systemDefault without raising org.threeten.bp.zone.ZoneRulesException,"<p>I have the following application code.</p>

<h2>Application code</h2>

<pre><code>public static long advanceByMax1HourWithoutOverflow(long currentTimeMillis) {
    ZoneId zoneId = ZoneId.systemDefault();

    ZonedDateTime zonedDateTime = Instant.ofEpochMilli(currentTimeMillis).atZone(zoneId);

    // 0-23
    int hour = zonedDateTime.getHour();

    if (hour &lt; 23) {
        zonedDateTime = zonedDateTime.plusHours(1);
        return zonedDateTime.toInstant().toEpochMilli();
    }

    // 0-59
    int minute = zonedDateTime.getMinute();

    if (minute &lt; 59) {
        zonedDateTime = zonedDateTime.plusMinutes(1);
        return zonedDateTime.toInstant().toEpochMilli();
    }

    return currentTimeMillis;
}
</code></pre>

<hr>

<p>I wrote a unit test for it with the following.</p>

<h2>Unit test code</h2>

<pre><code>@Test
public void advanceByMax1HourWithoutOverflow() {
    /*
    27 October 2018
    1540648800000 -&gt; 1540652400000
    22:00 -&gt; 23:00
    */
    long currentTimeMillis = 1540648800000L;
    long expected = 1540652400000L;
    long output = Utils.advanceByMax1HourWithoutOverflow(currentTimeMillis);
    assertEquals(expected, output);
</code></pre>

<p>I got the following error</p>

<pre><code>org.threeten.bp.zone.ZoneRulesException: No time-zone data files registered
</code></pre>

<p>I tried to fix it by using</p>

<h2>Unit test code</h2>

<pre><code>@Test
public void advanceByMax1HourWithoutOverflow() {
    Context context = mock(Context.class);
    AndroidThreeTen.init(context);

    /*
    27 October 2018
    1540648800000 -&gt; 1540652400000
    22:00 -&gt; 23:00
    */
    long currentTimeMillis = 1540648800000L;
    long expected = 1540652400000L;
    long output = Utils.advanceByMax1HourWithoutOverflow(currentTimeMillis);
    assertEquals(expected, output);
</code></pre>

<p>I'm getting</p>

<pre><code>java.lang.ExceptionInInitializerError
    at org.threeten.bp.ZoneRegion.ofId(ZoneRegion.java:143)
    at org.threeten.bp.ZoneId.of(ZoneId.java:358)
    at org.threeten.bp.ZoneId.of(ZoneId.java:286)
    at org.threeten.bp.ZoneId.systemDefault(ZoneId.java:245)
</code></pre>

<p>Is there any way I can pass the unit test, without changing my current app's method signature? I would like to just retain my current app method signature without any modification.</p>

<pre><code>long advanceByMax1HourWithoutOverflow(long currentTimeMillis)
</code></pre>

<p>Note, the gradle which I use for unit testing are</p>

<pre><code>implementation 'com.jakewharton.threetenabp:threetenabp:1.1.1'

testImplementation 'junit:junit:4.12'
testImplementation 'org.mockito:mockito-core:2.19.0'
</code></pre>
",https://stackoverflow.com/questions/53025980/how-to-unit-test-code-which-makes-use-of-zoneid-systemdefault-without-raising-or,"['java', 'android', 'unit-testing', 'threetenbp']",2817,TRUE,9,1
How to test dynamic react components,"<p>I'm new to unit testing and I am trying to test validation messages on my login form. When the user enters incorrect information and submits the form, an error message component is displayed. When I try to test if this error component exists I get a falsy response. Any help would be appreciated. </p>

<pre><code>onSubmit = () =&gt; {
  const errors = this.validate(this.state.data);
  this.setState({ errors });
  console.log(""test"");
};

validate = data =&gt; {
  const errors = {};
  if (!Validator.isEmail(data.email)) errors.email = ""Invalid Email"";
  if (!data.password) errors.password = ""Password required"";
  return errors;
};

render() {
const { data, errors } = this.state;

return (
  &lt;div&gt;
    &lt;Form onSubmit={this.onSubmit}&gt;
      &lt;Form.Field&gt;
        &lt;label htmlFor=""email""&gt;Email&lt;/label&gt;
        &lt;input
          type=""email""
          id=""email""
          name=""email""
          placeholder=""example@example.com""
          value={data.email}
          onChange={this.onChange}
        /&gt;
        {errors.email &amp;&amp; &lt;InlineError text={errors.email} /&gt;}
      &lt;/Form.Field&gt;
      &lt;Form.Field&gt;
        &lt;label htmlFor=""password""&gt;Password&lt;/label&gt;
        &lt;input
          type=""password""
          id=""password""
          name=""password""
          value={data.password}
          onChange={this.onChange}
        /&gt;
      &lt;/Form.Field&gt;
      &lt;Button type=""submit"" primary&gt;
        Login
      &lt;/Button&gt;
    &lt;/Form&gt;
  &lt;/div&gt;
);
</code></pre>

<p>}</p>

<p>and my LoginForm.test.js file</p>

<pre><code>describe(""user submits form"", () =&gt; {
it(""Returns no errors with correct data"", () =&gt; {
  const data = {
    email: ""dennis@gmail.com"",
    password: ""12345""
  };
  wrapper.find(""Button"").simulate(""click"");
  expect(wrapper.instance().validate(data)).toEqual({});
});

it(""Returns error when error exists"", () =&gt; {
  const data = {
    email: """",
    password: ""12345""
  };
  wrapper.find(""Button"").simulate(""click"");
  expect(wrapper.instance().validate(data)).toEqual({
    email: ""Invalid Email""
  });
});

it(""Displays InlineError when error exists"", () =&gt; {
  const data = {
    email: """",
    password: ""12345""
  };
  wrapper.find(""Button"").simulate(""click"");
  expect(wrapper.contains(&lt;InlineError text=""Invalid Email"" /&gt;)).toBe(true);
});
});
</code></pre>

<p>The first two tests pass however the third one fails</p>
",https://stackoverflow.com/questions/50990228/how-to-test-dynamic-react-components,"['reactjs', 'testing', 'jestjs', 'enzyme']",1495,FALSE,0,1
Target membership fix for unresolved identifier when testing framework,"<p>I have recently created a framework with unit testing. 
The problem is that when Im trying to launch tests, Im getting an error:</p>

<blockquote>
  <p>Use of unresolved identifier 'SessionManager'</p>
</blockquote>

<p>I discovered that problem may be fixed by setting target membership for SessionManager to both targets: framework and tests.</p>

<p>But the question is:</p>

<blockquote>
  <p>How they can work separately?</p>
</blockquote>

<p>Got this in framework seed:</p>

<pre><code>//  SessionManager.swift
//  URLSessionKit

import Foundation

public class SessionManager {
    var name : String
    public init(name: String) {
        self.name = name
    }
}
</code></pre>

<p>and this in tests:</p>

<pre><code>//  URLSessionKitTests.swift
//  URLSessionKitTests

import XCTest
@testable import URLSessionKit

class URLSessionKitTests: XCTestCase {

    func testExample() {
        SessionManager(name: ""someName"")
    }
</code></pre>
",https://stackoverflow.com/questions/50883277/target-membership-fix-for-unresolved-identifier-when-testing-framework,"['ios', 'swift', 'frameworks']",593,FALSE,0,0
Mocking HttpContext.Current Application does not persist,"<p>I am trying to set up unit testing on an existing solution which contains a MVC web project which uses an older 3rd party tool.  This tool makes heavy use of the <code>HttpContext.Current</code> to do the things it does, one of which is a fairly complex form of dependency injection to instantiate what are essentially service-layer objects.</p>

<p>So, in order to get these objects to instantiate in my unit testing project with everything they need I need to create my own <code>HttpContext</code> and assign it to <code>HttpContext.Current</code>.  I have this working relatively well but there seems to be a problem with the <code>HttpContext.Current.Application</code> object.  Basically, any time I add an object to that, either using <code>HttpContext.Current.Application[key] = object;</code> or <code>HttpContext.Current.Application.Add(key, object);</code> nothing seems to happen.</p>

<p>Decompiling <code>System.Web</code> indicates that there is not an easy way to assign the <code>Appplication</code> property since the getter is returning a value from a factory instance, so my guess is that this factory is generating a new application every time the <code>HttpApplication.Application</code> property is referenced.  Is there something I'm missing to ensure that this value is persistent?</p>

<p>Here is my code for creating the <code>HttpContext.Current</code> object:</p>

<pre><code>internal static class UnitTestUtilities
{

    private static HttpApplication application;

    private static HttpContext GetHttpContext(string url)
    {
        if (application == null)
        {
            application = new HttpApplication();
            application.Init();
        }
        HttpContext.Current = new HttpContext(new HttpRequest("""", url, """"),
            new HttpResponse(new StringWriter()))
        {
            ApplicationInstance = application
        };

        //Call hacks to get context application set up
        HttpContext.Current.ApplicationInstance.SetContext(HttpContext.Current);
        HttpContext.Current.ApplicationInstance.AddApplicationState(HttpContext.Current.Application);

        var testApplicationValue = ""TEST"";
        var testApplicationValue2 = ""TEST2"";
        HttpContext.Current.Application.Lock();
        HttpContext.Current.Application[""TEST""] = testApplicationValue;
        HttpContext.Current.Application.Add(""TEST2"", testApplicationValue2);
        HttpContext.Current.Application.UnLock();

        //Issue is here: HttpContext.Current.Application still contains 0 items!

        return HttpContext.Current;
    }


    #region System.Web hacks
    private static void SetContext(this HttpApplication app, HttpContext context)
    {
        var prop = typeof(HttpApplication).GetField(""_context"", BindingFlags.NonPublic | BindingFlags.Instance);
        prop.SetValue(app, context);
    }

    private static void AddApplicationState(this HttpApplication app, HttpApplicationState state = null)
    {
        if(state == null)
        {
            var ctor = typeof(HttpApplicationState).GetConstructor(
                      BindingFlags.Instance | BindingFlags.NonPublic,
                      null, new Type[] { }, new ParameterModifier[] { });
            state = (HttpApplicationState)ctor.Invoke(new Object[] { });
        }
        var prop = typeof(HttpApplication).GetField(""_state"", BindingFlags.NonPublic | BindingFlags.Instance);
        prop.SetValue(app, state);
    }
    #endregion
}
</code></pre>
",https://stackoverflow.com/questions/48307146/mocking-httpcontext-current-application-does-not-persist,"['c#', 'asp.net', 'unit-testing', 'httpcontext']",719,FALSE,1,0
Can I use Jest with Angular4,"<p>I was developing Angular4 project and was looking for Unit test frameworks. Angular has Jasmine and Karma as default frameworks. But I came accross Jest developed by facebook.In their documentation, they have repeatedly used react keyword. But can I use 'Jest' for angular4 unit testing? Any downfall if I use jest with angular4? Or any suggestions for other Unit test frameworks?</p>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/49188848/can-i-use-jest-with-angular4,"['javascript', 'angular', 'unit-testing']",139,TRUE,0,1
ES6 jsdom cannot read property &#39;innerHTML&#39; of null,"<p>I'm trying to setup unit testing with Mocha while using jsDOM to simulate the virtualDom for my ES6; but I keep getting errors with the recent </p>

<p><code>UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'innerHTML' of null</code></p>

<p>Here's my main.js setup</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 url = 'https://localhost/demo.json';
    const source = document.getElementById('row-template').innerHTML;
    const contentLoop = document.getElementById('feedback-loop');
    const searchForm = document.getElementById('searchForm');
    const searchInput = document.getElementById('searchInput');
    const ratingEntries = document.querySelectorAll('.ratings__button');
    const lengthContainer = document.querySelector('.length');</code></pre>
</div>
</div>
</p>

<p>and my test file, simply includes this main.js file</p>

<p>The error occurs on every line that has the <code>.innerHTML</code> method</p>

<p><code>const main = require('../src/js/main');</code></p>

<p>While mocha runs with this dom.js file <a href=""https://gist.github.com/ChidinmaKO/cd5a35624285c07e61a5373c5c8ff3ea"" rel=""nofollow noreferrer"">https://gist.github.com/ChidinmaKO/cd5a35624285c07e61a5373c5c8ff3ea</a></p>

<p>Please help. What am I missing?</p>
",https://stackoverflow.com/questions/53824598/es6-jsdom-cannot-read-property-innerhtml-of-null,"['javascript', 'unit-testing', 'mocha.js', 'es6-modules', 'jsdom']",827,TRUE,0,1
Objectify Web Safe Key Usage,"<p>I am using <code>Objectify</code> to store and retrieve data from App Engine Datastore.</p>

<p>String version of the key is created from the datastore object id.</p>

<pre><code>public String getWebsafeKey() {
    return Key.create(UserData.class, id).getString();
}
</code></pre>

<p>The <code>websafeKey</code> is used to get the UserData object from the Datastore.</p>

<pre><code>Key&lt;UserData&gt; userDataKey = Key.create(websafeKey);
UserData userData = ofy().load().key(userDataKey).now();
</code></pre>

<p>In our Unit testing when the <code>websafeKey</code> is changed a bit, the user data class can still be retrieved.</p>

<p>Passed websafeKey - <code>agxqfmMyaHF1YWxpdHlyEgsSBU1vdmllGICAgJDSioELDC</code></p>

<p>Actual websafeKey - <code>agxqfmMyaHF1YWxpdHlyEgsSBU1vdmllGICAgJDSioELDA</code></p>

<p>Is this a known limitation or this can be addressed?</p>
",https://stackoverflow.com/questions/51318045/objectify-web-safe-key-usage,"['google-cloud-datastore', 'objectify']",145,TRUE,0,1
Is there a software for plotting trending code coverage data from Karma/Jasmine,"<p>I have an Angular app along with the standard Karma/Jasmine set up for unit testing. What I want is to feed the code coverage reports I get for each nightly build into a software that would create a trend of how my coverage is changing through time. </p>

<p>Does anybody know a product that can do that? My Google search didn't come up with anything.</p>
",https://stackoverflow.com/questions/51718019/is-there-a-software-for-plotting-trending-code-coverage-data-from-karma-jasmine,"['angular', 'karma-jasmine', 'code-coverage', 'linechart', 'karma-coverage']",29,FALSE,0,0
"How to do unit testing for a function calling a private function , which makes an external API call in nodejs?","<p>How to do unit testing for a function calling a private function , which makes an external API call in nodejs. What i want is that my test should not be dependent on response from an external call and I thought of mocking the private function through which API call is made but I can't seem to achieve that. What should be a good approach to resolve this?</p>
",https://stackoverflow.com/questions/48415604/how-to-do-unit-testing-for-a-function-calling-a-private-function-which-makes-a,"['node.js', 'unit-testing', 'mocha.js', 'sinon', 'chai']",394,FALSE,0,1
Assertion null in running group of tests,"<p>Am newbie to Unit testing. Am using TestNG and Mockito for unit test. I have 8 test cases when running the test cases one by one it's working fine. After that i have added all those methods in one class. After running the test class i got Assertion null exception. Am not able to find the root cause. Here is my code.</p>

<pre><code>public class TestLoginController {

@Mock
DBResourseLoader dbResourceLoader;

@Mock
MessageLoader messageLoader;

@Mock
Logger logger;

@Mock
Properties properties;

@Mock
Properties databaseProperties;

@Mock
DBConnector connector;

@Mock
Connection connection;

@Mock
PropertyConfigurator propertyConfigurator;

@InjectMocks
LoginBean loginBean;

@Mock
CommonDAO commonDAO;

@Mock 
PreparedStatement preparedStatement;

@Mock
ResultSet resultSet;




@BeforeClass
public void setup() {
    try {

        MockitoAnnotations.initMocks(this);
        when(messageLoader.getMessageStatement("""")).thenReturn("""");
        when(dbResourceLoader.getJdbcDatasource()).thenReturn(properties);
        when(dbResourceLoader.getLogger()).thenReturn(databaseProperties);
        when(dbResourceLoader.getLogger(Logger.class)).thenReturn(logger);

        when(connector.getConnection(true)).thenReturn(connection);
    }catch(Exception e) {
        e.printStackTrace();
    }
}


@BeforeMethod
public void setBeforeValues() {


}

@Test
public void negTestCheckIsReportCreatedByCustomerReportFlagByNo() {
    try {
        when(commonDAO.getLoginControllerValue(""LOGIN_CONTROLLER"")).thenReturn(""NO"");
        reset(commonDAO);
        assertNotEquals(false, loginBean.checkIsReportCreatedByCustomer(""1234@1234.com""));
    }catch(Exception e) {
        e.printStackTrace();
    }
}

@Test
public void posTestCheckIsReportCreatedByCustomerReportFlagByNo() {
    try {

        when(commonDAO.getLoginControllerValue(""LOGIN_CONTROLLER"")).thenReturn(""NO"");
        assertEquals(true, loginBean.checkIsReportCreatedByCustomer(""1234@1234.com""));

    }catch(Exception e) {
        e.printStackTrace();
    }
}

@Test
public void negTestCheckIsReportCreatedByCustomerByReportFlagYes() {
    try {
        when(commonDAO.getLoginControllerValue(""LOGIN_CONTROLLER"")).thenReturn(""YES"");
        when(commonDAO.getCustomerReportCreationValue(""1234@gmail.com"")).thenReturn(false);
        assertNotEquals(true, loginBean.checkIsReportCreatedByCustomer(""1234@1234.com""));
    }catch(Exception e) {
        e.printStackTrace();
    }
}

@Test
public void posTestCheckIsReportCreatedByCustomerByReportFlagYes() {
    try {
        when(commonDAO.getLoginControllerValue(""LOGIN_CONTROLLER"")).thenReturn(""YES"");
        when(commonDAO.getCustomerReportCreationValue(""1234@1234.com"")).thenReturn(true);
        assertEquals(true, loginBean.checkIsReportCreatedByCustomer(""1234@1234.com""));
    }catch(Exception e) {
        e.printStackTrace();
    }
}

@Test
public void negTestCheckLoginAlertReportFlagByNo() {
    try {
        when(commonDAO.getLoginControllerValue(""LOGIN_CONTROLLER"")).thenReturn(""NO"");
        assertNotEquals(false, loginBean.checkIsReportCreatedByCustomer(""1234@1234.com""));
    }catch(Exception e) {
        e.printStackTrace();
    }
}

@Test
public void posTestLoginAlertCustomerReportFlagByNo() {
    try {
                    when(commonDAO.getLoginControllerValue(""LOGIN_CONTROLLER"")).thenReturn(""NO"");
        assertEquals(true, loginBean.checkIsReportCreatedByCustomer(""1234@1234.com""));

    }catch(Exception e) {
        e.printStackTrace();
    }
}

@Test
public void negTestLoginAlertByReportFlagYes() {
    try {
        when(commonDAO.getLoginControllerValue(""LOGIN_CONTROLLER"")).thenReturn(""YES"");
        when(commonDAO.getCustomerReportCreationValue(""1234@gmail.com"")).thenReturn(false);
        assertNotEquals(true, loginBean.checkIsReportCreatedByCustomer(""1234@1234.com""));
    }catch(Exception e) {
        e.printStackTrace();
    }
}

@Test
public void posTestCheckLoginAlertByReportFlagYes() {
    try {
        when(commonDAO.getLoginControllerValue(""LOGIN_CONTROLLER"")).thenReturn(""YES"");
        when(commonDAO.getCustomerReportCreationValue(""1234@1234.com"")).thenReturn(true);
        assertEquals(true, loginBean.checkIsReportCreatedByCustomer(""1234@1234.com""));
    }catch(Exception e) {
        e.printStackTrace();
    }
}

}
</code></pre>

<p>And the exception is</p>

<pre><code>FAILED: negTestCheckLoginAlertReportFlagByNo
java.lang.AssertionError: null
at org.testng.Assert.fail(Assert.java:93)
at org.testng.Assert.assertNotEquals(Assert.java:897)
at org.testng.Assert.assertNotEquals(Assert.java:902)
at 
com.test.login.controller.TestLoginController.
negTestCheckLoginAlertReportFlagByNo(TestLoginController.java:146)
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.testng.internal.MethodInvocationHelper.
invokeMethod(MethodInvocationHelper.java:108)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:661)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:869)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1193)
at org.testng.internal.TestMethodWorker.
invokeTestMethods(TestMethodWorker.java:126)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
at org.testng.TestRunner.privateRun(TestRunner.java:744)
at org.testng.TestRunner.run(TestRunner.java:602)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:380)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:375)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340)
at org.testng.SuiteRunner.run(SuiteRunner.java:289)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1301)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1226)
at org.testng.TestNG.runSuites(TestNG.java:1144)
at org.testng.TestNG.run(TestNG.java:1115)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
</code></pre>
",https://stackoverflow.com/questions/50459811/assertion-null-in-running-group-of-tests,"['java', 'exception', 'mockito', 'testng']",158,FALSE,0,2
Does it mean something wrong when I have too many Mockito when().thenReturn() to simulate the case?,"<p>I am trying to do unit testing using Mockito to simulate the case. In the testing class, we only have one public method. So to simulate different cases, I have to mock a lot of details of the data. Please see below:</p>

<pre><code>when(config.booleanValue(param1)).thenReturn(true);
        when(config.doubleValue(param2).thenReturn(9999.0);
        when(myCalendar.getAppointmentNumber()).thenReturn(3);
        when(location1.getLatitude()).thenReturn(90.0);
        when(location2.getLongitude()).thenReturn(90.0);
        when(location1.getLowerBoundary()).thenReturn(12.0);
        when(address1.getId()).thenReturn(1);
        when(address1.popularity()).thenReturn(0.6);
        when(people.getLocation(any(LocalDate.class))).thenReturn(location1);
        when(people.getAddresses(any(LocalDate.class))).thenReturn(Collections.singletonList(address1));
        when(location2.getLatitude()).thenReturn(90.3);
        when(location2.getLongitude()).thenReturn(90.3);
        when(location2.getId()).thenReturn(1);
        when(customer.getLocation(any(LocalDate.class))).thenReturn(location2);
        when(myCalendar.getPrevAppointment()).thenReturn(appointment1);
        when(myCalendar.getNextAppointment()).thenReturn(appointment2);
        when(appointment1.to(appointment2)).thenReturn(15.0);
        when(appointment2.to(any(Location.class))).thenReturn(9.0);
</code></pre>

<p>Using Mockito like this seems to be something wrong to me. Or I am thinking too much. Please lecture me. Thanks in advance.</p>
",https://stackoverflow.com/questions/53676101/does-it-mean-something-wrong-when-i-have-too-many-mockito-when-thenreturn-to,"['unit-testing', 'junit', 'mockito', 'powermock']",92,FALSE,0,1
C# TestMethod - async &lt;ActionResult&gt; Index(),"<p>I am new to Unit Testing and relatively new to C# too. Not a great combination! I have looked at similar questions on this forum and tried solutions with no success.
Within my Home Controller, I have defined the following method. How do I write a <code>[MethodTest]</code> for <code>async Task &lt;ActionResult&gt;</code>?</p>

<p><strong>Home Controller</strong> </p>

<pre class=""lang-cs prettyprint-override""><code>public async Task&lt;ActionResult&gt; Index()
{
    var userId = Request.IsAuthenticated ? HttpContext.User.Identity.GetUserId() : null;
    var thumbnails = await new List&lt;ThumbnailModel&gt;().GetPropertyThumbnailsAsync(userId);

    var count = thumbnails.Count() / 4;
    var model = new List&lt;ThumbnailAreaModel&gt;();
    for (int i = 0; i &lt;= count; i++)
    {
        model.Add(new ThumbnailAreaModel
        {
            Title = i.Equals(0) ? ""My Content"" : string.Empty,
            Thumbnails = thumbnails.Skip(i * 4).Take(4)
        });
    }

    return View(""Index"", model);
}

[TestMethod()]
public void Index()
{
    // Arrange

    // Validate model state end

    // Act
    ViewResult result = HomeController.Index() as Task&lt;ActionResult&gt;;

    //Assert
    Assert.IsNotNull(result);
}
</code></pre>

<p>If anyone can help or point me in the right direction, I would be grateful.</p>
",https://stackoverflow.com/questions/53792036/c-testmethod-async-actionresult-index,"['c#', 'unit-testing', 'redux-async-actions']",146,TRUE,0,1
Spring Batch Java annotated - restart example,"<p>Using the Spring Boot, Batch example: <a href=""https://spring.io/guides/gs/batch-processing/"" rel=""nofollow noreferrer"">https://spring.io/guides/gs/batch-processing/</a></p>

<p>Project is now running, but the site doesn't go into how to write Unit tests around this structure. Github examples for Spring Batch show xml examples, which do not seem to correlate to this boot style.</p>

<p>Has anyone ran into any good Spring Boot, Batch examples that show restarting, unit testing, etc</p>
",https://stackoverflow.com/questions/48695540/spring-batch-java-annotated-restart-example,"['spring-boot', 'spring-batch']",273,FALSE,0,1
Generating .TRX file in jenkins using .Net Framework 4.7.2 using xunit,"<p>So I've got a .Net 4.7.2 solution with a unit testing project also using 4.7.2 and xunit.</p>

<p>I've got a jenkins job setup to run the unit tests every 5 minutes and send an email to me if any tests fail.  Currently, I only know how to generate and send off an XML file, but I've got another jenkins job for unit testing against a .Net Core solution which sends off a TRX file to me if any jobs fail.</p>

<p>I really like the TRX file format (the template and information contained within) and I'd like to change my .Net 4.7.2 job to send off a TRX file instead, but from what I can find, MSTEST is the only way to generate a TRX file and it only works with .Net Core.</p>

<p>I only have a loose understanding of what options I have in regards to reporting from jenkins, but I was wondering if it's possible to either generate a TRX file or convert the XML file to TRX post build.</p>

<p>Thanks in advance</p>

<p><strong>Current Jenkins Windows Batch Command</strong></p>

<pre><code>cd ""C:\Program Files (x86)\Jenkins\workspace\JenkinsJobName\packages\xunit.runner.console.2.3.1\tools\net452\""
xunit.console ""C:\Program Files (x86)\Jenkins\workspace\JenkinsJobName\TestProject\bin\Debug\TestProject.dll"" 
-xml ""C:\Program Files (x86)\Jenkins\workspace\JenkinsJobName\report.xml""
</code></pre>
",https://stackoverflow.com/questions/52653911/generating-trx-file-in-jenkins-using-net-framework-4-7-2-using-xunit,"['.net', 'unit-testing', 'jenkins', 'xunit.net', 'trx']",442,FALSE,1,0
Assert exception raised due to previous test-case failure,"<p>I can not think of a better heading.</p>

<p>In the following code, if <code>rollBackLogger</code> is <code>nil</code>, the first test case would fail but all other test cases would raise an exception.</p>

<p>Is there a way available to avoid this, other than using an <code>if</code> statement?</p>

<p>I believe that this is a very common situation for unit testing and that there should be some function in <code>assert</code> or some other way around to avoid this. </p>

<pre><code>assert.NotNil(rollbackLogger)
assert.Equal(""Action"", rollBackLogger[0].Action)
assert.Equal(""random path"", rollBackLogger[0].FilePath)
</code></pre>
",https://stackoverflow.com/questions/51783247/assert-exception-raised-due-to-previous-test-case-failure,"['unit-testing', 'testing', 'go', 'junit', 'assert']",721,TRUE,3,2
How to Create a Unit Test for Adding Items in a Repository?,"<p>I have an <strong>IUnitOfWork</strong> interface that encapsulates my custom repositories. My custom repositories in turn inherit from an <strong>IRepository</strong> interface.</p>

<pre><code>// The class that I am attempting to unit test
// EmployeeBusiness.cs
private readonly IUnitOfWork _unitOfWork;

public EmployeeBusiness(IUnitOfWork unitOfWork)
{
    _unitOfWork = unitOfWork;
}


public EmployeeDto AddEmployee(EmployeeDto employeeDto)
{
    var employee = Mapper.Map&lt;Employee&gt;(employeeDto);

    if (employee == null) return null;

    _unitOfWork.Employees
        .Add(employee);

    _unitOfWork.Complete();

    return Mapper.Map&lt;EmployeeDto&gt;(employee); 
}

// IUnitOfWork interface
public interface IUnitOfWork : IDisposable
{
    IEmployeeRepository Employees { get; }

    void Complete();
}

// IEmployeeRepository interface
public interface IEmployeeRepository : IRepository&lt;Employee&gt; { }

// IRepository&lt;T&gt; interface
public interface IRepository&lt;TEntity&gt; where TEntity : class
{
    void Add(TEntity entity);

    // I have added other methods for simplicity
}
</code></pre>

<p>I am struggling with unit testing the <code>AddEmployee()</code> method because I am getting this error: </p>

<p><em>Expected invocation on the mock once, but was 0 times: uow => uow.Employees.Add(Employee)
Configured setups: 
IUnitOfWork uow => uow.Employees.Add(Employee)
Performed invocations: 
IRepository`1.Add(Employee)</em></p>

<p>This is my unit test</p>

<pre><code>[SetUp]
public void SetUp()
{
    _employeeDto = new EmployeeDto
    {
        FirstName = ""John"",
        LastName = ""Smith"",
        BirthDate = new DateTime(1965, 12, 31)
    };

    _employee = new Employee
    {
       FirstName = ""John"",
       LastName = ""Smith"",
       BirthDate = new DateTime(1965, 12, 31)
    };

    _unitOfWork = new Mock&lt;IUnitOfWork&gt;();

    Mapper.Initialize(cfg =&gt;
    {
        cfg.AddProfile&lt;EmployeeProfile&gt;();
    });
}


[Test]
public void AddEmployee_WhenCalled_AddEmployeeToDatabase()
{
    _unitOfWork.Setup(uow =&gt; uow.Employees.Add(_employee));
    _employeeBusiness = new EmployeeBusiness(_unitOfWork.Object);

    _employeeBusiness.AddEmployee(_employeeDto);

    _unitOfWork.Verify(uow =&gt; uow.Employees.Add(_employee), Times.Once);
    _unitOfWork.Verify(uow =&gt; uow.Complete(), Times.Once);
}
</code></pre>
",https://stackoverflow.com/questions/52854915/how-to-create-a-unit-test-for-adding-items-in-a-repository,"['c#', 'nunit', 'moq']",652,TRUE,0,3
Split PHPunit tests to stop out of memory error,"<p>I have a business app that uses phpunit for unit testing.  The business app is growing in size and growing in unit tests.  When I run phpunit to get a code coverage report, I am running out of memory. What is a good way to generate a code coverage report with lots of unit test?</p>

<p>Running the below phpunit.xml, I get the following error before finishing:</p>

<pre><code>PHP Fatal error:  Allowed memory size of 1073741824 bytes exhausted (tried to allocate 1068290 bytes)
</code></pre>

<p>I am using PHP5.6 and Jenkins to run the job.</p>

<pre><code>&lt;?xml version=""1.0"" encoding=""UTF-8""?&gt;
&lt;phpunit backupGlobals=""false""
  backupStaticAttributes=""false""
  bootstrap=""./src/bootstrap/autoload.php""
  colors=""true""
  convertErrorsToExceptions=""true""
  convertNoticesToExceptions=""true""
  convertWarningsToExceptions=""true""
  processIsolation=""false""
  stopOnFailure=""false""
  syntaxCheck=""false""
&gt;
 &lt;testsuites&gt;
  &lt;testsuite name=""module1""&gt;
   &lt;directory&gt;./tests/module1&lt;/directory&gt;
   &lt;directory&gt;./tests/module2&lt;/directory&gt;
   &lt;directory&gt;./tests/module3&lt;/directory&gt;
   &lt;directory&gt;./tests/module4&lt;/directory&gt;
   &lt;directory&gt;./tests/module5/directory&gt;
   &lt;directory&gt;./tests/module6&lt;/directory&gt;
   &lt;directory&gt;./tests/module7&lt;/directory&gt;
   &lt;directory&gt;./tests/module8&lt;/directory&gt;
  &lt;/testsuite&gt;
  &lt;testsuite name=""module2""&gt;
   &lt;directory&gt;./tests/module9&lt;/directory&gt;
   &lt;directory&gt;./tests/module10&lt;/directory&gt;
   &lt;directory&gt;./tests/module11&lt;/directory&gt;
   &lt;directory&gt;./tests/module12&lt;/directory&gt;
   &lt;directory&gt;./tests/module13&lt;/directory&gt;
   &lt;directory&gt;./tests/module14&lt;/directory&gt;
   &lt;directory&gt;./tests/module15&lt;/directory&gt;
   &lt;directory&gt;./tests/module16&lt;/directory&gt;
  &lt;/testsuite&gt;
 &lt;/testsuites&gt;

 &lt;filter&gt;
  &lt;blacklist&gt;
   &lt;directory&gt;./src&lt;/directory&gt;
  &lt;/blacklist&gt;
  &lt;whitelist&gt;
   &lt;directory&gt;./src/app/module&lt;/directory&gt;
  &lt;/whitelist&gt;
 &lt;/filter&gt;

 &lt;logging&gt;
  &lt;log type=""coverage-html"" target=""build/module"" title=""module""
   charset=""UTF-8"" yui=""true"" highlight=""true""
   lowUpperBound=""70"" highLowerBound=""90""/&gt;
  &lt;log type=""junit"" target=""build/logs/module.xml"" logIncompleteSkipped=""false""/&gt;
 &lt;/logging&gt;

&lt;/phpunit&gt;
</code></pre>
",https://stackoverflow.com/questions/49118107/split-phpunit-tests-to-stop-out-of-memory-error,"['php', 'phpunit']",5182,TRUE,8,1
How using HttpTestingController can I flush with a header?,"<p>I've got a Angular service that calls a http api, this API returns a file blob.   The service passes the response to a file save method to present the file for downloading.</p>

<p>I'm struggling with the unit testing of this method, specifically making sure there is a response with the right headers in it.
I think its part of the TestRequest.flush() function</p>

<pre><code>flush(body: ArrayBuffer | Blob | string | number | Object | (string | number | Object | null)[] | null, opts: {
    headers?: HttpHeaders | {
        [name: string]: string | string[];
    };
    status?: number;
    statusText?: string;
} = {}): void
</code></pre>

<p>But I can' t workout how to add headers. </p>

<pre><code>        req.flush(file, {
        headers: {
            [name: 'Content-Disposition']= '' },
        status: 200,
        statusText: 'OK'
    });
</code></pre>
",https://stackoverflow.com/questions/51542783/how-using-httptestingcontroller-can-i-flush-with-a-header,"['angular', 'unit-testing', 'http', 'http-headers']",2605,TRUE,2,1
Return a new object for each Returns() in NSubstitute,"<p>I have created a substitute which mocks a web service interface for my  unit testing which includes the following method definition:</p>

<pre><code>public Message Invoke(Message input)
</code></pre>

<p>This method is called using:</p>

<pre><code>var reply = webService.Invoke(messageObject)
</code></pre>

<p>When I make multiple calls to the same method, it is throwing the following exception:</p>

<p>System.InvalidOperationException : This message cannot support the operation because it has been read.</p>

<p>Here is my Nsubstitute mock code:</p>

<pre><code>outputMessageObj = GetResponseMessage()
wsMock.Invoke(Arg.Any&lt;Message&gt;()).Returns(outputMessageObj)
</code></pre>

<p>How do I ensure that a new outputMessage object is returned each time the call is made?</p>
",https://stackoverflow.com/questions/48085178/return-a-new-object-for-each-returns-in-nsubstitute,"['c#', 'unit-testing', 'nsubstitute']",1865,TRUE,8,1
How to unit test service methods that are basically 1 to 1 calls to a MyBatis Mapper interface,"<p>I'm new to MyBatis and Unit Testing.</p>

<p>I have a <code>CourseService</code> class that has (at the moment) only methods that call and return the equivalent method of the MyBatis Mapper (<code>CourseMapper</code>).</p>

<p>CourseService class.</p>

<pre><code>@Autowired
private CourseMapper courseMapper;

public Course getById(int id) {
    return courseMapper.getById(id);
}
...
</code></pre>

<p>CourseMapper interface.</p>

<pre><code>@Select(""select from courses where id = #{id}"")
public Course getById(int id);
...
</code></pre>

<p>Should I unit test <code>courseService.getById(id)</code>? Would be appropriate to mock the Mapper and construct the service with that mapper and make the mock call to <code>getById</code> return a Course with the id passed as argument? </p>

<pre><code>when(courseMapper.getCourseById(anyInt()))
    .thenAnswer(this::returnCourseWithSameIdThatInTheArgument); 
...

private Course CourseWithSameIdThatInTheArgument(InvocationOnMock i) {
    return new Course((int)i.getArguments()[0],true,1,"""","""",1);
}
</code></pre>

<p>Thank you in advance.</p>
",https://stackoverflow.com/questions/48223915/how-to-unit-test-service-methods-that-are-basically-1-to-1-calls-to-a-mybatis-ma,"['java', 'unit-testing', 'junit', 'mockito', 'mybatis']",574,TRUE,2,2
Embed Attachment to HTML img in an email,"<p>I am working with a file for Unit testing and a Resourcefile (""WorkflowNotifications.resx"") which contains strings with HTML code and one png image (""mail_header.png""). In the HTML code is an image which should be the one from the resourcefile. My goal is to refer this image to the sourcelink of the img attribute. And in doing so I should use the Attachmentclass. I do not know what to do with my initialized Attachmentobject and how to add it to the sourcelink. I know there is a similar post on this topic, but mine is a bit more specific because I should not refer to image directly in the HTML code. Thank you for your time and help!</p>

<p>html img code:</p>

<pre><code>&lt;img src=""cid:""{0}"" &gt;
</code></pre>

<p>I use string.Format to replace the placeholder in the unit testing method so far, but the image will not display.</p>

<p>Help method for getting a stream:</p>

<pre><code>public static Stream GetMailHeader()
    {
        return ToStream((Image)MailTemplates.WorkflowNotifications.ResourceManager.GetObject(""mail_header""), ImageFormat.Png);
    }

    private static Stream ToStream(Image image, ImageFormat format)
    {
        var stream = new System.IO.MemoryStream();
        image.Save(stream, format);
        stream.Position = 0;
        return stream;
    }
</code></pre>

<p>Attachment object in the unittesting method:</p>

<pre><code>var att = new Attachment(Resources.ResourceGovernor.GetMailHeader(), ""mail_header"");
</code></pre>

<p>ResourceGoverner is just a class that is handling most of the resources and WorkflowNotifications is the resourcefile.</p>
",https://stackoverflow.com/questions/51418272/embed-attachment-to-html-img-in-an-email,"['c#', 'html', 'base64', 'html-email']",105,TRUE,0,1
AWS CreateBatchWrite unit test,"<p>I'm trying to write some unit test around AWS DynamoDb C# library, CreateBatchWrite.</p>

<p>This is the method:</p>

<pre><code>public void BatchSave&lt;T&gt;(string tableName, List&lt;T&gt; items)
{
    if (string.IsNullOrWhiteSpace(tableName))
    {
        throw new ArgumentNullException(nameof(tableName));
    }

    if (items == null)
    {
        throw new ArgumentNullException(nameof(items));
    }

    items.RemoveAll(x =&gt; x == null);

    BatchWrite&lt;T&gt; batch = _dynamoDbContext.CreateBatchWrite&lt;T&gt;(
        new DynamoDBOperationConfig()
        {
            OverrideTableName = tableName
        });

    batch.AddPutItems(items);
    batch.Execute();
}
</code></pre>

<ul>
<li>What I want to test are my precondition</li>
<li>_dynamoDbContext is injected and it's an interface (IDynamoDBContext)</li>
</ul>

<p>My problem is the return object from CreateBatchWrite: BatchWrite is a strongly typed class.</p>

<p>Apart from moving my preconditions one layer below or above, is there any way of unit testing this? Is my approach correct?</p>
",https://stackoverflow.com/questions/52328753/aws-createbatchwrite-unit-test,"['c#', '.net', 'unit-testing', 'amazon-dynamodb', 'aws-sdk']",838,TRUE,2,1
Testing Lists Results,"<p>I am creating a Unit Testing using NLog and NSubstitute.</p>

<p>I have in API Controller this method:</p>

<pre><code>    public GenericListItems&lt;CalendarYearItem&gt; GetYears(int startingYear = 0,  int rangeYears = 50, int startIndex = 0, int itemCount = 4)
    {
        if (startingYear == 0)
        {
            startingYear = DateTime.Now.Year;
        }

        List&lt;CalendarYearItem&gt; years = Enumerable.Range(startingYear, rangeYears).Select(x =&gt; new CalendarYearItem(x++)).ToList();
        if (years != null)
        {
            int firstIndex = 0;
            int totalCount = years.Count;
            years = PaginateList(years, startIndex, itemCount, totalCount, firstIndex);
            return new GenericListItems&lt;CalendarYearItem&gt;(years, firstIndex, totalCount);
        }
        return new GenericListItems&lt;CalendarYearItem&gt;();
    }
</code></pre>

<p>And this interface:</p>

<pre><code>    /// &lt;summary&gt;
    /// Get Years
    /// &lt;/summary&gt;
    /// &lt;returns&gt;List Months&lt;/returns&gt;
    GenericListItems&lt;CalendarYearItem&gt; GetYears(int startingYear, int rangeYears, int startIndex = 0, int itemCount = 4);
</code></pre>

<p>I need test when call this method if return a total count 50;
If the starting year is 0 validate if first position is 2018;</p>

<pre><code>   [Test]
    [TestCase(0, 50)]
    public void GetYears_GetCalendarListYearWithEmptyYear_ReturnCalendarListYearsStartingCurrentYear(int startingYear, int rangeYears)
    {
        GenericListItems&lt;CalendarYearItem&gt; calendar = new GenericListItems&lt;CalendarYearItem&gt;();

        _substitute.GetYears(startingYear, rangeYears);

        Assert.That(calendar.TotalCount, Is.EqualTo(50));
        //var result = _substitute.GetFullDate(year, month, day).Returns(calendar);
        //Assert.AreEqual(calendar, result);
    }
</code></pre>

<p><strong>Instead Assert i Need to use Collections Assert?
but when a create the arrange i have to copy my linq query to create?</strong></p>
",https://stackoverflow.com/questions/52073434/testing-lists-results,"['c#', '.net', 'unit-testing', 'nsubstitute']",39,TRUE,1,1
mocking function with same name and different argument using proxyquire,"<p>I have a file with format below which uses certain module.</p>

<pre><code>let module = require('modulename')
let r = module()
r.post(variable, callbackFunction)
r.post(variable, variable, variable, callbackFunction)
</code></pre>

<p>I am trying to mock this two function using proxyquire as given below</p>

<pre><code>let module= function(){
    return {
        post: (variable, callback) =&gt; {
            //some codes
            return callback(error, res)},
        post: (variable,variable,variable, callback) =&gt; {
            //somecode
            return callback(error, res)}
    }}
let mock = proxyquire(filepath,{'modulename':module})
</code></pre>

<p>Since it contain two function with same name, i am unable to mock these two post function as the function call goes to only one function(second function). How to resolve this? Anyody got any idea? I am fairly new to unit testing and proxyquire</p>
",https://stackoverflow.com/questions/53774447/mocking-function-with-same-name-and-different-argument-using-proxyquire,"['node.js', 'unit-testing', 'mocking', 'proxyquire']",294,FALSE,1,0
How to test timer-based RxJS observables in Jest,"<p>I'm moderately new to RxJS and very new to unit testing with Jest and I've run into a pretty confusing problem when trying to test some mocked-up RxJS observables.</p>

<p>In order to mimic a data stream, I created an Observable in a test <code>spec.js</code> file like this:</p>

<pre><code>var Rx = require(""rx"");

var source = Rx.Observable.interval(500).take(10);

source.subscribe(
    function(x){ console.log(x) },
    function(e){ console.log(e) },
    function(){ console.log('completed') }
  );
</code></pre>

<p>Although this logs correctly when just ran as a node script, it doesn't log anything when ran through <code>npm test</code>. The <code>Observable.delay</code> and <code>setTimeout</code>  functions don't appear to work as well. </p>
",https://stackoverflow.com/questions/48428059/how-to-test-timer-based-rxjs-observables-in-jest,"['javascript', 'node.js', 'unit-testing', 'jestjs']",5298,TRUE,4,1
Angular 6 service failing to pass unit tests with (NullInjectorError: No provider for HttpClient!),"<p>I am trying to do unit testing in angular 6 , when I run `ng test' </p>

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

<pre><code>Error: StaticInjectorError(DynamicTestModule)[HttpClient]:
          StaticInjectorError(Platform: core)[HttpClient]:
            NullInjectorError: No provider for HttpClient!
            at NullInjector.push../node_modules/@angular/core/fesm5/core.js.NullInjector.get (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:691:1)
            at resolveToken (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:928:1)
            at tryResolveToken (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:872:1)
            at StaticInjector.push../node_modules/@angular/core/fesm5/core.js.StaticInjector.get (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:769:1)
            at resolveToken (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:928:1)
            at tryResolveToken (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:872:1)
            at StaticInjector.push../node_modules/@angular/core/fesm5/core.js.StaticInjector.get (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:769:1)
            at resolveNgModuleDep (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:17435:1)
            at NgModuleRef_.push../node_modules/@angular/core/fesm5/core.js.NgModuleRef_.get (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:18124:1)
            at inject (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:1023:1)
Chrome 69.0.3497 (Windows 10 0.0.0): Executed 2 of 12 (2 FAILED) (0 secs / 0.119 secs)
Chrome 69.0.3497 (Windows 10 0.0.0) UserService should have add function FAILED
        Error: StaticInjectorError(DynamicTestModule)[HttpClient]:
          StaticInjectorError(Platform: core)[HttpClient]:
            NullInjectorError: No provider for HttpClient!
            at NullInjector.push../node_modules/@angular/core/fesm5/core.js.NullInjector.get (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:691:1)
            at resolveToken (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:928:1)
            at tryResolveToken (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:872:1)
            at StaticInjector.push../node_modules/@angular/core/fesm5/core.js.StaticInjector.get (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:769:1)
            at resolveToken (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:928:1)
            at tryResolveToken (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:872:1)
            at StaticInjector.push../node_modules/@angular/core/fesm5/core.js.StaticInjector.get (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:769:1)
            at resolveNgModuleDep (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:17435:1)
            at NgModuleRef_.push../node_modules/@angular/core/fesm5/core.js.NgModuleRef_.get (http://localhost:9876/node_modules/@angular/core/fesm5/core.js?:18124:1)
Chrome 69.0.3497 (Windows 10 0.0.0): Executed 2 of 12 (2 FAILED) (skipped 10) ERROR (0.094 secs / 0.119 secs)
</code></pre>

<p>Here is service spec ts file</p>

<pre><code> import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import {HttpClientModule} from '@angular/common/http';
import { UserService } from './user.service';

TestBed.configureTestingModule({
    imports: [HttpClientTestingModule, HttpClientModule],
    providers: [UserService]
});

fdescribe('UserService', () =&gt; {
  beforeEach(() =&gt; TestBed.configureTestingModule({}));

  it('should be created', () =&gt; {
    const service: UserService = TestBed.get(UserService);
    expect(service).toBeTruthy();
  });

  it('should have add function', () =&gt; {
    const service: UserService = TestBed.get(UserService);
    expect(service.addComments).toBeTruthy();
  });

});
</code></pre>

<p>Her is usersevice ts file </p>

<pre><code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {Status } from '../model/statuses.model';
import { Comment } from '../model/comments.model';
import { User } from '../model/user.model';
import { Headers, Http, Response } from '@angular/http';
import { catchError, tap, map } from 'rxjs/operators';
import { Observable, of, throwError } from 'rxjs';
import { HttpHeaders, HttpErrorResponse } from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

@Injectable({
  providedIn: 'root'
})
export class UserService {
  status: Status[];
  constructor(private http: HttpClient) { }
  statusUrl = 'http://localhost:3000/statuses';
  commentsUrl = 'http://localhost:3000/comment';
  usersUrl = 'http://localhost:3000/users';

  private extractData(res: Response) {
    // tslint:disable-next-line:prefer-const
    let body = res;
    return body || {};
  }

 // get all users
  getUsers(): Observable&lt;any&gt; {
    return this.http.get(this.usersUrl).pipe(
      map(this.extractData),
      catchError(this.handleError));
    }

  // get users by ID
  getUserById(id: number) {
    return this.http.get&lt;User&gt;(this.usersUrl + '/' + id);
  }

  // get all statuses
  getStatuses(): Observable&lt;any&gt; {
    return this.http.get(this.statusUrl).pipe(
      map(this.extractData),
      catchError(this.handleError));
    }

  // add comments
  addComments(comments: Comment) {
    comments.localTime = new Date();
    return this.http.post(this.commentsUrl, comments);
  }

  // get comments
  getComments(id: number): Observable&lt;any&gt; {
    return this.http.get(this.commentsUrl).pipe(
      map(this.extractData),
      catchError(this.handleError));
  }
  // upadet user status
  updateStatus(status: Status) {
  return this.http.put(this.statusUrl + '/' + status.id, status);
  }

  // add user status
  addStatus(status: Status) {
    return this.http.put(this.statusUrl, status);
   }
   // Errors Handler
  private handleError(error: HttpErrorResponse) {
    if (error.error instanceof ErrorEvent) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error.message);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong,
      console.error(
        `Backend returned code ${error.status}, ` +
        `body was: ${error.error}`);
    }
    // return an observable with a user-facing error message
    return throwError('Something bad happened; please try again later.');
  }

}
</code></pre>

<p>I tried different solution from stack oveflow but nothing is working , I tried even this solution here <a href=""https://stackoverflow.com/questions/48572621/angular-5-service-failing-to-pass-unit-tests-with-nullinjectorerror-no-provide?rq=1"">unit test errors angular 5</a></p>

<p>But unfortunatelly nothing works in angular 6 </p>

<p>What am I doing wrong, any help will be apreciated????</p>
",https://stackoverflow.com/questions/53066408/angular-6-service-failing-to-pass-unit-tests-with-nullinjectorerror-no-provide,"['javascript', 'angular', 'typescript', 'unit-testing', 'angular6']",3859,TRUE,1,1
How to return different object from jest.spyOn based on function call parameters?,"<p>Currently I have this code for unit testing</p>

<pre><code>mockWindow = {
  document: {
    createElement: jest.fn().mockReturnValue(div),
    head: {
      appendChild: jest.fn(),
    },
    body: {
      appendChild: jest.fn(),

    },
    removeEventListener: jest.fn(),
  },
  addEventListener: jest.fn(),
  removeEventListener: jest.fn(),
};
jest.spyOn(window, 'open').mockReturnValue(mockWindow);
</code></pre>

<p>Now I am adding another call to <code>window.open</code> to my code base with a different parameter: </p>

<pre><code> window.open('', 'new_target', 'width=1000,height=500')
</code></pre>

<p>I want to be able to return a different value when the second <code>window.open</code> is called. Is there anyway  I can ask <code>spyOn</code> to return different values based on the parameters?</p>

<p>I tried <code>jest.spyOn(window, 'open', '', 'new_target')</code> but I get this error <code>Error:(47, 5) TS2554: Expected 2-3 arguments, but got 4.</code>. The third parameter is supposed to specify the access type (i.e. get vs set)</p>
",https://stackoverflow.com/questions/53492265/how-to-return-different-object-from-jest-spyon-based-on-function-call-parameters,"['javascript', 'jestjs']",267,FALSE,4,0
mocking a promise with shallow rendering using jest in react redux app,"<p>I have looked at the following tutorials <a href=""https://hackernoon.com/unit-testing-redux-connected-components-692fa3c4441c"" rel=""nofollow noreferrer"">https://hackernoon.com/unit-testing-redux-connected-components-692fa3c4441c</a> <a href=""https://airbnb.io/enzyme/docs/api/shallow.html"" rel=""nofollow noreferrer"">https://airbnb.io/enzyme/docs/api/shallow.html</a> and tried to create a shallow rendered test of a component but i have actions being triggered on render which collect data and help render the component. how can i mock this?</p>

<p><strong>tests/jest/containers/homecontent.js</strong></p>

<pre><code>import configureStore from 'redux-mock-store'
import { shallow } from 'enzyme';
import { HomeContent } from '../../../app/containers/home';
const passMetaBack = meta =&gt; {
        this.setState({
            title: 'test',
            description: 'test'
        });
    };

// create any initial state needed
const initialState = {};
// here it is possible to pass in any middleware if needed into //configureStore
const mockStore = configureStore();

describe('Login Component', () =&gt; {
    let wrapper;
    let store;
    beforeEach(() =&gt; {
        // our mock login function to replace the one provided by mapDispatchToProps
        const mockLoginfn = jest.fn();
        //creates the store with any initial state or middleware needed
        store = mockStore(initialState)
        wrapper = shallow(&lt;HomeContent isGuest={false} isReady={true} priv={{}} passMetaBack={passMetaBack} fetchContents={mockLoginfn} /&gt;)
    });

    it('+++ render the DUMB component', () =&gt; {
        expect(wrapper.length).toEqual(1)
    });
});
</code></pre>

<p>The error i get is</p>

<pre><code> FAIL  tests/jest/containers/homecontent.test.js
  Login Component
    ✕ +++ render the DUMB component (25ms)

  ● Login Component › +++ render the DUMB component

    TypeError: Cannot read property 'then' of undefined

      38 |              if(this.props.isReady &amp;&amp; this.props.priv != undefined){
      39 |              let self = this;
    &gt; 40 |              this.props.fetchContents()
      41 |              .then(response =&gt; {
      42 |                      let data = response.payload.data;
      43 |                      if (data.header.error) {

      at HomeContent.initData (app/containers/home.js:40:7)
      at HomeContent.render (app/containers/home.js:71:12)
      at ReactShallowRenderer._mountClassComponent (node_modules/react-test-renderer/cjs/react-test-renderer-shallow.development.js:195:37)
      at ReactShallowRenderer.render (node_modules/react-test-renderer/cjs/react-test-renderer-shallow.development.js:143:14)
      at node_modules/enzyme-adapter-react-16/build/ReactSixteenAdapter.js:287:35
      at withSetStateAllowed (node_modules/enzyme-adapter-utils/build/Utils.js:103:16)
      at Object.render (node_modules/enzyme-adapter-react-16/build/ReactSixteenAdapter.js:286:68)
      at new ShallowWrapper (node_modules/enzyme/build/ShallowWrapper.js:119:22)
      at shallow (node_modules/enzyme/build/shallow.js:19:10)
      at Object.&lt;anonymous&gt; (tests/jest/containers/homecontent.test.js:24:19)

  ● Login Component › +++ render the DUMB component

    TypeError: Cannot read property 'length' of undefined

      26 |
      27 |     it('+++ render the DUMB component', () =&gt; {
    &gt; 28 |         expect(wrapper.length).toEqual(1)
      29 |     });
      30 | });
      31 |

      at Object.&lt;anonymous&gt; (tests/jest/containers/homecontent.test.js:28:24)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        2.218s
Ran all test suites matching /tests\/jest\/containers\/homecontent.test.js/i.
</code></pre>

<p><code>this.props.fetchContents()</code> comes in from an action on the component</p>
",https://stackoverflow.com/questions/51631592/mocking-a-promise-with-shallow-rendering-using-jest-in-react-redux-app,"['react-redux', 'jestjs']",1131,TRUE,1,1
"How do I unit test my request, given that the return result is always encrypted?","<p>I have this helper class that helps to generate request header and return it as a <code>request.SuperAgentRequest</code> using <code>superagent-bluebird-promise</code>.</p>

<p>My question here is</p>

<p>How do I unit test my request? Given that the return result is always encrypted.</p>

<p><strong>How to test <code>security.decryptJWE</code>?</strong></p>

<p>What I have done in my unit testing so far is to only check the number of times the function is being called. </p>

<p>Unit test class:</p>

<pre><code>let sendRequestSpy = sinon.spy(helper, ""sendRequest"");

main.updateInfo();

sinon.assert.callCount(sendRequestSpy, 10);
</code></pre>

<p>helper class:</p>

<pre><code>const restClient = require('superagent-bluebird-promise');

function sendRequest(id) {
    ...

    _.set(headers, ""Authorization"", authHeaders);

    let request = restClient.get(url);

    // Set headers
    if (!_.isUndefined(headers) &amp;&amp; !_.isEmpty(headers)) {
        request.set(headers);
    }

    return request;
}
</code></pre>

<p>main class:</p>

<pre><code>function updateInfo {

    ...
        for (var i = 0; i &lt; list.length; i++) {

            let request = helper.sendRequest(id);
            request.buffer(true).end(function (err, res) {
            ...
                let data = {
                    body: res.body,
                    text: res.text
                };

                let apiData = data.text;

                let privateKey = ""./resource/priv_key.pem"";

                var jweParts = apiData.split(""."");
                security.decryptJWE(jweParts[0], jweParts[1], jweParts[2], jweParts[3], jweParts[4], privateKey)
                .then(apiData =&gt; {
                    ...
                    //process here
                }
            }
    }
}
</code></pre>

<p>security class:</p>

<pre><code>...
security.decryptJWE = function decryptJWE(header, encryptedKey, iv, cipherText, tag, privateKey) {
  console.log(""Decrypting JWE"".green + "" (Format: "" + ""header"".red + ""."" + ""encryptedKey"".cyan + ""."" + ""iv"".green + ""."" + ""cipherText"".magenta + ""."" + ""tag"".yellow + "")"");
  console.log(header.red + ""."" + encryptedKey.cyan + ""."" + iv.green + ""."" + cipherText.magenta + ""."" + tag.yellow);
  return new Promise((resolve, reject) =&gt; {

    var keystore = jose.JWK.createKeyStore();

    console.log((new Buffer(header, 'base64')).toString('ascii'));

    var data = {
      ""type"": ""compact"",
      ""ciphertext"": cipherText,
      ""protected"": header,
      ""encrypted_key"": encryptedKey,
      ""tag"": tag,
      ""iv"": iv,
      ""header"": JSON.parse(jose.util.base64url.decode(header).toString())
    };
    keystore.add(fs.readFileSync(privateKey, 'utf8'), ""pem"")
      .then(function (jweKey) {
        // {result} is a jose.JWK.Key
        jose.JWE.createDecrypt(jweKey)
          .decrypt(data)
          .then(function (result) {
            resolve(JSON.parse(result.payload.toString()));
          })
          .catch(function (error) {
            reject(error);
          });
      });

  })
    .catch(error =&gt; {
      console.error(""Error with decrypting JWE: %s"".red, error);
      throw ""Error with decrypting JWE"";
    })
}
</code></pre>
",https://stackoverflow.com/questions/53185076/how-do-i-unit-test-my-request-given-that-the-return-result-is-always-encrypted,"['node.js', 'unit-testing', 'encryption', 'sinon']",72,FALSE,1,1
Object doesn&#39;t support this action at _ActivatedRoute_58,"<p>Am using unit testing in Angular 2 by using Jasmin and Karma. </p>

<p>I need mock this below code </p>

<pre><code>this.activatedRoute.url.subscribe(url =&gt; {
            debugger;
            this.isEdit = false;
            if (url[0].path === 'updatecoc') {
                this.isEdit = true;
            }
        });
</code></pre>

<p>I have tried mocking by this way : 
<a href=""https://stackoverflow.com/a/40790202/2218635"">How to mock an activatedRoute parent Route in angular2 for testing purposes?</a></p>

<pre><code>let fakeActivatedRoute = new MockActivatedRoute();
    fakeActivatedRoute.parent = new MockActivatedRoute();

    let urlSegment: UrlSegment[] = [];
    urlSegment.push({ path: ""updatecoc"", parameters: {} });
    fakeActivatedRoute.url = Observable.of(urlSegment);    
    beforeEach(() =&gt; {    
        TestBed.configureTestingModule({

            imports: [FormsModule, MessagesModule, DataTableModule, DropdownModule, ConfirmDialogModule, AccordionModule,
                AutoCompleteModule, DialogModule, EditorModule, HttpModule],
            declarations: [MaintainCOCComponent],
            providers: [{ provide: MaintainCOCService, useClass: MaintainCOCService },
            { provide: Configuration, useClass: Configuration },
            { provide: Router, useClass: MockRouter },
            { provide: ActivatedRoute, useClass: fakeActivatedRoute }];
</code></pre>

<p>But am getting an error while mocking <code>ActivatedRoute</code> Module. I have tried everything from 2 days. I can't resolve this issue.</p>

<p>The full error message is:</p>

<pre><code>Object doesn't support this action
   at _ActivatedRoute_58.get (Function code:173:46)
   at DynamicTestModuleInjector.prototype.getInternal (Function code:281:43)
   at NgModuleInjector.prototype.get (http://localhost:9876/base/src/test.ts:60528:9)
   at TestBed.prototype.get (http://localhost:9876/base/src/test.ts:17440:13)
   at AppView.prototype.injectorGet (http://localhost:9876/base/src/test.ts:89000:17)
   at DebugAppView.prototype.injectorGet (http://localhost:9876/base/src/test.ts:89428:13)
   at View_MaintainCOCComponent_Host0.prototype.createInternal (Function code:20:3)
   at AppView.prototype.createHostView (http://localhost:9876/base/src/test.ts:88956:9)
   at DebugAppView.prototype.createHostView (http://localhost:9876/base/src/test.ts:89412:13)
   at ComponentFactory.prototype.create (http://localhost:9876/base/src/test.ts:44498:9)
</code></pre>

<p><strong>Note:</strong> I should provide a bounty for resolved answer.</p>
",https://stackoverflow.com/questions/48378670/object-doesnt-support-this-action-at-activatedroute-58,"['angular', 'unit-testing', 'typescript', 'jasmine', 'karma-jasmine']",135,TRUE,1,1
Adding unit tests to existing Android Studio project,"<p>How do I add unit or integration tests to and existing Android Studio project?</p>

<p>I've tried adding folders in Project View as well as creating tests through the context menu (right-click).</p>

<p>I can't get Android Studio to recognize the folder as test folders.</p>

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

<ul>
<li><a href=""https://stackoverflow.com/questions/21927447/how-to-get-android-studio-to-recognize-file-as-source-test/28630023#28630023"">How to get Android Studio to recognize file as source (test)</a></li>
<li><a href=""https://stackoverflow.com/questions/31468012/unit-testing-in-android-studio"">Unit testing in android studio</a></li>
<li><a href=""https://stackoverflow.com/questions/37762095/create-unit-tests-in-android-studio"">Create unit tests in android studio</a></li>
</ul>
",https://stackoverflow.com/questions/51698857/adding-unit-tests-to-existing-android-studio-project,['android-studio'],823,TRUE,1,4
Why is file not being imported - testing VueJS with Jest,"<p>I've gotten the basic setup for unit testing VueJS with Jest configured, and have successfully tested other components in a similar fashion, but for one particular file I'm importing the file to be tested and it's being logged as undefined.</p>

<pre><code>/* Test */

import transition from '@/components/mixins/transition'
/* The '@' aliases the src directory which has been validated 
for other components */

describe('transition mixin', () =&gt; {
   it('should invoke transition correctly', () =&gt; {
      console.log('transition: ', transition) 
      /* logs transition: undefined when suite is run */
   })
})
</code></pre>

<p>Directory structure:</p>

<pre><code>src
-components
--mixins
---transition.js
</code></pre>

<p>This is what transitions.js looks like: </p>

<pre><code>/* transitions.js, not much to see here */
export const transition = {
   props: {...},
   computed: {...},
   methods: {...}
}
</code></pre>

<p>Here is the jest.conf.js file although there's nothing here (to me) that suggests the transition.js mixin file to be tested would be excluded:</p>

<pre><code>/* jest.conf.js */

const path = require('path')

module.exports = {
  rootDir: path.resolve(__dirname, '../../'),
  browser: true,
  moduleFileExtensions: [
    'js',
    'json',
    'vue'
  ],
  moduleNameMapper: {
     '^@/(.*)$': '&lt;rootDir&gt;/src/$1'
  },
  transform: {
     '^.+\\.js$': '&lt;rootDir&gt;/node_modules/babel-jest',
     '.*\\.(vue)$': '&lt;rootDir&gt;/node_modules/vue-jest'
  },
  snapshotSerializers: ['&lt;rootDir&gt;/node_modules/jest-serializer-vue'],
  setupFiles: ['&lt;rootDir&gt;/test/unit/setup'],
  coverageDirectory: '&lt;rootDir&gt;/test/unit/coverage',
  collectCoverage: true,
  collectCoverageFrom: [
    'src/**/*.{js,vue}',
    '!src/main.js',
    '!src/router/index.js',
    '!**/node_modules/**'
  ]
}
</code></pre>
",https://stackoverflow.com/questions/51562318/why-is-file-not-being-imported-testing-vuejs-with-jest,"['javascript', 'vue.js', 'vuejs2', 'jestjs']",54,FALSE,1,0
How to set the timezone for a SimpleDateFormat in Android Unit test,"<p>I want to test a method in a Date utility class that gets a <code>Date</code> from a String. The String that is passed is <code>1980-03-26T00:00:00.000+0200</code> and I want to compare the resulting date with <code>assertEquals</code>. The test failed with this output:</p>

<pre><code>org.junit.ComparisonFailure: 
Expected :Wed Mar 26 00:00:00 PST 1980
Actual   :Wed Mar 26 00:00:00 SGT 1980
</code></pre>

<p>Here's my test:</p>

<pre><code>INITIAL_DATA_DATE_FROM_STRING = ""1980-03-26T00:00:00.000+0200"";
EXPECTED_DATA_DATE_FROM_STRING = ""Wed Mar 26 00:00:00 PST 1980"";

// inside the method ...

date = DateUtils.getDateFromString(INITIAL_DATA_DATE_FROM_STRING);
assertEquals(EXPECTED_DATA_DATE_FROM_STRING, String.valueOf(date));
</code></pre>

<p>Here's the method that I am testing:</p>

<pre><code>    public static Date getDateFromString(String dateAsString) {
        return getDateFromString(dateAsString, ""dd/MM/yyyy"");
    }

    public static Date getDateFromString(String dateAsString, String dateFormat) {
        Date formattedDate = null;
        if (StringUtils.notNull(dateAsString)) {
            DateFormat format = new SimpleDateFormat(dateFormat);
            try {
                formattedDate = parseString(dateAsString, format);
            } catch (ParseException e) {
                try {
                    formattedDate = parseString(dateAsString, new SimpleDateFormat(""yyyy-MM-dd""));
                } catch (ParseException e1) {
                    // handle exception code
                }
            }
        }
        return formattedDate;
    }
</code></pre>

<p>So the unit test is not timezone independent. Is there anyway to set the default timezone just for unit testing?</p>
",https://stackoverflow.com/questions/53799418/how-to-set-the-timezone-for-a-simpledateformat-in-android-unit-test,"['android', 'unit-testing', 'timezone', 'simpledateformat']",3168,TRUE,1,1
e2e testing angular 7: Failed: Cannot read property &#39;fetchData&#39; of undefined,"<p>I'm trying to do some e2e testing for my service in angular 7, the method return Observable, this is my methode:</p>

<pre class=""lang-js prettyprint-override""><code>import { Injectable } from '@angular/core';
import { UrlDecoratorService } from ""../../common/url-decorator.service"";
import { APIFetcherService } from ""../common/api-fetcher.service"";
import { Observable } from 'rxjs';
import { IALChrono, ALChrono } from '../../common/IALChrono.interface';

@Injectable()
export class AnnonceChronoDetailService {
    private months: string[];
    constructor(private urlDecoratorService: UrlDecoratorService, private apiFetcher: APIFetcherService) {
    }

    fetchData(chronoInfo: ALChrono): Observable&lt;any&gt; {
        // construct API parameters and URL
        var URL: string = this.urlDecoratorService.urlAPIDecorate(""AL"", ""GetAccessChrono"");

        var params = this.urlDecoratorService.generateParameters({
            year: chronoInfo.year,
            month: chronoInfo.month,
            sortBy: chronoInfo.sortBy,
            sortDirection: chronoInfo.sortDirection,
            pageNumber: chronoInfo.currentPage,
            pageSize: chronoInfo.pageSize
        });

        return this.apiFetcher.fetchJson(URL, params);
    }
}
</code></pre>



<p>and this is my test :</p>

<pre class=""lang-js prettyprint-override""><code>import { AppPage } from './app.po';
import { AnnonceChronoDetailService } from '../../src/app/services/annonce-legale/annonce-chrono-detail.service';
import { ALChrono } from '../../src/app/common/IALChrono.interface';
import { APIResponse } from '../../src/app/common/api-response.interface';
import { Observable } from 'rxjs';

describe('workspace-project App', () =&gt; {
  let page: AppPage;
  let service: AnnonceChronoDetailService;
  this.chronoInfo = new ALChrono(); //it's a class

  beforeEach(() =&gt; {
    page = new AppPage();
  });

  it('should display welcome message', () =&gt; {
    page.navigateTo();
    expect(page.getParagraphText()).toEqual('Welcome to MyProject!');
  });


  it('#getObservableValue should return value from observable', (done: DoneFn) =&gt; {
    service.fetchData(this.chronoInfo).subscribe((resp: APIResponse) =&gt; {
      expect(resp.dataCount).toBe(5);
      done();
    });
  });
});
</code></pre>



<p>and this is my terminal error :</p>

<pre class=""lang-js prettyprint-override""><code>DevTools listening on ws://127.0.0.1:53112/devtools/browser/2a1d94b2-ef47-4910-9ee2-e875b615ed45
Jasmine started

  workspace-project App
    √ should display welcome message
    × #getObservableValue should return value from observable
      - Failed: Cannot read property 'fetchData' of undefined
          at UserContext.&lt;anonymous&gt; (D:\Front\e2e\src\app.e2e-spec.ts:34:13)
          at new ManagedPromise (D:\Front\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:1077:7)
          at ControlFlow.promise (D:\Front\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:2505:12)
          at TaskQueue.execute_ (D:\Front\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:3084:14)
          at TaskQueue.executeNext_ (D:\Front\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:3067:27)
          at asyncRun (D:\Front\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:2974:25)
          at D:\Front\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:668:7
          at &lt;anonymous&gt;
      From: Task: Run it(""#getObservableValue should return value from observable"") in control flow
          at ControlFlow.emit (D:\Front\node_modules\protractor\node_modules\selenium-webdriver\lib\events.js:62:21)
          at ControlFlow.shutdown_ (D:\Front\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:2674:10)
          at shutdownTask_.MicroTask (D:\Front\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:2599:53)
      From asynchronous test:
      Error
          at Suite.&lt;anonymous&gt; (D:\Front\e2e\src\app.e2e-spec.ts:33:3)
          at Object.&lt;anonymous&gt; (D:\Front\e2e\src\app.e2e-spec.ts:7:1)
          at Module._compile (module.js:635:30)
          at Module.m._compile (D:\Front\node_modules\ts-node\src\index.ts:439:23)
          at Module._extensions..js (module.js:646:10)
          at Object.require.extensions.(anonymous function) [as .ts] (D:\Front\node_modules\ts-node\src\index.ts:442:12)

**************************************************
*                    Failures                    *
**************************************************

1) workspace-project App #getObservableValue should return value from observable
  - Failed: Cannot read property 'fetchData' of undefined

Executed 2 of 2 specs (1 FAILED) in 6 secs.
[10:02:20] I/launcher - 0 instance(s) of WebDriver still running
[10:02:20] I/launcher - chrome #01 failed 1 test(s)
[10:02:20] I/launcher - overall: 1 failed spec(s)
[10:02:20] E/launcher - Process exited with error code 1
An unexpected error occurred: undefined
</code></pre>



<p>i want to test the real value of my return methode not like the unit testing, and they don't know my method <strong>fetchData</strong>.</p>

<p>if you need some more information please tell me😁.</p>

<p>thanks a lot.</p>
",https://stackoverflow.com/questions/53335638/e2e-testing-angular-7-failed-cannot-read-property-fetchdata-of-undefined,"['angular', 'protractor', 'e2e-testing', 'angular2-observables', 'angular-e2e']",689,FALSE,1,1
Unable to call default Alloy libraries in Ti.Unit Framework,"<p>We are planning to use Ti.Unit framework for Unit testing. We use moment alloy library in our project. Default alloy library, not added as file in our project. Issue is, we are unable to call moment or any other default alloy libraries in Ti.Unit test. It is not recognizing alloy default libraries. Any way we can call this library.
var moment = require(/alloy/moment) . How to write in Ti.Unit test?</p>
",https://stackoverflow.com/questions/52429992/unable-to-call-default-alloy-libraries-in-ti-unit-framework,"['unit-testing', 'appcelerator', 'appcelerator-titanium', 'appcelerator-alloy', 'appcelerator-studio']",27,FALSE,0,0
"&#39;Provided id of the wrong type&#39;, even though table id is set with auto_increment?","<p>I am creating an h2 table for unit testing, the table is created with this sql:</p>

<pre><code>CREATE TABLE IF NOT EXISTS RULE_LIST
(
   RULE_LIST_ID BIGINT AUTO_INCREMENT primary key,
   RULE_TYP_CDE varchar(10) NOT NULL,
   RULE_GROUP varchar(50),
   RULE_NM varchar(128),
);
</code></pre>

<p>I then attempt to insert a row with:</p>

<pre><code>DELETE FROM RULE_LIST;
INSERT INTO RULE_LIST(
  RULE_TYP_CDE,
  RULE_GROUP,
  RULE_NM
)
VALUES (
  'testType',
  'testGroup',
  'testName'
);
</code></pre>

<p>But this results in the exception:
<code>java.lang.IllegalArgumentException: Provided id of the wrong type for class [associated java entity]. Expected: class java.lang.Long, got class java.lang.Integer</code>.
I don't know where or what is trying to insert an integer for the id, as I thought it would be generated with auto_increment and I did not include an integer in my insert statement. What's going on here?</p>
",https://stackoverflow.com/questions/53577139/provided-id-of-the-wrong-type-even-though-table-id-is-set-with-auto-increment,"['sql', 'hibernate', 'jpa', 'h2']",58,FALSE,0,0
Testing simple React component using Jest and enzyme - what did I wrong?,"<p>I'm 'unit testing' greenhorn. What did I wrong here? How can I test such simple components?</p>

<p><code>test.js</code></p>

<pre><code>import React from 'react';
import { shallow } from 'enzyme';
import StartButton from './';

describe('StartButton', () =&gt; {
  const wrapper = shallow(&lt;StartButton /&gt;);

  it('renders correctly', () =&gt; {
    expect(wrapper).toMatchSnapshot();
  });

  it('renders correctly', () =&gt; {
    expect(wrapper.find('.StartButton-container')).to.have.length(1);
  });
});
</code></pre>

<p><code>startButton</code></p>

<pre><code>import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';

import './style.css';

const StartButton = () =&gt; (
  &lt;div className=""StartButton-container""&gt;
    &lt;RaisedButton
      label=""Start Here""
      className=""StartButton-main-button""
      //onClick={this.addBeer}
    /&gt;
  &lt;/div&gt;
);

export default StartButton;
</code></pre>

<p><code>error</code></p>

<blockquote>
  <p>FAIL  src\components\StartButton\test.js   ● StartButton › renders
  correctly</p>

<pre><code>TypeError: Cannot read property 'have' of undefined

  at Object.it (src/components/StartButton/test.js:13:54)
      at new Promise (&lt;anonymous&gt;)
  at Promise.resolve.then.el (node_modules/p-map/index.js:46:16)
      at &lt;anonymous&gt;
  at process._tickCallback (internal/process/next_tick.js:188:7)
</code></pre>
  
  <p>PASS  src\components\App\test.js</p>
  
  <p>Test Suites: 1 failed, 1 passed, 2 total Tests:       1 failed, 2
  passed, 3 total Snapshots:   2 passed, 2 total Time:        0.181s,
  estimated 1s Ran all test suites related to changed files.</p>
  
  <p>Watch Usage: Press w to show more.</p>
</blockquote>
",https://stackoverflow.com/questions/49268324/testing-simple-react-component-using-jest-and-enzyme-what-did-i-wrong,"['javascript', 'reactjs', 'unit-testing', 'enzyme', 'jestjs']",103,TRUE,0,2
How do I test for speed with PyTest / tox?,"<p>For testing machine learning algorithms / repositories, I see three things that matter:</p>

<ol>
<li>Does it crash</li>
<li>Does it have a minimum test accuracy</li>
<li>Is it fast enough</li>
</ol>

<p>While (1) and maybe (2) is standard unit testing, I'm not too sure how to deal with (3). Can I test this with pytest / tox?</p>

<p>I found <a href=""https://pypi.python.org/pypi/pytest-benchmark"" rel=""nofollow noreferrer""><code>pytest-benchmark</code></a>, but how would I do this for example for <a href=""https://github.com/MartinThoma/lidtk/blob/master/tests/test_classifiers.py#L15-L16"" rel=""nofollow noreferrer""><code>lidtk</code></a>?</p>

<p>In pseudo-code, I want to do the following:</p>

<pre><code>def classifier_predict(input_features):
    # do something smart, but maybe too time-consuming
    return result

def input_generator():
    # Generate something random which classifier_predict
    # can work on - don't measure this time!
    return input_features

class Agents(unittest.TestCase):
    def test_classifier_predict():
        self.assertMaxTime(classifier_predict,
                           input_generator,
                           max_time_in_ms=100)
</code></pre>
",https://stackoverflow.com/questions/48264284/how-do-i-test-for-speed-with-pytest-tox,"['python', 'testing', 'benchmarking', 'tox', 'pytest-benchmark']",723,TRUE,0,1
"How do i do unit test on else statement that just return. - Nodejs, Sinon","<p>I am doing my unit testing in nodejs using sinon.</p>

<p>How do test for the else portion for my task1.js? It is suppose to be if my count is not 0, i will proceed to my own processing, else I end my task.</p>

<p>I can mock my getbookForUpdateCount to return count values but what comes next?</p>

<p>How do i ensure that that path is taken?</p>

<p><strong>Task1.js:</strong></p>

<pre><code>function updateInfo() {

    bookDao.getbookForUpdateCount(updateCountParams, function (results) {

        console.log(""Step 1: "" + results[0].RECCOUNT + "" for updates!"".blue);
        //1. Get count. If &gt; 0, proceed. else end task.
        if (results[0].RECCOUNT &gt; 0) {

            ...
            //some other functions
        }
        else {
            //no record to be processed.
            return;
        }
    });
}
</code></pre>
",https://stackoverflow.com/questions/53182555/how-do-i-do-unit-test-on-else-statement-that-just-return-nodejs-sinon,"['node.js', 'unit-testing', 'sinon']",595,FALSE,0,1
Mockito.verify with KafkaProducer and ProducerRecord,"<p>I'm unit testing a very simple wrapper class for a KafkaProducer whose send method is simply like this</p>

<pre><code>public class EntityProducer { 
    private final KafkaProducer&lt;byte[], byte[]&gt; kafkaProducer;
    private final String topic;

    EntityProducer(KafkaProducer&lt;byte[], byte[]&gt; kafkaProducer, String topic)
    {
        this.kafkaProducer = kafkaProducer;
        this.topic = topic;
    }

    public void send(String id, BusinessEntity entity) throws Exception
    {
        ProducerRecord&lt;byte[], byte[]&gt; record = new ProducerRecord&lt;&gt;(
            this.topic,
            Transformer.HexStringToByteArray(id),
            entity.serialize()
        );
        kafkaProducer.send(record);
        kafkaProducer.flush();
    }
}
</code></pre>

<p>The unit test reads as follows:</p>

<pre><code>@Test public void send() throws Exception
{
    @SuppressWarnings(""unchecked"")
    KafkaProducer&lt;byte[], byte[]&gt; mockKafkaProducer = Mockito.mock(KafkaProducer.class);
    String topic = ""mock topic"";
    EntityProducer producer = new EntityProducer(mockKafkaProducer, topic);

    BusinessEntitiy mockedEntity = Mockito.mock(BusinessEntity.class);
    byte[] serialized = new byte[]{1,2,3};
    when(mockedCipMsg.serialize()).thenReturn(serialized);

    String id = ""B441B675-294E-4C25-A4B1-122CD3A60DD2"";
    producer.send(id, mockedEntity);

    verify(mockKafkaProducer).send(
        new ProducerRecord&lt;&gt;(
            topic,
            Transformer.HexStringToByteArray(id),
            mockedEntity.serialize()
        )
    );

    verify(mockKafkaProducer).flush();
</code></pre>

<p>The first verify method fails, hence the test failis, with the following message:</p>

<pre><code>Argument(s) are different! Wanted:
kafkaProducer.send(
    ProducerRecord(topic=mock topic, partition=null, key=[B@181e731e, value=[B@35645047, timestamp=null)
);
-&gt; at xxx.EntityProducerTest.send(EntityProducerTest.java:33)
Actual invocation has different arguments:
kafkaProducer.send(
    ProducerRecord(topic=mock topic, partition=null, key=[B@6f44a157, value=[B@35645047, timestamp=null)
);
</code></pre>

<p>What is most relevant is that the key of the ProducerRecord is not the same, the value appears the same</p>

<p>Is the unit test properly oriented? How may I make the test pass?</p>

<p>Kind regards.</p>
",https://stackoverflow.com/questions/52869183/mockito-verify-with-kafkaproducer-and-producerrecord,"['java', 'apache-kafka', 'mockito']",6346,TRUE,3,2
Chai POST request test does not send email,"<p>New to unit testing an API.</p>

<p>Using Chai, I am trying to test a POST request to an API.
Basically, the POST request should add the details into the database and send a confirmation email to the entered email address.</p>

<p>My tests checks for the data been added to the database. But whenever the test is run, it does not sends the confirmation email from the POST request.</p>
",https://stackoverflow.com/questions/51048572/chai-post-request-test-does-not-send-email,"['node.js', 'api', 'unit-testing', 'testing', 'chai']",271,TRUE,0,1
Listen To call on a struct function used by another struct in Golang,"<p>So I am a beginner with mocking struct and functions in Golang. I basically want to check if a function has been called for unit testing purpose. Here is the code:</p>

<pre><code>type A struct {

}

func (a *A) Foo (){}

type B struct {
    a *A
}

func (b* B) Bar () {
    a.Foo()
}
</code></pre>

<p>I basically want to check that Foo is indeed called when Bar is called </p>

<p>I know there is some mock framework available for Golang but they are pretty complicated when it comes to testing existing struct and struct methods</p>
",https://stackoverflow.com/questions/52104610/listen-to-call-on-a-struct-function-used-by-another-struct-in-golang,"['go', 'mocking']",580,TRUE,0,1
How to mock struct methods in Golang,"<p>I'm reading this page (I'm not using Amazon, just reading for golang education)</p>

<p><a href=""https://aws.amazon.com/blogs/developer/mocking-out-then-aws-sdk-for-go-for-unit-testing/"" rel=""nofollow noreferrer"">https://aws.amazon.com/blogs/developer/mocking-out-then-aws-sdk-for-go-for-unit-testing/</a></p>

<p>When I try it for myself, I get type errors.</p>

<pre><code>type Queue struct {
    Client ThirdPartyStruct
    URL    string
}

type mockedReceiveMsgs struct {
    ThirdPartyStruct
    Resp ValueIWantToMock
}

q := Queue{Client: mockedReceiveMsgs{}}
</code></pre>

<p>When I try to do the exact same thing, I get</p>

<pre><code>cannot use mocked literal (type mockedReceiveMsgs) as type ThirdPartyStruct in field value
</code></pre>

<p>I feel like I'm copying the Amazon tutorial exactly. How come in there code, mockedReceiveMsgs can be used in place of ThirdPartyStruct?</p>
",https://stackoverflow.com/questions/48179565/how-to-mock-struct-methods-in-golang,"['unit-testing', 'go', 'mocking']",3418,TRUE,0,2
i want to test a method in a repository with events phpunit laravel,"<p>Hello everyone I am new to Unit testing and I am stuck on this </p>

<p>Here is the repository method I am testing => </p>

<pre><code>public function store(array $input){

        $input['billing_contact'] = (isset($input['billing_contact'])) ? 1 : 0;  
        \DB::beginTransaction();
        try {
            $new_contact = $this-&gt;model-&gt;create($input);

            //EVENT CREATE ACCOUNT (USER)
            event(new EventCreateUserWithContact($new_contact));
            \DB::commit();
        }
        catch(\Exception $e){
            \DB::rollback();
            return false;
        }


        return $new_contact;

    }
</code></pre>

<p>Here is the test that I am trying to make =></p>

<pre><code>class ContactTest extends TestCase
{
    use WithFaker;
    protected $contact;/**/
    protected $container;/**/

    public function setup()
    {
        parent::setup();
        $this-&gt;container = new \Illuminate\Container\Container();
        $this-&gt;contact = new Contact();
        DB::beginTransaction();
    }
    public function tearDown()
    {
        DB::rollback();
        parent::tearDown();
    }
    /**
     * A basic test example.
     *
     * @return void
     */
    public function testContactRepo()
    {
//        Event::();
        $publisher = factory(\App\Models\Publisher::class)-&gt;create();
        $contact =  factory(\App\Models\Contact::class)-&gt;create();


//
        $data =  [

            'first_name' =&gt; $this-&gt;faker-&gt;word,
            'last_name'=&gt;  $this-&gt;faker-&gt;word,
            'email' =&gt; $this-&gt;faker-&gt;unique()-&gt;safeEmail,
            'phone'=&gt; 112321321,
            'job'=&gt; $this-&gt;faker-&gt;word,
            'billing_contact'=&gt; $this-&gt;faker-&gt;word,
            'approve_delete_at'=&gt; $this-&gt;faker-&gt;date('Y-m-d',  '1461067200'),
            'publisher_id'=&gt; $publisher-&gt;id,

        ];

        $rep = new ContactRepositoryEloquent($this-&gt;container);

        $contact = $rep-&gt;store($data);
    dd($contact);


    }
}
</code></pre>

<p>I do not understand how to get the new contact object because I got an exception error when I run the test (I get false)
Do I need to create a fake event to make it worked? </p>
",https://stackoverflow.com/questions/52551793/i-want-to-test-a-method-in-a-repository-with-events-phpunit-laravel,"['php', 'laravel', 'unit-testing', 'phpunit', 'repository']",405,TRUE,0,1
Compress InputStream with GZIPOutputStream into ByteArray,"<p>I have a method that takes an InputStream as a parameter and I'm trying to compress the input stream using GZIPOutputStream and then return a compressed byte array. My code looks like this:</p>

<pre><code>    public static byte[] compress(final InputStream inputStream) throws IOException {
    final int byteArrayOutputStreamSize = Math.max(32, inputStream.available());
    try(final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(byteArrayOutputStreamSize);
    final GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream)) {
        IOUtils.copy(inputStream, gzipOutputStream);
        return byteArrayOutputStream.toByteArray();
    }
}
</code></pre>

<p>But somehow it doesn't seem to be working. I'm trying to perform unit testing on this with the following code:</p>

<pre><code>    @Test
public void testCompress() throws Exception {
    final String uncompressedBytes = ""some text here"".getBytes();
    final InputStream inputStream = ByteSource.wrap(uncompressedBytes).openStream();
    final byte[] compressedBytes = CompressionHelper.compress(inputStream);
    Assert.assertNotNull(compressedBytes);
    final byte[] decompressedBytes = decompress(compressedBytes);
    Assert.assertEquals(uncompressedBytes, decompressedBytes);
}

public static byte[] decompress(byte[] contentBytes) throws Exception {
    try (ByteArrayOutputStream out = new ByteArrayOutputStream();
         ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(contentBytes);
         InputStream inputStream = new GZIPInputStream(byteArrayInputStream)) {
        IOUtils.copy(inputStream, out);
        return out.toByteArray();
    }
}
</code></pre>

<p>But I'm getting this exception </p>

<blockquote>
  <p>java.io.EOFException: Unexpected end of ZLIB input stream</p>
</blockquote>

<p>What I'm i doing wrong?</p>
",https://stackoverflow.com/questions/48980472/compress-inputstream-with-gzipoutputstream-into-bytearray,"['java', 'inputstream', 'bytearrayoutputstream', 'gzipoutputstream', 'ioutils']",2118,TRUE,0,1
What is the best practice to test private methods in Angular 2 / Typescript,"<p>I've created Angular 5 project and writing unit tests using Karma, Jasmine. I don't like the idea of making all methods public only for accessing from tests.</p>

<pre><code>export class AppComponent {
    mainMenu: any[];

    constructor(
        private menuService: MenuService
    ) {}

    ngOnInit(): void {
        this.initTable();
        this.initMenu();
    }

    private initTable(): void {
        // ... initializes array for table
    }

    private initMenu(): void {
        this.menuService.getMainMenu()
            .subscribe(data =&gt; this.mainMenu = data);
    }
}
</code></pre>

<p><code>initTable</code> and <code>initMenu</code> methods are just helpers for dividing the code and make more organized and readable, I don't need them to be accessible in <code>public</code> mode. But here I'm facing the problem with unit testing, here's how my test case should look like:</p>

<pre><code>it ('Should call menuService.getMainMenu', () =&gt; {
    spyOn(menuService, 'getMainMenu').and.returnValue(Observable.of([]));

    // this will throw exception
    component.initMenu();

    expect(menuService.getMainMenu).toHaveBeenCalled();
});
</code></pre>

<p>Any ideas?</p>
",https://stackoverflow.com/questions/49130030/what-is-the-best-practice-to-test-private-methods-in-angular-2-typescript,"['angular', 'unit-testing', 'typescript', 'karma-jasmine']",6893,TRUE,0,1
In Memory database vs Moqing framework in .NET Core,"<p>we are going to implement TDD approach in our next project. So I have been studying Unit Testing with NUnit in ASP.NET Core. As I am new I am confused about few things. So I would like to share these questions with you for making decisions based on the expert opinions. </p>

<ol>
<li>What are the Pros and Cons of Mocking database and In-Memory database? </li>
<li>In which situation, we should use Mocking and in what situation we should go with InMemory database provider?</li>
<li>Which is the better approach, using InMemory or using Mocking?</li>
<li>Can we implement both approaches together in the same project?</li>
<li>For integration testing, should we use mocking or In Memory?</li>
<li>Is it a better approach to use the In-Memory database in Unit Testing?</li>
<li>While testing Business Layer, should we use Mocking or In-Memory database?</li>
<li>While testing MVC Controller, should we use Mocking or In-Memory database?</li>
</ol>

<p>Please help me to find the answers to these questions. It might be that, some questions are similar, however, I don't want to remove them for having a better understanding from you guys. Thanks.</p>
",https://stackoverflow.com/questions/50154414/in-memory-database-vs-moqing-framework-in-net-core,"['unit-testing', 'asp.net-core-mvc', 'tdd', 'moq', 'in-memory-database']",2827,TRUE,4,1
Is it possible to generate an x509 certificate in Javascript?,"<p>I have been assigned some JavaScript tasks at work to help me gain exposure with that language. So I'm writing a unit test for a JavaScript implementation someone else has written. I have some tests working but I still need to use an x509 cert for testing. Since placing a file on a CI server is not an option, how can I create an x509 cert for unit testing?</p>
",https://stackoverflow.com/questions/51882313/is-it-possible-to-generate-an-x509-certificate-in-javascript,"['javascript', 'x509certificate']",739,FALSE,0,0
c# xunit colour testing not work,"<pre><code> [Theory]
    [InlineData(0.75)]
    public void ColorBindTest2(double max)
    {
        DefaultColorUnit.MediumColorStatic = Colors.Yellow;
        DefaultColorUnit.HighColorStatic = Colors.Red;
        var excepted = Colors.Orange;

        Color actual = _asd.renkata(max).Item2;

        Assert.Equal(excepted.R, actual.R);
        Assert.Equal(excepted.G, actual.G);
        Assert.Equal(excepted.B, actual.B);
    }
</code></pre>

<p>This is my unit testing code and below is my real code</p>

<pre><code>public Tuple&lt;Brush, Color&gt; renkata(double val)
{

    byte r1 = DefaultColorUnit.LowColorStatic.R;
    byte g1 = DefaultColorUnit.LowColorStatic.G;
    byte b1 = DefaultColorUnit.LowColorStatic.B;


    byte r2 = DefaultColorUnit.MediumColorStatic.R;
    byte g2 = DefaultColorUnit.MediumColorStatic.G;
    byte b2 = DefaultColorUnit.MediumColorStatic.B;


    byte r3 = DefaultColorUnit.HighColorStatic.R;
    byte g3 = DefaultColorUnit.HighColorStatic.G;
    byte b3 = DefaultColorUnit.HighColorStatic.B;
    if (val &lt;= 1 &amp;&amp; val &gt; 0.5)
    {
        val = 2 * (Math.Abs(0.5 - val));

        Color p1 = new Color();

        byte r = (byte)((r3 * val) + r2 * (1 - val));
        byte g = (byte)((g3 * val) + g2 * (1 - val));
        byte b = (byte)((b3 * val) + b2 * (1 - val));
        p1 = Color.FromRgb(r, g, b);
        Brush sold = new SolidColorBrush(Color.FromRgb(r, g, b));

        return new Tuple&lt;Brush, Color&gt;(sold, p1);


    }
    else if (val == 0.5)
    {

        Brush sold = new SolidColorBrush(Color.FromRgb(r2, g2, b2));
        Color p1 = (Color.FromRgb(r2, g2, b2));

        return new Tuple&lt;Brush, Color&gt;(sold, p1);

    }
    else if (val &lt; 0.5 &amp;&amp; val &gt;= 0)
    {
        val = 2 * (Math.Abs(0.5 - val));
        val = 1 - val;
        Color p1 = new Color();

        byte r = (byte)((r2 * val) + r1 * (1 - val));
        byte g = (byte)((g2 * val) + g1 * (1 - val));
        byte b = (byte)((b2 * val) + b1 * (1 - val));
        p1 = Color.FromRgb(r, g, b);

        SolidColorBrush sold = new SolidColorBrush(Color.FromRgb(r, g, b));


        return new Tuple&lt;Brush, Color&gt;(sold, p1);
    }
    else if (val &gt; 1)
    {
        SolidColorBrush sold = new SolidColorBrush(Colors.Black);
        Color p1 = Colors.Black;
        return new Tuple&lt;Brush, Color&gt;(sold, p1);
    }
    else if (val &lt; 0)
    {
        SolidColorBrush sold = new SolidColorBrush(Colors.White);
        Color p1 = Colors.White;
        return new Tuple&lt;Brush, Color&gt;(sold, p1);
    }
    else
    {
        SolidColorBrush sold = new SolidColorBrush(Colors.Blue);
        Color p1 = Colors.Blue;
        return new Tuple&lt;Brush, Color&gt;(sold, p1);
    }
}
</code></pre>

<p>I want to testing my color calculator from three color colour gradient.
color.orange in visual studio is 255 165 0 but my orange is 255 127 0 my code is loking good on running. but testing it is not real orange where is my wrong is my code calculate wrong color rgb or colors.orange is not real orange.</p>
",https://stackoverflow.com/questions/51379622/c-xunit-colour-testing-not-work,"['c#', 'testing', 'colors', 'xunit']",302,FALSE,0,0
How to setup a method call inside another method call to return different results,"<p>I have a method similar to the following:</p>

<pre><code>public List&lt;Item&gt; MethodA() {
    List&lt;Things&gt; result1 = MethodB(param1);
    if(result1==null)
        //Do Something

    List&lt;Things&gt; result2 = MethodB(param2);

    //Do Something 
}
</code></pre>

<p>I tried mocking this method, using Moq, for unit testing as below:</p>

<pre><code>//Mocking the call to MethodB to return null the second time it's called
mockService.SetupSequence(x=&gt;x.MethodB(It.IsAny&lt;List&lt;Things&gt;&gt;()))
.Returns(GetList())
.Returns(null);

//Call to method A to run the test
MethodA();
</code></pre>

<p>However this doesn't seem to work and I get only the list as the returned result for MethodB after mocking. However, I want the list to be returned in the first call and null in the second call. Any pointers/thoughts/ideas how to achieve it would be really helpful. </p>
",https://stackoverflow.com/questions/52954609/how-to-setup-a-method-call-inside-another-method-call-to-return-different-result,"['c#', 'unit-testing', 'moq']",372,TRUE,0,2
How should I unit test this React Component?,"<p>This is my component. It's basically a wrapper for another component. My question is how should I unit test this component? Apart from checking state and calling the two methods and making sure they update the state. </p>

<p>Apart from that, that just seems to render the props/state so is there any need to test this?</p>

<pre><code>import React from 'react';
import { PropTypes as PT } from 'prop-types';

export default Wrapped =&gt;
  class extends React.Component {
    static propTypes = {
      numOne: PT.number,
    };

    constructor(props) {
      super(props);

      this.state = {
        showModal: false,
      };
    }

    openModal = () =&gt; {
      this.setState({
        showModal: true,
      });
    };

    closeModal = () =&gt; {
      this.setState({
        showModal: false,
      });
    };

    render() {
      return (
        &lt;Wrapped
          numberValue={this.props.numOne}
          showHolidayModal={this.state.showHolidayListModal}
          showModal={this.openModal}
          closeModal={this.closeModal}
          {...this.props}
        /&gt;
      );
    }
  };
</code></pre>

<p>This is my component (just example) Which I am also unit testing, that it renders what is passed in</p>

<pre><code>import React from 'react';
import { PropTypes as PT } from 'prop-types';
import container from './container';
import { Card, Button, Modal } from '../common';

export const Leave = props =&gt; {
  return (
    &lt;div&gt;
      &lt;span&gt;Dummy data : {props.numberValue}&lt;/span&gt;
      {props.showModal &amp;&amp; &lt;Modal /&gt;}

      &lt;Button onClick={props.closeModal} label=""close"" /&gt;
    &lt;/div&gt;
  );
};

Leave.propTypes = {
  numberValue: PT.number,
  showModal: PT.bool,
  openModal: PT.func,
  closeModal: PT.func,
};

export default container(Leave);
</code></pre>
",https://stackoverflow.com/questions/50705392/how-should-i-unit-test-this-react-component,"['javascript', 'reactjs', 'unit-testing', 'jestjs', 'enzyme']",46,TRUE,2,1
Karma Jasmine Html report is not showing up on ng test,"<p>I'm not able to get karma jasmine Html report when running unit testing in chrome. Chrome is loading with component's html but not showing test results.</p>

<p>However i'm getting test results in terminal itself. I've tried adding below in karma.config.js but getting errors.</p>

<p>In Pulgins --> require('karma-jasmine-html-reporter')
In reporters --> kjhtml</p>

<p>{</p>

<pre><code>""message"": ""Uncaught TypeError: env.stopOnSpecFailure is not a function\nat node_modules/karma-jasmine-html-reporter/src/lib/adapter.js:26:7\n\nTypeError: env.stopOnSpecFailure is not a function\n    at node_modules/karma-jasmine-html-reporter/src/lib/adapter.js:26:7\n    at node_modules/karma-jasmine-html-reporter/src/lib/adapter.js:76:3"",

""str"": ""Uncaught TypeError: env.stopOnSpecFailure is not a function\nat node_modules/karma-jasmine-html-reporter/src/lib/adapter.js:26:7\n\nTypeError: env.stopOnSpecFailure is not a function\n    at node_modules/karma-jasmine-html-reporter/src/lib/adapter.js:26:7\n    at node_modules/karma-jasmine-html-reporter/src/lib/adapter.js:76:3""
</code></pre>

<p>}</p>

<p>Below are the versions in package.json </p>

<pre><code>""jasmine-core"": ""~2.99.1"",
""jasmine-spec-reporter"": ""^4.1.0"",
""karma"": ""~2.0.0"",
""karma-chrome-launcher"": ""^2.2.0"",
""karma-cli"": ""~1.0.1"",
""karma-coverage-istanbul-reporter"": ""^1.2.1"",
""karma-jasmine"": ""^1.1.0"",
""karma-jasmine-html-reporter"": ""^1.1.0"",
</code></pre>

<p>Below is the Karma.config.js</p>

<p>// Karma configuration file, see link for more information
// <a href=""https://karma-runner.github.io/1.0/config/configuration-file.html"" rel=""nofollow noreferrer"">https://karma-runner.github.io/1.0/config/configuration-file.html</a></p>

<pre><code>process.env.CHROME_BIN = require('puppeteer').executablePath();

module.exports = function(config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular/cli'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-junit-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular/cli/plugins/karma'),
      require('karma-jasmine-html-reporter')
    ],
    client: {
      clearContext: false, // leave Jasmine Spec Runner output visible in browser
      captureConsole: false
    },
    junitReporter: {
      outputDir: 'reports/junit/',
      outputFile: 'TESTS-xunit.xml',
      useBrowserName: false,
      suite: '' // Will become the package name attribute in xml testsuite element
    },
    coverageIstanbulReporter: {
      reports: ['html', 'lcovonly', 'text-summary'],
      dir: './reports/coverage',
      fixWebpackSourcePaths: true
    },
    angularCli: {
      environment: 'dev'
    },
    reporters: ['progress', 'junit', 'kjhtml'],
    port: 9876,
    colors: true,
    // Level of logging, can be: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
  });
};
</code></pre>
",https://stackoverflow.com/questions/50602712/karma-jasmine-html-report-is-not-showing-up-on-ng-test,"['angular', 'unit-testing', 'karma-jasmine']",3190,FALSE,5,0
EF Core SQLite in memory exception: SQLite Error 1: &#39;near &quot;MAX&quot;: syntax error&#39;,"<p>I am creating SQLite In Memory database for unit testing:</p>

<pre><code>        var connection = new SqliteConnection(""DataSource=:memory:"");
        connection.Open();

        try
        {
            var options = new DbContextOptionsBuilder&lt;BloggingContext&gt;()
                .UseSqlite(connection)
                .Options;

            // Create the schema in the database
            using (var context = new BloggingContext(options))
            {
                context.Database.EnsureCreated();
            }

            // Run the test against one instance of the context
            using (var context = new BloggingContext(options))
            {
                var service = new BlogService(context);
                service.Add(""http://sample.com"");
            }

            // Use a separate instance of the context to verify correct data was saved to database
            using (var context = new BloggingContext(options))
            {
                Assert.AreEqual(1, context.Blogs.Count());
                Assert.AreEqual(""http://sample.com"", context.Blogs.Single().Url);
            }
        }
</code></pre>

<p><strong>context.Database.EnsureCreated();</strong> fails with with exception:
<em>Message: Microsoft.Data.Sqlite.SqliteException : SQLite Error 1: 'near ""MAX"": syntax error'.</em></p>

<p>There is <a href=""https://github.com/aspnet/EntityFrameworkCore/issues/7030"" rel=""noreferrer"">github issue</a> saying: 
<em>The issue here is varchar(max) is SqlServer specific type. The scaffolding should not add it as relational type which gets passed to migration in other providers which is prone to generate invalid sql at migration.</em></p>

<p><strong>But how then can I use SQLite in Memory for unit tests if my database contains many varchar(max) columns?</strong></p>
",https://stackoverflow.com/questions/53560489/ef-core-sqlite-in-memory-exception-sqlite-error-1-near-max-syntax-error,"['c#', 'sqlite', 'entity-framework-core', 'ef-core-2.0', 'ef-core-2.1']",6312,FALSE,10,3
How to create test data in rspec,"<p>Hi i am working on rails app with ruby-2.5.0 and Rails 5. I have to test my forgot_password controller there is a method which validates if the email id is presnt in the database or not.</p>

<pre><code>forgot_password_controller.rb
# frozen_string_literal: true

class ForgotPasswordController &lt; ApplicationController

    def create
        user = User.find_by_email(forgot_password_params[:email])
        unless user.blank?
      render json: {}, status: 200
    else
      render json: {}, status: 404
    end
  rescue StandardError
    render json: {}, status: 500
  end

    private

  def forgot_password_params
    permitted = %i[email]
    params.require(:data)
          .require(:attributes)
          .permit(permitted)
          .transform_keys(&amp;:underscore)
  end
end
</code></pre>

<p>I want to test my api. i have written unit testing as follows:-</p>

<pre><code>forgot_password_controller_spec.rb
# frozen_string_literal: true

require 'rails_helper'

describe ForgotPasswordController do
  before do
    User.create!(email: 'xyz@gmail.com',
                 password: 'pass',
                 password_confirmation: 'pass')
  end

  describe 'POST create' do
    subject { post :create, params: params }

    context 'when email is found' do
      let(:params) do
        { data: { attributes: { email: 'xyz@gmail.com' } } }
      end

      it { is_expected.to have_http_status(200) }
    end

    context 'when email is not found' do
      let(:params) do
        { data: { attributes: { email: 'xyz2@gmail.com' } } }
      end

      it { is_expected.to have_http_status(404) }
    end

    context 'when wrong params passed' do
      let(:params) do
        { data: '' }
      end

      it { is_expected.to have_http_status(500) }
    end
  end
end
</code></pre>

<p>Now i want to create test data with 'let'
 like  </p>

<pre><code>let(:user) { instance_double('user') }
let(:save_result) { true }
</code></pre>

<p>How can i create user with let please help me. Thanks in advance.</p>
",https://stackoverflow.com/questions/49497513/how-to-create-test-data-in-rspec,"['ruby-on-rails', 'unit-testing', 'rspec']",3903,TRUE,2,1
How to debug HeadlessChrome 0.0.0 (Linux 0.0.0) ERROR { &quot;isTrusted&quot;: true } in Angular 6 unit test?,"<p>When I run my test suite, I get an error in a totally different unit test than the one I've been working in. What am I doing wrong?</p>

<pre><code>HeadlessChrome 0.0.0 (Linux 0.0.0) ERROR
{
    ""isTrusted"": true
}
</code></pre>

<p>It is then followed by some build steps and the following error during test execution:</p>

<pre><code>HeadlessChrome 0.0.0 (Linux 0.0.0) ERROR
  An error was thrown in afterAll
  [object ErrorEvent] thrown
</code></pre>

<p>If I comment out certain tests, say in class A, another test fails in Component B. If I comment those out, another test fails in Component C. <em>None of these tests has been updated recently so none of them should be failing.</em></p>

<p>I saw in <a href=""https://stackoverflow.com/questions/45722256/how-do-i-debug-a-object-errorevent-thrown-error-in-my-karma-jasmine-tests"">this question</a> that some people attribute this issue to the node_modules folder. However, I just mitigated a similar issue to this by reinstalling the node_modules folder yesterday. Is this that common of an error? <strong>It can't possibly be the case that developers are supposed to consistently delete and reinstall the node_modules folder.</strong> I must have done something wrong but all I've been doing is unit testing like usual.</p>

<p><strong>How can I debug and fix this Headless Chrome error so that I can get back to unit testing?</strong></p>

<p>Here are some stats about my environment:</p>

<p>Relevant Dependency versions:</p>

<pre><code>""@angular/cli"": ""6.0.8"",
    ""@angular/compiler-cli"": ""6.0.6"",
    ""@angular/language-service"": ""6.0.6"",
    ""@types/jasmine"": ""~2.5.53"",
    ""@types/jasminewd2"": ""~2.0.2"",
    ""@types/node"": ""~6.0.60"",
    ""codelyzer"": ""^4.0.1"",
    ""jasmine-core"": ""~2.6.2"",
    ""jasmine-spec-reporter"": ""~4.1.0"",
    ""karma"": ""~1.7.0"",
    ""karma-chrome-launcher"": ""~2.1.1"",
    ""karma-cli"": ""~1.0.1"",
    ""karma-coverage-istanbul-reporter"": ""^1.2.1"",
    ""karma-jasmine"": ""~1.1.0"",
    ""karma-jasmine-html-reporter"": ""^0.2.2"",
    ""ng-diff-match-patch"": ""^2.0.6"",
    ""protractor"": ""~5.1.2"",
    ""ts-node"": ""~3.2.0"",
    ""tslint"": ""~5.7.0"",
    ""typescript"": ""2.7.2"",
    ""@angular-devkit/build-angular"": ""~0.6.8""
</code></pre>

<p>Relevant Karma.conf settings:</p>

<pre><code>reporters: ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['ChromeHeadless'],
    singleRun: false,
    customLaunchers: {
      ChromeHeadless: {
        base: 'Chrome',
        flags: [
          '--headless',
          // '--disable-gpu',
          '--no-sandbox',
          // Without a remote debugging port, Google Chrome exits immediately.
          '--remote-debugging-port=9222',
        ],
      }
    },
    browserDisconnectTolerance: 8,
    browserNoActivityTimeout: 60000,
    browserDisconnectTimeout: 20000,
</code></pre>
",https://stackoverflow.com/questions/51863488/how-to-debug-headlesschrome-0-0-0-linux-0-0-0-error-istrusted-true-in-a,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine', 'karma-runner']",4598,TRUE,2,1
"How to unit-test an object that contain a type union using typescript, karma and sinon?","<p>I'm doing unit-testing for a project which is written in typescript with angular framework, by applying karma with mocha and chai frameworks. And there's an interface for the object as: </p>

<pre><code>interface ISolution {
    _id: string;
    paymentFrequency: PaymentFrequency;
};
</code></pre>

<p>And PaymentFrequency type is defined as:</p>

<pre><code>type PaymentFrequency = 'MONTHLY' | 'ANNUAL' | 'SINGLE';
</code></pre>

<p>In the controller,</p>

<pre><code>open(solution: ISolution) { };
</code></pre>

<p>The problem is when I tried to mock the solution as:</p>

<pre><code>let solution = { _id: 'aa0', paymentFrequency: 'MONTHLY', ....};
let spy = sandbox.stub(controller, 'open').withArgs(solution);
</code></pre>

<p>Typescript gave me the error as ""type string is not assignable to type paymentFrequency"". Let me know if there's a way to handle it.</p>
",https://stackoverflow.com/questions/49192377/how-to-unit-test-an-object-that-contain-a-type-union-using-typescript-karma-and,"['angularjs', 'unit-testing', 'typescript', 'mocha.js', 'sinon-chai']",648,TRUE,1,2
How to get stackTrace from caller,"<p>I want to be able to display in the log who caused the error:</p>

<pre><code>def printError(errorMessage: String): Error = {
   new Error(errorMessage, /* create stack trace */)
}

def badMethod(...): IO[Error, ...] = {
    ...
    IO.fail(printError(""This is bad""))
}
</code></pre>

<p>I want something inside <code>printError</code> which would show that the error was created in <code>badMethod</code>. </p>

<p>I tried with <code>Thread.getAllStackTraces.get(Thread.currentThread()).toList</code> but I get the head of the stack in <code>printError</code>. </p>

<p>In unit testing, there is the <code>Position</code> class which could do that but I don't know how to use it in none-test context. </p>

<p>Maybe some <code>implicit</code> something would do it ? </p>

<p>Any idea ? </p>

<p>Thank you. </p>
",https://stackoverflow.com/questions/53953059/how-to-get-stacktrace-from-caller,"['scala', 'functional-programming']",254,TRUE,1,2
Controller implementing interface not instantiated after adding @Validated spring annotation,"<p>I have a below RestController where I am trying to validate search() method input parameter map for empty. However during unit testing this RestController is not instantiated when it implements ServiceIF interface. If I comment implementing interface then controller is instantiated and validation works properly. I do not understand why annotating @Validated for a class which implements some interface does not work.</p>

<pre><code>@Validated
@RestController
public class MyServiceImpl implements ServiceIF{

    @RequestMapping(value = ""search"", method = RequestMethod.POST, produces = APPLICATION_JSON)
    public ResponseEntity&lt;Object&gt; search(@RequestBody @NotEmpty Map&lt;String, String&gt; body) {
    }
}
</code></pre>

<p>I am writing a below unit test to validate for empty map :</p>

<pre><code>RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { Application.class})
public class MyServiceImplTest {

    @Autowired
    private ServiceIF controller;
    private MockMvc mockMvc;

    @Before
    public void setUp(){
            mockMvc = MockMvcBuilders.standaloneSetup(controller)
                                    .setControllerAdvice(new InputValidationsExceptionHandler())
                                    .build();
    }

    @After
    public void tearDown(){
            mockMvc = null;
    }

    @Test
    public void testSearchInvalid() throws Exception{
        ObjectMapper mapper = new ObjectMapper();
        Map&lt;String, String&gt; map = new HashMap&lt;&gt;();
        String data = mapper.writeValueAsString(map);

        //Test invalid case
        this.mockMvc.perform(post(""/search"").content(data)
                                .contentType(MediaType.APPLICATION_JSON))
                                .andDo(print())
                                .andExpect(status().isBadRequest());

    }
} 
</code></pre>
",https://stackoverflow.com/questions/53678149/controller-implementing-interface-not-instantiated-after-adding-validated-sprin,"['spring', 'spring-mvc', 'spring-boot', 'spring-validator']",1556,TRUE,1,1
Bitbucket / git checkout specific folders when running pipeline,"<p>I'm working with a set of applications stored in a git repository.  Some code is suitable for unit testing, but quite a bit of it isn't (yet).  </p>

<p>I set up a bitbucket pipeline to build and test the unit-testable code.  That seems to work fine.</p>

<p>I would like to avoid checking out the remainder of the code.  Is there a way to check out only a subset of the branch?</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/51574713/bitbucket-git-checkout-specific-folders-when-running-pipeline,"['git', 'bitbucket', 'bitbucket-pipelines']",1448,FALSE,1,1
testing to check if a function calls another function if requirements are met,"<p>I am new to unit testing and was working on an example problem where I am getting very confused. </p>

<p>In the example below, I need to test if function onPost is called, after onSubmitHandler is called, given that the boolean value of employee is true. </p>

<pre><code>class Employee extends React.Component{

    function onSubmitHandler(){
        if(employee){
            this.onPost()
        }
        else {
            this.onFailure()
        }

    }

    function onPost(){
        return something
    }

    function onFailure(){
        return something
    }

    render(){
        return(&lt;EmployeeForm onAdd = {onSubmitHandler} /&gt;
        )
    }
}
</code></pre>

<p>Below is the test I created.   </p>

<pre><code>   test('onPost is called',()=&gt;{
        const wrapper  = shallow (&lt;Employee/&gt;)
        wrapper.instance().onSubmitHandler()
        Employee.onPost= jest.fn()
        expect(Employee.onPost).toBeCalled()


    })
</code></pre>

<p>This test is failing and I was wondering if I could get some clarification on how to go about testing the function. Thank you.</p>
",https://stackoverflow.com/questions/49593055/testing-to-check-if-a-function-calls-another-function-if-requirements-are-met,"['reactjs', 'jestjs']",3868,TRUE,1,1
Is there any way to unit test xamarin.forms app and use the test set for c.i. with app center?,"<p>I am new to testing for xamarin forms and unit testing in general. I've created an unit test project for my xamarin.forms app, I wrote some basic unit tests and I was wondering if I can run these test using appcenter and continuos integration. 
I can run these tests only on windows pc locally, but my ci server runs on Mac so I was wondering what approach can I use to unit test my app.</p>
",https://stackoverflow.com/questions/52389328/is-there-any-way-to-unit-test-xamarin-forms-app-and-use-the-test-set-for-c-i-wi,"['unit-testing', 'xamarin.forms', 'continuous-integration', 'automated-tests', 'visual-studio-app-center']",848,TRUE,1,2
AngularJS Karma check url param is present,"<p>I'm new to unit testing and trying to write a unit test for my app. My Route is :</p>

<pre><code>{
    name: 'details',
    url: '/accounts/company/:companyId',
    controller: 'controllere',
    templateUrl: 'templateurl',
}
</code></pre>

<p>My Controller :</p>

<pre><code>if (!$stateParams.companyId) {
    $scope.promise = $state.go('home');
} else {
    // get company details
}
</code></pre>

<p>In my unit test I need to test if ""companyId"" is present in the URL, then only proceed with the rest else redirect to ""home"". I tried this code but it fails everytime. I don't know what wrong I'm doing.</p>

<pre><code>it('should respond to URL with params', function() {
    expect($state.href('/accounts/company/', { companyId: 'test-company' })).toEqual('#/accounts/company/test-company');
});
</code></pre>

<p>Everytime I run this test it says : Expected null to equal '#/accounts/company/test-company'.</p>
",https://stackoverflow.com/questions/49746678/angularjs-karma-check-url-param-is-present,"['angularjs', 'unit-testing', 'karma-jasmine', 'karma-webpack']",987,FALSE,1,1
Unit test / mock getAttribute angular5,"<p>I'm unit testing a method that begins with an if statement like</p>

<pre><code>if(document.body.querySelector('#elementID li').getAttribute('disabled') === 'false')
</code></pre>

<p>My HTML code looks like:</p>

<pre><code>&lt;ul id=""elementID""&gt;
    &lt;li *ngFor=""let item of items; [attr.disabled]=""data.isDisabled""""&gt;&lt;/li&gt;
&lt;/ul&gt;
</code></pre>

<p>No matter what I do, I always get the error <strong>TypeError: Cannot read property 'getAttribute' of null</strong>. I know how to test the logic after the if statement, I just cannot get past it. </p>

<p>I've tried to create the li dynamically in my tests and I used the setAttribute like </p>

<pre><code> it('should test', () =&gt; {
    let element = document.createElement('ul')
    element.setAttribute('id', 'elementID')
    let li = document.createElement('li');
    li.setAttribute('disabled', 'false');
    element.appendChild(li);
    component.Method();
    expect(someVariable).toBeTruthy();
 }
</code></pre>

<p>but that doesn't work. Any Ideas?</p>
",https://stackoverflow.com/questions/49823901/unit-test-mock-getattribute-angular5,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",1503,FALSE,1,0
Cannot add a new project to an MVC application,"<p>I am teaching myself MVC and I am trying to learn how to do unit testing.  I wish to add a xUnit Test Project through my solution explorer but I do not see the option to add a new project.  I right click on the solution explorer, select add, and there are options to add new item, existing item, etc.. but no option to add a new project.  Any help would be appreciated.  </p>
",https://stackoverflow.com/questions/48106497/cannot-add-a-new-project-to-an-mvc-application,"['visual-studio', 'model-view-controller']",22,FALSE,0,0
Dependency Injection object creation clarification,"<p>I'm putting together a unit testing training class for C# developers.  I can debug through the code and see what's happening in some simple dependency injection examples.  But I can't find the words / phrases to accurately describe what is happening when we create a class object and pass it a new Service.   </p>

<p>Two questions. </p>

<p>How is this </p>

<pre><code>var test = new Service();
Client client = new Client(test);
</code></pre>

<p>different that this?</p>

<pre><code>Client client = new Client(new Service());
</code></pre>

<p>And what is the term used for the Service in this example? </p>

<pre><code>new Client(new Service());
</code></pre>
",https://stackoverflow.com/questions/50829297/dependency-injection-object-creation-clarification,"['c#', 'dependency-injection']",77,TRUE,0,1
testing an input with junit,"<p>So I developing this very simple game of TicTacToe. I want to test the method given below: </p>

<pre><code>public class Board {

    private Scanner scan = new Scanner(System.in);

    public int inputBoardSize() {
        while (flag) {
            System.out.print(""Enter the number of grids you want to play with:"");
            try {
                boardSize = Integer.parseInt(scan.next());
                if (boardSize &lt; 3 || boardSize &gt; 10) {
                    System.out.println(""Please choose a board size between 3 and 10"");
                    continue;
                }
                flag = false;
                break;
            } catch (NumberFormatException e) {
                e.getMessage();
                System.out.println(""Please enter a number"");
                continue;
            }

        }
        printBoard(boardSize);
        return boardSize;
    }
</code></pre>

<p>But I am new to unit testing and need a little help. I am not able to figure out how to test two conditions </p>

<ol>
<li>the NumberFormatException</li>
<li>When the input is not between 3 and 10. </li>
</ol>

<p>My testing class for the second condition is something like this:</p>

<pre><code>public class BoardTest extends TestCase {

    @Test
    public void test() {
        Board board = new Board();

        String input = ""2"";
        InputStream in = new ByteArrayInputStream(input.getBytes());
        System.setIn(in);

    }
}
</code></pre>

<p>I am not able to figure out what to do next.</p>
",https://stackoverflow.com/questions/49717299/testing-an-input-with-junit,"['java', 'unit-testing', 'junit', 'mockito']",918,TRUE,0,2
Custom builtin functions in jsonnet,"<p>Is there a way how I can call golang functions from jsonnet?</p>

<p>Now that there is a go port of jsonnet and for example ksonnet is adding <a href=""https://github.com/ksonnet/ksonnet/pull/521"" rel=""nofollow noreferrer"">custom native functions</a> I am wondering if there is a way how to extend jsonnet with more native functions?</p>

<p>I have many packages written in golang (with unit-testing, etc) and now it seems like I will need to rewrite some of them into jsonnet.</p>
",https://stackoverflow.com/questions/50400405/custom-builtin-functions-in-jsonnet,"['go', 'jsonnet']",469,TRUE,0,1
Lumen / Laravel: Can&#39;t figure out how unittesting a json response works,"<p>I can't figure out how unit testing works.</p>

<p>I have controller which returns a JSON response</p>

<p><strong>Controller.php</strong></p>

<pre><code>public function getDiscount(Request $request)
{
    if (isset($request) &amp;&amp; !empty($request)) {
        return response()-&gt;json($this-&gt;discount-&gt;calculateDiscount($request-&gt;json()-&gt;all()))-&gt;getOriginalContent();
    }
}
</code></pre>

<p>With postman, this is the result of this route:</p>

<p><strong>Post by client:</strong></p>

<pre><code>{
  ""customer-id"": ""3"",
  ""items"": [
    {
      ""product-id"": ""A101"",
      ""quantity"": ""2"",
      ""unit-price"": ""9.75"",
      ""total"": ""19.50""
    },
    {
      ""product-id"": ""A102"",
      ""quantity"": ""1"",
      ""unit-price"": ""49.50"",
      ""total"": ""49.50""
    }
  ],
  ""total"": ""69.00""
}
</code></pre>

<p><strong>Response by API</strong></p>

<pre><code>{
    ""applied_discounts"": [
        {
            ""id"": 3,
            ""name"": ""Tools Discount"",
            ""description"": ""Seems like you really like Tools, here's one for free!""
        }
    ],
    ""discounted_items"": [
        {
            ""product-id"": ""A101"",
            ""quantity"": ""2"",
            ""unit-price"": ""9.75"",
            ""total"": ""19.50"",
            ""discounted_price"": 15.6
        }
    ],
    ""discounted_price"": 65.1,
    ""original_price"": ""69.00""
}
</code></pre>

<p>Now when I try to make unit test, this is what I came up with:</p>

<pre><code>public function testToolsDiscount()
{
    $this-&gt;json('POST', '/discount',
        [
            'customer-id' =&gt; '3',
            'items' =&gt; [
                [
                    'product-id' =&gt; 'A101',
                    'quantity' =&gt; '2',
                    'unit-price' =&gt; '9.75',
                    'total' =&gt; '19.50'
                ],
                [
                'product-id' =&gt; 'A102',
                'quantity' =&gt; '1',
                'unit-price' =&gt; '49.50',
                'total' =&gt; '49.50'
                ]
            ],
            'total' =&gt; '69.00'
        ])
        -&gt;seeJson(
            [
            'applied_discounts' =&gt; [
                [
                    'id' =&gt; 3,
                ]
            ],
        ]);
}
</code></pre>

<p>However when I run it, this is the error I get</p>

<blockquote>
  <p>DiscountTest::testToolsDiscount Invalid JSON was returned from the
  route. Perhaps an exception was thrown?</p>
</blockquote>

<p>What am I doing wrong?</p>
",https://stackoverflow.com/questions/51293530/lumen-laravel-cant-figure-out-how-unittesting-a-json-response-works,"['php', 'laravel', 'unit-testing', 'lumen']",1046,TRUE,3,3
ENONET error while running jest-preset-angular,"<p>I am trying to integrate jest for my angular project for unit testing.</p>

<p>I followed the instructions from <a href=""https://www.xfive.co/blog/testing-angular-faster-jest/"" rel=""nofollow noreferrer"">this link</a>.</p>

<p>I am facing a weird error as <code>ENOENT: no such file or directory, open 'E:\source-code\packages\core\src\view\ng_module.ts'</code> when i run.</p>

<p>My folder structure doesnt have a folder named <strong>package</strong>.After a lot of digging i found that <code>packages\core\src\view\ng_module.ts'</code> is used by a npm package(angular :P)<a href=""https://i.stack.imgur.com/RRJlq.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/RRJlq.png"" alt=""screenshot of the path used in angular""></a></p>

<p>i dont know how this error is being thrown which doesnt happen when i run through karma</p>

<p>This is my config for jest
<code>
    ""jest"": {
        ""preset"": ""jest-preset-angular"",
        ""setupTestFrameworkScriptFile"": ""&lt;rootDir&gt;/src/setupJest.ts"",
        ""globals"": {
            ""ts-jest"": {
                ""tsConfigFile"": ""src/tsconfig.spec.json"",
                ""useBabelrc"": true
            },
            ""__TRANSFORM_HTML__"": true
        },
        ""transform"": {
            ""^.+\\.(ts|html)$"": ""&lt;rootDir&gt;/node_modules/jest-preset-angular/preprocessor.js"",
            ""^.+\\.js$"": ""babel-jest""
        },
        ""transformIgnorePatterns"": [
            ""&lt;rootDir&gt;/node_modules/(?!(@ngrx|ngx-dialog|ng-infinity))""
        ]
    }</code></p>
",https://stackoverflow.com/questions/48135466/enonet-error-while-running-jest-preset-angular,"['angular', 'jest-preset-angular']",1385,TRUE,3,1
Mock variable in unit test android,"<p>Searched on google about, how to mock a variable in unit testing and seen some suggestions, for my case its not working. my scenario is,</p>

<pre><code>class Keys {

private static Keys sKeys;
private String enKey = null;

static synchronized sKeys getInstance() {
    if(sKeys == null) {
        sKeys = new Keys();
    }
    return sKeys;
}

Boolean isLocked() {
    if(enKey == null ) {
        return true;
    }
    return false;
  }
}
</code></pre>

<p>This is the class, i have written. Unit test of the class is below,</p>

<pre><code>@RunWith(MockitoJUnitRunner.class)     
public class KeysTest {

@Test
public void isLocked_Test() {
    Keys key = Keys.getInstance();
    Key.isLocked();
   // Here in isLocked function I want to mock the enKey value to other than null
   }
}
</code></pre>

<p>Here, i want to call isLocked function, and i want to set or mock the <strong>enKey</strong> variable value to other than null.</p>

<p>How i can do that?
Could anyone help me on that?</p>
",https://stackoverflow.com/questions/49926163/mock-variable-in-unit-test-android,"['android', 'unit-testing', 'mockito', 'android-testing']",1662,TRUE,0,1
How to setup a Jenkins pipeline for postman tests,"<p>Postman is used as a popular testing tool for API testing, you can write bunch of unit tests using Postman and execute them as a part of your build process to perform unit testing. The following covers the Jenkins integration of Postman tests.</p>

<p>In order to do that you should have</p>

<ol>
<li>Exported Postman tests as a collection</li>
<li>Make the APIs available at run time when the tests are performed. (Using docker or by creating a separate build pipeline.)</li>
</ol>
",https://stackoverflow.com/questions/49441224/how-to-setup-a-jenkins-pipeline-for-postman-tests,"['jenkins', 'postman']",9035,TRUE,3,2
Setting boto3 dynamodb endpoint_url globaly,"<p>I want to use <a href=""https://docs.aws.amazon.com/de_de/amazondynamodb/latest/developerguide/DynamoDBLocal.html"" rel=""nofollow noreferrer"">dynamodb local</a> for local (unit) testing of my python/boto3 based application.</p>

<p>Now I can do something like this</p>

<pre><code>if test_mode:
    client = boto3.client(""dynamodb"", endpoint_url=""localhost:8000"")
    resource = boto3.resource(""dynamodb"", endpoint_url=""localhost:8000"")
else:
    client = boto3.client(""dynamodb"")
    resource = boto3.resource(""dynamodb"")
</code></pre>

<p>But I would like to avoid the <code>test_mode</code> check.</p>

<p>Can I somehow ""prepare"" boto3 so the dynamodb endpoint URL is set globally?</p>

<p><strong>Update</strong></p>

<p>To further explain what I want. I want some sort of function, where I can say:</p>

<pre><code>boto3.setGlobalDynamodbEndpoint(""http://localhost:8000"")
</code></pre>

<p>such that when, after calling this function, I do:</p>

<pre><code>client = boto3.client(""dynamodb"")
resource = boto3.resource(""dynamodb"")
</code></pre>

<p>The endpoint will automatically be set to <code>""http://localhost:8000""</code></p>
",https://stackoverflow.com/questions/49955926/setting-boto3-dynamodb-endpoint-url-globaly,"['amazon-dynamodb', 'boto3']",2044,TRUE,3,2
unit test a node.js controller that call external api,"<p>How do I test below module/function where it calls external api? If I'm firing the api that's not unit test anymore, that's call intergration or flow testing. I know there's such thing call mock api, but what it should test? I expect only 2 outcome, it fail or it succeed. Since the external api already handle edge case (says name param is not supply), do I have to do unit testing on my side?</p>

<pre><code>const request = require('request')
import PATH from './config/somewhere'

export const createUser = async (req, res, next) =&gt; {
  try {
    response = await request.post(`${PATH}/api/user/create`, {form: {name: req.body.name}})
    res.json(response)
  } catch(err) {
    this.throw(err.message)
  }
}
</code></pre>
",https://stackoverflow.com/questions/50229308/unit-test-a-node-js-controller-that-call-external-api,"['javascript', 'node.js', 'unit-testing', 'express']",727,FALSE,0,1
Access HttpContext in constructor for fake DI,"<p>I am working on an asp.net mvc application that does not have DI or unit testing yet. So I started to restructure the application to have unit tests by spliting the application into 3 layers: Controllers - Services - DataAccess.</p>

<p>Some of the controllers were using the Session and the Cookies to store and retrieve values. So I create an interface and a class that deals with saving and retrieving values from Session and Cookies.</p>

<p>I did this only by using unit testing and never run the application.</p>

<p>Since the application did not had DI I created on the contructor of the controller the ContextService by giving as an input parameter the HttpContext of the Controller.</p>

<p>However when I run the application the values were not retrieved or saved in the Session or Cookies. It seems that the HttpContext is null on contructor.</p>

<p>Question 1:
How should I deal with my ContextService. Should it use the static property HttpContext.Current in order to access the session and cookies (how will it be unit tested) or ...?</p>

<p>Question 2:
If you know another solution how should it be adapt in order to have also DI in the future.</p>
",https://stackoverflow.com/questions/50655432/access-httpcontext-in-constructor-for-fake-di,"['c#', 'asp.net-mvc', 'dependency-injection', 'httpcontext']",303,TRUE,1,1
"H2 Database: expected &quot;ALL, ANY, SOME, SELECT, FROM, WITH&quot;","<p>I am using H2 as an in memory database for unit testing our application. This query is giving the error <code>expected ""ALL, ANY, SOME, SELECT, FROM, WITH""</code> for this sql query</p>

<pre><code>SELECT CF.*, ROWNUM CASHFLOW_INDEX
FROM ( SELECT * FROM
TB_CASHFLOWS CFW WHERE CFW.CASHFLOW_DATE &gt;= :runDate AND
CFW.CASHFLOW_TYPE &lt;&gt; 'ISSUE' AND CFW.ISIN = :securityCode ORDER BY
CFW.CASHFLOW_DATE,CFW.CASHFLOW_TYPE ASC ) CF
</code></pre>

<p>at the runDate location as below:</p>

<pre><code>SELECT CF.*, ROWNUM CASHFLOW_INDEX
FROM ( SELECT * FROM
TB_CASHFLOWS CFW WHERE CFW.CASHFLOW_DATE &gt;= :[*]RUNDATE AND
CFW.CASHFLOW_TYPE &lt;&gt; 'ISSUE' AND CFW.ISIN = :SECURITYCODE ORDER BY
CFW.CASHFLOW_DATE,CFW.CASHFLOW_TYPE ASC ) CF
</code></pre>

<p>But the same query is working fine in the h2 console when the parameters are given as '<code>2017-02-28</code>' and '<code>USD_TREASURY_28FEB</code>'. This query will be executed by spring jdbc template. Is this a problem with the way the parameters are passed for H2?</p>

<p>The java code is as below:</p>

<pre><code>Object[] cashflowQueryArgs = new Object[] {""2017-02-28"",""USD_TREASURY_28FEB"" };

List&lt;Cashflow&gt; instrumentCashflows = getJdbcTemplate().query(
    cashflowsQuery, 
    cashflowQueryArgs,
    new BeanPropertyRowMapper&lt;Cashflow&gt;(Cashflow.class));
</code></pre>
",https://stackoverflow.com/questions/50329189/h2-database-expected-all-any-some-select-from-with,"['sql', 'h2', 'spring-jdbc', 'jdbctemplate']",2172,TRUE,3,1
How to test two Java concrete children classes that have same behaviors but different implementation details?,"<p>I am thinking about code reuse here:</p>

<p>Assuming we have such classes:</p>

<pre><code> public abstract class AbstractMap {
    public abstract void put(K k, V v);
    public abstract V get(K k);
 }

 public class ConcreteMapA extends AbstractMap {
    @Override
    public void put(K k, V v) {
       // put implementation detail A
       ...
    }
    @Override
    public V get(K k) {
       // get implementation detail A
       ...
    }
 }

 public class ConcreteMapB extends AbstractMap {
    @Override
    public void put(K k, V v) {
       // put implementation detail B
       ...
    }
    @Override
    public V get(K k) {
       // get implementation detail B
       ...
    }
 }
</code></pre>

<p>The two maps are implementing the same functionalities but with different implementation details. I would like to write unit test for these two concrete classes. But then the test cases start to be duplicate. </p>

<pre><code> public class ConcreteMapATest {
    @Test
    public void testPutCase1 {          
       ...
    }
    @Test
    public void testPutCase2 {          
       ...
    }
    @Test
    public void testGetCase1 {         
       ...
    }
    ...
 }

 // following starts to be duplicate code
 public class ConcreteMapBTest {
    @Test
    public void testPutCase1 {          
       ...
    }
    @Test
    public void testPutCase2 {          
       ...
    }
    @Test
    public void testGetCase1 {         
       ...
    }
    ...
 }
</code></pre>

<p>So what could be the right way to test such? How to reuse these testMethods? Or maybe I just should not do the reuse for unit testing?</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/49075643/how-to-test-two-java-concrete-children-classes-that-have-same-behaviors-but-diff,"['java', 'unit-testing', 'junit', 'mockito', 'abstract-class']",49,FALSE,0,0
Get token for an existing user with LexikJWTauthenticationBundle Symfony 3.3,"<p>I'm a noob in unit testing and I want to test my API.
So, LexikJWTAuthenticationBundle works fine when I try to access in /login_check path and the CRUL command line.
But when I try to do the TestCase I get this error :</p>

<p>1) Tests\AppBundle\Controller\StoreControllerTest::testPOSTRate
<em>GuzzleHttp\Exception\ClientException: Client error: GET <a href=""http://localhost:8000/api/stores"" rel=""nofollow noreferrer"">http://localhost:8000/api/stores</a> resulted in a 401 Unauthorized response:
{""code"":401,""message"":""Invalid JWT Token""}</em></p>

<p><strong>My testPOST function :</strong></p>

<pre><code>public function testPOSTRate(){
    $data = array(
      'rate' =&gt; 1,
      'store' =&gt; 1
    );
    // I'm not sure if it's the right way to get Token
    $token = $this-&gt;getService('lexik_jwt_authentication.encoder')-&gt;encode([
      'username' =&gt; 'Nacer',
      ]);

    $this-&gt;client-&gt;get('http://localhost:8000/api/stores', [
      'body' =&gt; json_encode($data),
      'headers' =&gt; [
        'Authorization' =&gt; 'Bearer '.$token
      ]
    ]);
  }
</code></pre>
",https://stackoverflow.com/questions/48831056/get-token-for-an-existing-user-with-lexikjwtauthenticationbundle-symfony-3-3,"['jwt', 'token', 'symfony-3.3', 'lexikjwtauthbundle']",728,TRUE,0,1
How to implement testing on ios project that relies on firebase API&#39;s,"<p>I have a project that uses FirebaseAuth, Firebase Database and Firebase Storage. The project is well advanced and needs to implement automated testing.
I have recently studied unit testing using ios XCTests. I understood basically how the native use of unit testing works and through the use of Mocks (Cuckoo specifically).</p>

<p>I arranged my code by removing dependency injections and something like that to prepare to implement the tests.
My question is that I needed to do tests like:</p>

<p>""When I perform a certain action on a ViewController, I wanted to check if it is saving a certain object in a Firebase Database collection (or mock), on the correct path."" </p>

<p>Or better,</p>

<p>When registering a new user in the database (<em>[""name"": ""Mike"", ""email"":""mike@email.com"", ""gender"":""male""]</em>), I would like to verify that it was actually saved in the path ""<em>/users/{mikeId}/{mike}</em>"".</p>

<p>I do not know if I was very clear, but I have doubts about how to test this kind of thing. Would I have to test the functions of my DataManager that do operations in the database? Create mocks that get this value and create a sort of fake database locally?</p>
",https://stackoverflow.com/questions/51699634/how-to-implement-testing-on-ios-project-that-relies-on-firebase-apis,"['swift', 'unit-testing', 'firebase', 'xctest']",252,FALSE,1,0
Jest + Enzyme unit test a dictionary,"<p>Pretty new to unit testing and I'm having trouble with writing a test to cover a dictionary object that I have. The tests I'm writing pass, but when I run a coverage report it says it is still uncovered.</p>

<p>This is what the dictionary looks like: <code>modals[key]</code> and this is what the modals object looks like </p>

<p><code>const modals = {
  cartSuccessModal: 'SuccessModal',
  cartErrorModal: 'ErrorModal',
};</code></p>

<p>These are examples of the tests that I've tried that pass, but do not properly cover the <code>modals[key]</code> line:</p>

<p><code>expect(modals['cartSuccessModal']).toEqual('SuccessModal');
 expect(modals['cartErrorModal']).toEqual('ErrorModal');</code></p>
",https://stackoverflow.com/questions/51864055/jest-enzyme-unit-test-a-dictionary,"['reactjs', 'jestjs', 'enzyme']",336,FALSE,0,0
Yii2 Codeception acceptance Class name must be a valid object or a string,"<p>I'm trying to set up codeception testing on Yii2. My stack is: vagrant + Selenium + chromedriver +PHP 7.1. Here is my conception config:</p>

<pre><code>    actor: AcceptanceTester
modules:
    enabled:
    - WebDriver:
        url: 'http://localhost:8080/'
        window_size: 1920x1080
        browser: chrome
        capabilities:
            chromeOptions:
                args: [""--no-sandbox"", ""--headless"", ""--disable-gpu""]
                binary: ""/usr/bin/google-chrome-stable""
    - Yii2:
        part: [orm,email]
        entryScript: index-test.php
</code></pre>

<p>config/test.php is equal to config/console.php</p>

<p>Here is some output from console:</p>

<pre><code>     ./yii serve
Server started on http://localhost:8080/
Document root is ""/var/www/test/web""
Quit the server with CTRL-C or COMMAND-C.
[Fri Jun  1 12:46:39 2018] ::1:45348 [200]: /
[Fri Jun  1 12:46:52 2018] ::1:45362 [200]: /
</code></pre>

<p>Finally I took PageCest the same as HomeCest in basic template and run the tests. Unit testing is working, but acceptance tests return following:</p>

<pre><code>PageCest: Ensure that about page works
</code></pre>

<p>Test  tests/acceptance/PageCest.php:ensureThatAboutPageWorks</p>

<pre><code>[Error] Class name must be a valid object or a string
</code></pre>

<p>This error repeats for all methods is PageCest.
What I did wrong ?</p>
",https://stackoverflow.com/questions/50641188/yii2-codeception-acceptance-class-name-must-be-a-valid-object-or-a-string,"['selenium', 'yii2', 'codeception']",611,TRUE,0,1
Test chrome.extension.getURL() and other chrome functions of chrome with Jasmine,"<p>I have followed this tutorial to test vanilla javascript with jasmine:
<a href=""https://dev.to/aurelkurtula/unit-testing-with-vanilla-javascript-the-very-basics-7jm"" rel=""nofollow noreferrer"">https://dev.to/aurelkurtula/unit-testing-with-vanilla-javascript-the-very-basics-7jm</a></p>

<p>However I got the point in which a function I want to test assigns a 'src' to an 'img' element.</p>

<pre><code>setImage(){
     const img = document.createElement('img');
     img.src = chrome.extension.getURL('images/icon.png');

     return img;
}
</code></pre>

<p>And, for the test with Jasmine I did I did:</p>

<pre><code>it('should check image creation', () =&gt; {
     const img = document.createElement('img');
     img.src = '../images/icon.png';

     expect(setImage()).toEqual(img)
})
</code></pre>

<p>I got this error after running the test:</p>

<pre><code>TypeError: Cannot read property 'getURL' of undefined
</code></pre>

<p>referring to the chrome.extension.</p>

<p>Does anybody know how I can test this?</p>
",https://stackoverflow.com/questions/53548521/test-chrome-extension-geturl-and-other-chrome-functions-of-chrome-with-jasmine,"['javascript', 'google-chrome-extension', 'jasmine']",305,TRUE,0,1
How to stub a class which returns a class?,"<p>I have a method which i'm unit testing and i'm trying to test both </p>

<pre><code>    ...
    let db = new MockDb()
    ...
    db.query(query)
        .then(cursor =&gt; {
          return cursor.next()
            .then(result =&gt; {
              if (result !== undefined || !data.id) { &lt;-- WANT TO STUB CURSOR.NEXT() SO I CAN TEST RESULT BEING DIFFERENT VALUES
                data.id = uuidv4()
              }
    ...
</code></pre>

<p>I have this file that is used for mocking/stubbing which contains 2 classes, but only exposes one of them</p>

<pre><code>class MockDb {  
  query (aql) {
    return new Promise((resolve, reject) =&gt; {
      return resolve(new MockCursor())
    })
  }
}


class MockCursor {
  next () {
    return new Promise((resolve, reject) =&gt; {
      return resolve({foo: 'bar'})
    })
  }
}

module.exports = MockDb
</code></pre>

<p>How can I stub what <code>cursor.next()</code> returns in this case?</p>

<p>Does NOT work - gives error <code>TypeError: cursor.stub is not a function</code></p>

<pre><code>before(() =&gt; {
  let cursor = sinon.stub()
  cursor.stub('next').return(undefined)
  sinon.stub(db, 'query').resolves(cursor)
})
</code></pre>

<p>If i expose the <code>MockCursor</code> class I can simply do this:</p>

<pre><code>let db = new MockDb()
let cursor = new MockCursor()
sinon.stub(cursor, 'next').resolves(undefined)
sinon.stub(db, 'query').resolves(cursor)
</code></pre>

<p>But i was just trying to do it without having to expose the MockCursor class explicitly</p>
",https://stackoverflow.com/questions/51291203/how-to-stub-a-class-which-returns-a-class,"['javascript', 'node.js', 'unit-testing', 'sinon']",129,FALSE,0,1
How to mock variable in unit test android studio,"<p>Searched on google about, how to mock a variable in unit testing and seen some suggestions, for my case its not working. my scenario is,</p>

<pre><code>class Keys {

private static Keys sKeys;
private String enKey = null;

static synchronized sKeys getInstance() {
    if(sKeys == null) {
        sKeys = new Keys();
    }
    return sKeys;
}

Boolean isLocked() {
    if(enKey == null ) {
        return true;
    }
    return false;
  }
}
</code></pre>

<p>This is the class, i have written. Unit test of the class is below,</p>

<pre><code>@RunWith(MockitoJUnitRunner.class)     
public class KeysTest {

@Test
public void isLocked_Test() {
    Keys key = Keys.getInstance();
    Key.isLocked();
   // Here in isLocked function I want to mock the enKey value to other than null
   }
}
</code></pre>

<p>Here, i want to call isLocked function, and i want to set or mock the <strong>enKey</strong> variable value to other than null.</p>

<p>How i can do that?
Could anyone help me on that?</p>
",https://stackoverflow.com/questions/49919380/how-to-mock-variable-in-unit-test-android-studio,"['android', 'unit-testing', 'android-testing']",797,FALSE,0,1
Mockito testing Rest client,"<p>I am having a hard time doing unit testing with the Rest client. I am trying to mock the rest call and return a specific object to check its value. But I get <code>java.lang.IllegalArgumentException: URI is not absolute</code> as an error. </p>

<p>I know that there is a way to use <code>mockServer</code> but I think this is helpful only in testing the responses, but not the body.</p>

<p>I am running it with SpringBoot. Here is my code: </p>

<p>Service:</p>

<pre><code>@Service
public class ServiceImpl implements Service {

    private final String url;
    private RestTemplate restTemplate = new RestTemplate();

    public ServiceImpl(@Value(""${call.url}"") String url) {
        this.url = url;
    }

    @Override
    public MyObject getMyObject(String param1, String param2) {
        MyObject myObject;

        try {
            myObject = restTemplate.getForObject(url, MyObject.class, param1, param2);
        } catch (HttpClientErrorException e) {
            throw new MyObjectException();
        }
        return myObject;
    }
}
</code></pre>

<p>Test:</p>

<pre><code>@InjectMocks
@Spy
private Service service;
MyObject found = mock(MyObject.class);

@Mock
RestTemplate restTemplate;

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
}

@Test
public void() test{
   MyObject myObject = new MyObject();
   myObject.setField(value);

    //Given
    Mockito.when(restTemplate.getForObject(
        Mockito.anyString(),
        ArgumentMatchers.any(Class.class), 
        Mockito.anyString(), 
        Mockito.anyString()))
    .thenReturn(myObject);

    found = service.getMyObject(""param1"", ""param2"");
    //Then
    assertEquals(myObject.getField(), found.getField());
}
</code></pre>
",https://stackoverflow.com/questions/53469955/mockito-testing-rest-client,"['java', 'unit-testing', 'spring-boot', 'mockito', 'resttemplate']",2503,FALSE,0,1
unit tests in python with large __init__ code for class file,"<p>I'm trying to understand unit testing in python. If I have a class with a large <code>__init__</code> function, and I am writing unit-tests for member functions of this class, which need to refer <code>self</code> object, what's the best way to go about it?</p>

<p>As a follow up several of these functions could be <code>@staticmethods</code>, but we have decided to stay pythonic, and keep <code>self.func_calls</code> instead so is there an easier way to write test-code for such functions? </p>
",https://stackoverflow.com/questions/49196565/unit-tests-in-python-with-large-init-code-for-class-file,"['python', 'unit-testing']",387,TRUE,0,2
Middleman test and console environments for config.rb,"<p>I'm using Middleman v4 and I'm having issues in both the console and when I use RSpec to unit test my libraries.</p>

<p>Right now I comment out most of my <code>config.rb</code> file, something like this.</p>

<pre><code>require 'lib/foo'
require 'lib/bar'

#activate external_pipeline ...

#activate stuff
</code></pre>

<p>Activating features like the external pipeline causes problems in both console and when I'm unit testing. I could use environment variables and conditionals to fix the problem, but I was wondering if anyone has had to approach this issue.</p>
",https://stackoverflow.com/questions/48472207/middleman-test-and-console-environments-for-config-rb,"['middleman', 'middleman-4']",142,TRUE,0,1
Firebase function for dialogflow unittest not returning,"<p>I have the following firebase cloud function that does work as written.</p>

<pre><code>'use strict';

const {
    dialogflow,
    Image,
  } = require('actions-on-google')

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);

const db = admin.firestore();

const config = require('config');

// Initialize the Auth0 client
var AuthenticationClient = require('auth0').AuthenticationClient;
var auth0 = new AuthenticationClient({
    domain: functions.config().familybank.auth0.domain,
    clientID: functions.config().familybank.auth0.clientid
});

const app = dialogflow();

app.intent(config.get('dialogflow.intents.welcome_user'), async (conv) =&gt; {
    const userInfo = await auth0.getProfile(conv.user.access.token)
    .catch( function(err) {
        console.error('Error getting userProfile from Auth0: ' + err);
        conv.close(""Something went wrong. Please try again in a few minutes. "" + err)
    });

    // check for existing bank, if not present, create it
    var bankRef = db.collection(config.get('firestore.bank_collection_key')).doc(userInfo.email);
    const bankSnapshot = await bankRef.get()

    if (bankSnapshot.exists) {
        conv.ask(""Welcome back to Family Bank. I just opened the bank I found for "" + userInfo.name + "". How can I help you?"");
    } else {
        // create new account
        conv.ask(""Welcome to Family Bank. I just created a new bank for "" + userInfo.name + "". I can help you create and manage accounts. What would you like to do?"");
    }
})

exports.accessAccount = functions.https.onRequest(app);
</code></pre>

<p>I also wrote the following unittest that does successfully stub Auth0, Firestore, etc., but it fails to get a return value. Here's the test</p>

<pre><code>const chai = require('chai');
const assert = chai.assert;
const sinon = require('sinon');

const admin = require('firebase-admin');
const test = require('firebase-functions-test')();

const config = require('config');

var UsersManager = require('auth0/src/auth/UsersManager');

describe('Cloud Functions', () =&gt; {
  let myFunctions, adminInitStub, firestoreStub, collectionStub;

  before(() =&gt; {
    test.mockConfig({""familybank"": {""auth0"": {""domain"": ""mockdomain"", ""clientid"": ""mockid""}}});
    adminInitStub = sinon.stub(admin, 'initializeApp');

    oldFirestore = admin.firestore;
    firestoreStub = sinon.stub();
    Object.defineProperty(admin, 'firestore', { get: () =&gt; firestoreStub });
    collectionStub = sinon.stub();
    firestoreStub.returns({ collection: collectionStub });

    sinon.stub(UsersManager.prototype, 'getInfo').callsFake( function fakeGetProfile() {
      return Promise.resolve({""email"": ""someuser@domain.com"", ""name"": ""Joe Banks""});
    });
    myFunctions = require('../index');
  });

  after(() =&gt; {
    adminInitStub.restore();
    admin.firestore = oldFirestore;
    test.cleanup();
  });

  describe('accessAccount', () =&gt; {
    it('should return a 200', (done) =&gt; {
      const bankOwnerParam = 'someuser@domain.com';
      const bankStub = sinon.stub();

      collectionStub.withArgs(config.get('firestore.bank_collection_key')).returns({ doc: bankStub });
      bankStub.withArgs(bankOwnerParam).returns({ get: () =&gt; Promise.resolve({ mykey: 'mydata', exists: true })});

      const req = {""responseId"":""RESPONSEID"",""queryResult"":{""queryText"":""GOOGLE_ASSISTANT_WELCOME"",""action"":""input.welcome"",""parameters"":{},""allRequiredParamsPresent"":true,""fulfillmentMessages"":[{""text"":{""text"":[""""]}}],""outputContexts"":[{""name"":""projects/familybank/agent/sessions/SESSIONID/contexts/google_assistant_welcome""},{""name"":""projects/familybank/agent/sessions/SESSIONID/contexts/actions_capability_audio_output""},{""name"":""projects/familybank/agent/sessions/SESSIONID/contexts/google_assistant_input_type_voice""},{""name"":""projects/familybank/agent/sessions/SESSIONID/contexts/actions_capability_media_response_audio""}],""intent"":{""name"":""projects/familybank/agent/intents/65b6c584-be5d-456b-ad77-341abdb4dcb4"",""displayName"":""Default Welcome Intent""},""intentDetectionConfidence"":1.0,""languageCode"":""en-us""},""originalDetectIntentRequest"":{""source"":""google"",""version"":""2"",""payload"":{""isInSandbox"":true,""surface"":{""capabilities"":[{""name"":""actions.capability.AUDIO_OUTPUT""},{""name"":""actions.capability.MEDIA_RESPONSE_AUDIO""}]},""requestType"":""SIMULATOR"",""inputs"":[{""rawInputs"":[{""query"":""Talk to Family Bank"",""inputType"":""VOICE""}],""intent"":""actions.intent.MAIN""}],""user"":{""lastSeen"":""2018-11-15T14:41:36Z"",""accessToken"":""TOKEN"",""locale"":""en-US"",""userId"":""USERID""},""conversation"":{""conversationId"":""SESSIONID"",""type"":""NEW""},""availableSurfaces"":[{""capabilities"":[{""name"":""actions.capability.AUDIO_OUTPUT""},{""name"":""actions.capability.SCREEN_OUTPUT""},{""name"":""actions.capability.WEB_BROWSER""}]}]}},""session"":""projects/familybank/agent/sessions/SESSIONID""};
      const res = {
        response: (code) =&gt; {
          assert.equal(code, 200);
          done();
        }
      };

      myFunctions.accessAccount(req, res);
    });
  });
})
</code></pre>

<p>When I run the test, I get the following failure</p>

<pre><code>root@fc19e6bca144:/appfiles/functions# npm test

&gt; familybank@0.0.1 test /appfiles/functions
&gt; mocha --reporter spec



  Cloud Functions
    accessAccount
      1) should return a 200


  0 passing (3s)
  1 failing

  1) Cloud Functions
       accessAccount
         should return a 200:
     Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure ""done()"" is called; if returning a Promise, ensure it resolves. (/appfiles/functions/test/index.test.js)




npm ERR! Test failed.  See above for more details.
</code></pre>

<p>I can't figure out why this doesn't return a value. I followed <a href=""https://firebase.google.com/docs/functions/unit-testing#testing_http_functions"" rel=""nofollow noreferrer"">https://firebase.google.com/docs/functions/unit-testing#testing_http_functions</a>, and followed the links to some related files.</p>
",https://stackoverflow.com/questions/53499852/firebase-function-for-dialogflow-unittest-not-returning,"['javascript', 'firebase', 'google-cloud-functions', 'dialogflow-es', 'actions-on-google']",180,FALSE,0,1
Clojure Mock call to Java Object function,"<p>I have a function that makes a call to a service. I want to mock this API for unit testing to simulate two situations: </p>

<ol>
<li>API succeeds, and returns nothing</li>
<li>API fails, and throws an exception</li>
</ol>

<p>My sample code is given below:</p>

<pre><code>(defn- get-client [] (client/getService))

(def get-client-memo (memoize get-client))

(defn- api
  [id1 id2]
   (.client_api (get-client-memo) id1 id2)
     (log/info ""successfully deactivated""))
</code></pre>

<p>I figure, I can make use of with-redefs-fn to mock a function defined in clojure. But How do I mock the Java object and its API?</p>

<p>Thanks for your help,
Swagatika</p>
",https://stackoverflow.com/questions/50939101/clojure-mock-call-to-java-object-function,"['java', 'unit-testing', 'clojure']",472,FALSE,0,0
Unit test an Android activity,"<p>I'm making an application in the android studio. And for this project, I have to make multiple unit tests. But I have no idea what I can unit test this application. I'm really struggling with unit testing so I would appreciate if someone could help me, or come up with some unit tests I can implement in my project. Its an app with a listview that retrieves data from a web service.</p>

<p>Code: </p>

<pre><code> public class MainActivity extends AppCompatActivity {

ListView listView;
ArrayAdapter&lt;String&gt; adapter;
String[] data;
String[] waarde;
String[] hoog;
String[] laag;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    listView = findViewById(R.id.listview);

    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());

    getData();

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) {
        Intent intent = new Intent(MainActivity.this, Showdata.class);
        intent.putExtra(""teeltbed"", listView.getItemAtPosition(position).toString());
        startActivity(intent);
        }
    });

}

private void getData()
{
    String getData = null;
    String dbResult = ""empty"";
    dbConnect database = new dbConnect(this);

    try{
        String query = ""SELECT * FROM Lamp"";
        getData = ""?query="" + URLEncoder.encode(query, ""UTF-8"");
        //data += ""&amp;username="" + URLEncoder.encode(userName, ""UTF-8"");
        String link = ""http://10.247.240.53/kas/lampen.php"";
        dbResult = database.execute(link).get();
    }
    catch (Exception e){

    }

    try{
        JSONObject jsonObject = new JSONObject(dbResult);
        JSONArray array = jsonObject.getJSONArray(""Lamp"");
        waarde = new String[array.length()];
        data = new String[array.length()];
        hoog = new String[array.length()];
        laag = new String[array.length()];
        for (int i = 0; i &lt; array.length(); i++)
        {
            jsonObject = array.getJSONObject(i);
            data[i] = jsonObject.getString(""teeltbed"");
            waarde[i] = ""A: "" + jsonObject.getString(""waarde"") + "" %"";
            hoog[i] = ""H: "" + jsonObject.getString(""hoog"") + "" W/m2"";
            laag[i] = ""L: "" + jsonObject.getString(""laag"") + "" W/m2"";

        }

        listView.setAdapter(new dataListAdapter(data, waarde, hoog, laag));
    }

    catch (Exception e)
    {
        e.printStackTrace();
    }
}

class dataListAdapter extends BaseAdapter{
    String[] data, waarde;

    dataListAdapter(){
        data = null;
        waarde = null;
    }

    public dataListAdapter(String[] sdata, String[]swaarde, String[]shoog, String[]slaag)
    {
        data = sdata;
        waarde = swaarde;
        hoog = shoog;
        laag = slaag;

    }

    public int getCount()
    {
        return data.length;
    }

    public Object getItem(int arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    public View getView (int position, View convertView, ViewGroup parent)
    {
        LayoutInflater inflater = getLayoutInflater();
        View row;
        row = inflater.inflate(R.layout.layout_list, parent, false);
        TextView t1, t2, t3, t4;
        t1 = (TextView) row.findViewById(R.id.list_item);
        t2 = (TextView) row.findViewById(R.id.list_item2);
        t3 = (TextView) row.findViewById(R.id.list_item3);
        t4 = (TextView) row.findViewById(R.id.list_item4);
        t1.setText(data[position]);
        t2.setText(waarde[position]);
        t3.setText(hoog[position]);
        t4.setText(laag[position]);
        return (row);
    }
}

class Sproeier
{
 public int TeeltBed;
 public String Stand;
 public double Actueel;
 public double Hoog;
 public double Laag;

 public void Sproeier()
 {
     int teeltbed;
     double hoog;
     double laag;
 }
}

class Lamp {

}

public static class ScadaWebservice
{

}

class Kas
{

    public void kas()
    {

    }
}
</code></pre>

<p>}</p>
",https://stackoverflow.com/questions/51023012/unit-test-an-android-activity,"['java', 'android', 'unit-testing', 'testing']",3149,FALSE,0,1
Python - How to run unittest without starting the application?,"<p>I have a very basic python application that I wanted to use for upskilling in unit testing. The problem is when I run my test file, it starts the application. I need to shut down the application in order for the test to run and get results. I think this is something to do with the mainloop() used in the application code. How can I just run the tests without the application starting?</p>

<p><strong>Application code:</strong></p>

<pre><code>class User:

    def __init__(self, un, pw, ut, upc):
        self.username = un
        self.password = pw
        self.userT = ut
        self.userPreferredCar = upc
        self.userInfo = """"

    def get_un(self):
        return self.username

    def get_ut(self):
        return self.userT

    def get_pw(self):
        return self.password

    def get_userPreferredCar(self):
        return self.userPreferredCar

    def set_userInfo(self):
        self.userInfo = str(""Hello "" + self.username + "", you picked: "" + self.userPreferredCar)
        return self.userInfo

def Login():
    #Create login window
    login_screen = Tk()
    #Create window title
    login_screen.title('Login')
    #Set the window size
    login_screen.geometry('250x150')

    #tkinter form code

    login_screen.mainloop()

def signup_function():
    #Get the current user
    curr_user = User(username_signupE.get(), password_signupE.get(), userT.get(), carT.get())

    #If the inputs are empty then throw error screen
    if curr_user.get_un() == """" or curr_user.get_pw() == """" or curr_user.get_ut() == """" or curr_user.get_userPreferredCar() == """":
        accCreateErr = Tk()
        accCreateErr.title('Error')
        accCreateErr.geometry('150x50')
        errL = Label(accCreateErr, text='\nPlease fill out all details!')
        errL.grid()
        accCreateErr.mainloop()
    else:
        # Write the new user details to the user file
        with open(user_file, 'w') as f:
            f.write(curr_user.get_un())
            f.write('\n')
            f.write(curr_user.get_pw())
            f.write('\n')
            f.write(curr_user.get_ut())
            f.write('\n')
            f.write(curr_user.get_userPreferredCar())
            f.close()
#Destory the signup window
signup_screen.destroy()
#Run the Login function
Login()
</code></pre>

<p><strong>Test code:</strong></p>

<pre><code>import unittest
from main import User
from main import Car

class TestUser(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        print('Set up User class')

    @classmethod
    def tearDownClass(cls):
        print('Tear down User class\n')

    def setUp(self):
        print('Set up dummy users')
        self.user_1 = User('Ryan', 'pass', 'Seller', 'Hatchback')
        self.user_2 = User('Adam', 'pass', 'User', 'Van')

    def tearDown(self):
        print('tearDown')

    def test_userInfo(self):
        print('Test the user info')
        self.user_1.set_userInfo()
        self.user_2.set_userInfo()

        self.assertEqual(self.user_1.set_userInfo(), 'Hello Ryan, you picked: Hatchback')
        self.assertEqual(self.user_2.set_userInfo(), 'Hello Adam, you picked: Van')

if __name__ == '__main__':
    unittest.main()
</code></pre>
",https://stackoverflow.com/questions/48532454/python-how-to-run-unittest-without-starting-the-application,"['python', 'unit-testing']",1562,TRUE,2,1
using cmock to mock a function that is a windows CALLBACK,"<p>I am having a problem with a case where i have created a C function that is passed to another library as a callback, so it uses CALLBACK notation. this is using VS2015. </p>

<p>VOID CALLBACK TheCallback(void)</p>

<p>i am unit testing some code using unity and cmock and I am trying to mock the callback..  </p>

<p>so, when cmock scripts create all of the mocks  (the mock header file) it creates lines like this:</p>

<p>void TheCallback_CMockIgnoreAndReturn(UNITY_LINE_TYPE cmock_line, VOID CALLBACK cmock_to_return);</p>

<p>(note the word CALLBACK in there)</p>

<p>and when i compile i get warnings and errors like this:</p>

<p>warning C4229: anachronism used: modifiers on data are ignored</p>

<p>error C2182: 'cmock_to_return': illegal use of type 'void'</p>

<p>It seems to have to do with that CALLBACK stuck right in the middle. </p>

<p>any ideas at all on how i can declare this as a CALLBACK and not have VS2015 complain about the type in the function prototype of the ignore and return mock?</p>

<p>i am wondering if i need to somehow undefine CALLBACK when unit testing, not sure if i can even</p>

<p>Any ideas would be great..
Thank You.</p>
",https://stackoverflow.com/questions/48287885/using-cmock-to-mock-a-function-that-is-a-windows-callback,"['unit-testing', 'visual-studio-2015', 'callback', 'cmock']",686,TRUE,0,1
Jasmine test with selecting items from list,"<p>I have an angular application and I need to do some unit testing on some methods with Jasmine. IN this case I do a unit test on a select list. So that the select list will not be empty.</p>

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

<pre><code> createStatusOptions(listValueoptions: OptionModel[], resources: any): OptionModel[] {
        const processStatusOptions = listValueoptions.map(listValueOption =&gt; {
            listValueOption.value = `${caseStatusEnum.inProgress}_${listValueOption.value}`;
            listValueOption.selected = true;
            return listValueOption;
        });

        const caseStatusEnumKeys = Object.keys(caseStatusEnum).filter(key =&gt; !isNaN(Number(key)));
        const enumOptions = this.optionService.createOptions(
            new ConfigOptionModel({ source: caseStatusEnumKeys, resources, resourcesModel: enumResourcesModel, isCustomEnum: true, }));

        return [
            this.getEnumOption(enumOptions, caseStatusEnum.submitted, true),
            ...processStatusOptions,
            this.getEnumOption(enumOptions, caseStatusEnum.closed),
        ];
    }

 private getEnumOption(options: OptionModel[], enumType, isSelected = false): OptionModel {
        const option = options.filter(enumOption =&gt; enumOption.value === `${enumType}`)[0];
        option.selected = isSelected;
        return option;
    }
</code></pre>

<p>And I have the unit test like this:</p>

<pre><code>it('should create status options when there ar list value options are provided', () =&gt; {
        optionService.options = [
            {
                value: caseStatusEnum.submitted.toString(),
            },
            {
                value: caseStatusEnum.inProgress.toString(),
            },
            {
                value: caseStatusEnum.closed.toString(),
            },
        ] as OptionModel[];



        // tslint:disable-next-line:max-line-length
        const result = service.createStatusOptions(optionService.options, [[103], [104], [105] ]);
        console.log(result);
       expect(result.length).toBe(2);
        expect(result).toEqual([{ value: '103', selected: true }, { value: '105', selected: false }]);

    });
</code></pre>

<p>But I get an error like this:</p>

<pre><code>Services: CaseService &gt; should create status options when there ar list value options are provided
TypeError: Cannot set property 'selected' of undefined
    at &lt;Jasmine&gt;
    at CaseService.getEnumOption (http://localhost:9878/src/app/case/src/services/case.service.ts?:130:9)
    at CaseService.getEnumOption [as createStatusOptions] (http://localhost:9878/src/app/case/src/services/case.service.ts?:109:22)
    at UserContext.&lt;anonymous&gt; (http://localhost:9878/src/app/case/src/services/case.service.spec.ts?:149:32)
    at ZoneDelegate.../../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (http://localhost:9878/E:/Projects/Source/Repos/VLR/Web/vlrworkspace/node_modules/zone.js/dist/zone.js?:388:1)
    at ProxyZoneSpec.push.../../node_modules/zone.js/dist/proxy.js.ProxyZoneSpec.onInvoke (http://localhost:9878/E:/Projects/Source/Repos/VLR/Web/vlrworkspace/node_modules/zone.js/dist/proxy.js?:128:1)
    at ZoneDelegate.../../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (http://localhost:9878/E:/Projects/Source/Repos/VLR/Web/vlrworkspace/node_modules/zone.js/dist/zone.js?:387:1)
    at Zone.../../node_modules/zone.js/dist/zone.js.Zone.run (http://localhost:9878/E:/Projects/Source/Repos/VLR/Web/vlrworkspace/node_modules/zone.js/dist/zone.js?:138:1)
    at runInTestZone (http://localhost:9878/E:/Projects/Source/Repos/VLR/Web/vlrworkspace/node_modules/zone.js/dist/jasmine-patch.js?:145:1)
    at UserContext.&lt;anonymous&gt; (http://localhost:9878/E:/Projects/Source/Repos/VLR/Web/vlrworkspace/node_modules/zone.js/dist/jasmine-patch.js?:160:1)
    at &lt;Jasmine&gt;
</code></pre>

<p>So my question is: How to solve this?</p>

<p>Thank you</p>

<p>if I do this:</p>

<pre><code>   console.log(optionService.options);
</code></pre>

<p>I get this output:</p>

<pre><code>Array(3)
0: {value: ""103"", selected: true}
1: {value: ""104""}
2: {value: ""105"", selected: false}
length: 3
__proto__: Array(0)
</code></pre>

<p>this is the file:</p>

<pre><code>import { fakeAsync, tick } from '@angular/core/testing';
import { FormServiceMock, MultiFileUploadServiceMock } from 'afw/forms/testing';
import { AfwHttp } from 'afw/generic-services';
import { AfwHttpMock, OptionServiceMock } from 'afw/generic-services/testing';
import { OptionModel, SearchResultModel } from 'afw/models';
import { FeedbackStoreServiceMock } from 'afw/store-services/testing';
import { RouterMock } from 'afw/testing';
import { PagingDataModel, TableSortDataModel } from 'afw/ui-components';
import { caseOwnerEnum, caseStatusEnum, caseTypeEnum, MultiFileUploadResourcesModel } from 'lr/models';
import { Observable, observable } from 'rxjs';
import { CaseTypeInfoModel } from 'support-shared/base/models';
import { CaseTypeInfoStoreServiceMock } from 'support-shared/base/services/case-type-info-store.service.mock';
import { CaseFormComponent } from '../case-base/src/case-form/case-form.component';
import { CaseBaseModel, CaseReferenceModel } from '../models';
import { CaseService } from './case.service';

let service: CaseService;
let afwHttpMock: AfwHttpMock;
// tslint:disable-next-line:prefer-const
let formServiceMock: FormServiceMock;
let multiFileUploadService: MultiFileUploadServiceMock;
let router: RouterMock;
let feedbackStoreService: FeedbackStoreServiceMock;
let optionService: OptionServiceMock;
let caseTypeInfoStoreService: CaseTypeInfoStoreServiceMock;
// tslint:disable-next-line:prefer-const
let component: CaseFormComponent;


fdescribe('Services: CaseService', () =&gt; {

    beforeEach(() =&gt; {
        afwHttpMock = new AfwHttpMock();
        multiFileUploadService = new MultiFileUploadServiceMock();
        router = new RouterMock();
        feedbackStoreService = new FeedbackStoreServiceMock();
        optionService = new OptionServiceMock();
        caseTypeInfoStoreService = new CaseTypeInfoStoreServiceMock();
        service = new CaseService(afwHttpMock as any, multiFileUploadService as any, router as any,
            feedbackStoreService as any, optionService as any, caseTypeInfoStoreService as any);
    });

    it('should create an instance', () =&gt; {
        expect(service).toBeTruthy();
    });

    it('should get case reference details', () =&gt; {
        afwHttpMock.setupOnlyResponse({ type: caseTypeEnum.revisionRequest, details: { bsn: 'bsnLabel' } }, 200);
        const d = service.getCaseReferenceDetails('spinnerMessage', { reference: '112314121', type: caseTypeEnum.revisionRequest });
        d.subscribe(r =&gt; {
            expect(r.details.length === 1);
            expect(r.details[0].key).toBe('bsn');
            expect(r.details[0].value).toBe('bsnLabel');
            expect((r.details[0] as any).resourceKey).toBe('bsn');
        });
        afwHttpMock.returnSuccessResponse();
    });


    // tslint:disable-next-line:no-identical-functions
    it('should get case reference details with full response', () =&gt; {
        afwHttpMock.setupOnlyResponse({ body: { type: caseTypeEnum.revisionRequest, details: [{ key: 'hoi' }] } }, 200);
        const d = service.getCaseReferenceDetailsFullResponse('spinnerMessage', { reference: '100001075', type: caseTypeEnum.revisionRequest });
        // tslint:disable-next-line:no-commented-code
        // tslint:disable-next-line:no-identical-functions
        /*  let result;
         d.subscribe(r =&gt; {
             result = r;
         }); */

        d.subscribe(r =&gt; {
            expect(r.ok === true);
            expect(r.body.details[0].key).toBe('hoi');
        });

        afwHttpMock.returnSuccessResponse();
        // expect(result.ok === true);
        // expect(result.)

    });


    // tslint:disable-next-line:no-commented-code
    it('shoud get case type info configuration that is used on various views when snapshot exists', () =&gt; {
        let result99: Observable&lt;CaseTypeInfoModel[]&gt;;
        result99 = service.getCaseTypeInfo('spinner') as Observable&lt;CaseTypeInfoModel[]&gt;;
        const response = [{ mock: 'mock' } as any];
        service['caseTypeInfoSnapshot'] = response;
        service.getCaseTypeInfo('spinner').subscribe(i =&gt; {
            expect(i).toEqual(response);
        });
    });

    // tslint:disable-next-line:no-identical-functions
    it('shoud get case type info configuration that is used on various views when snapshot doesnt exists', () =&gt; {
        let result99: Observable&lt;CaseTypeInfoModel[]&gt;;
        const spy = spyOn(caseTypeInfoStoreService, 'addCaseTypeInfoToStore');
        result99 = service.getCaseTypeInfo('spinner') as Observable&lt;CaseTypeInfoModel[]&gt;;
        const response = [{ mock: 'mock' } as any];
        service['caseTypeInfoSnapshot'] = response;
        // caseTypeInfoStoreService..subscribe((result) =&gt; { expect(result).toBe(false); });
        result99.subscribe((result) =&gt; {
            expect(response).toEqual(response);
        });


        afwHttpMock.setupOnlyResponse(result99, 200);
        afwHttpMock.returnSuccessResponse();
    });

    it('should create status options when no list value options are provided', () =&gt; {
        optionService.options = [
            {
                value: caseStatusEnum.submitted.toString(),
            },
            {
                value: caseStatusEnum.inProgress.toString(),
            },
            {
                value: caseStatusEnum.closed.toString(),
            },
        ] as OptionModel[];


        // tslint:disable-next-line:no-commented-code
        //  const spy = spyOn(service, 'createStatusOptions');
        const result = service.createStatusOptions([], {});
        expect(result.length).toBe(2);
        expect(result).toEqual([{ value: '103', selected: true }, { value: '105', selected: false }]);
        // tslint:disable-next-line:no-commented-code
        //  const response = [{ mock: 'mock' } as any];
        // expect(spy).toBe(result);
    });

    it('should create status options when there ar list value options are provided', () =&gt; {
        optionService.options = [
            {
                value: caseStatusEnum.submitted.toString(),
            },
            {
                value: caseStatusEnum.inProgress.toString(),
            },
            {
                value: caseStatusEnum.closed.toString(),
            },
        ] as OptionModel[];



        // tslint:disable-next-line:max-line-length
        const result = service.createStatusOptions(optionService.options, 103);
        console.log(optionService.options);
        expect(result.length).toBe(2);
        expect(result).toEqual([{ value: '103', selected: true }, { value: '105', selected: false }]);

    });






    it('should get case reference without details', () =&gt; {
        afwHttpMock.setupOnlyResponse({}, 200);
        const spy = spyOn(afwHttpMock, 'post').and.callThrough();
        const model = new CaseReferenceModel({ reference: '112314121', type: caseTypeEnum.revisionRequest });
        const d = service.getCaseReferenceDetails('spinnerMessage', model);
        d.subscribe(r =&gt; {
            expect(r).toBeDefined();
        });
        expect(spy).toHaveBeenCalledWith('api/support/cases/get-reference-details', model, 'spinnerMessage');
        afwHttpMock.returnSuccessResponse();
    });

    it('should add case reference without details', () =&gt; {
        afwHttpMock.setupOnlyResponse({}, 200);
        const spy = spyOn(afwHttpMock, 'post').and.callThrough();
        const model = new CaseReferenceModel({ reference: '112314121', type: caseTypeEnum.revisionRequest });
        const d = service.addCase('spinnerMessage', model as any);
        d.subscribe(r =&gt; {
            expect(r).toBeDefined();
        });
        expect(spy).toHaveBeenCalledWith('api/support/cases', model, 'spinnerMessage');
        afwHttpMock.returnSuccessResponse();
    });

    it('should search for cases', () =&gt; {
        const formModel: any = { makeQueryString: () =&gt; 'name=test' };
        const pagingModel = new PagingDataModel({ currentPage: 10, itemsPerPage: 20 });
        const sortModel = new TableSortDataModel({ columnName: 'kol', isDescending: false });

        const spy = spyOn(afwHttpMock, 'get').and.callThrough();
        const mockData = [
            new CaseBaseModel({
                id: 100000001,
                type: caseTypeEnum.revisionRequest,
                status: caseStatusEnum.inProgress,
                substatus: 5266,
                verdict: null,
                owner: caseOwnerEnum.caseManager,
                dateSubmitted: '02-02-2009',
                dateClosed: '',
                reference: 'aaa',
            }),
        ];

        const setupResponse = new SearchResultModel&lt;CaseBaseModel&gt;();
        setupResponse.result = mockData;
        setupResponse.totalResultCount = 27;

        afwHttpMock.setupOnlyResponse(setupResponse, 200);
        let response: SearchResultModel&lt;CaseBaseModel&gt;;
        service.search(formModel, sortModel, pagingModel, 'spinnerText').subscribe(result =&gt; {
            response = result;
        });
        afwHttpMock.returnOnlyResponse();

        expect(spy).toHaveBeenCalledWith('api/support/cases?name=test&amp;columnName=kol&amp;isDescending=false&amp;currentPage=10&amp;itemsPerPage=20',
            'spinnerText');
        expect(response).toEqual(setupResponse);
        expect(response.result[0].getResourceForStatus).toBeDefined();
    });

    it('should save documents', fakeAsync(() =&gt; {
        const spy = spyOn(multiFileUploadService, 'syncFilesWithBackend').and.callThrough();
        const spyRouter = spyOn(router, 'navigate').and.callThrough();
        const spyFeedback = spyOn(feedbackStoreService, 'addSuccessMessageOnMainPortal');
        service.saveDocuments(1, [{} as any], MultiFileUploadResourcesModel.keys, '../', { key: 'da', value: 'fa' });
        expect(spy).toHaveBeenCalledWith('api/support/cases/1/documents', [{}],
            MultiFileUploadResourcesModel.keys.bijlageToevoegenSpinnerTekst,
            MultiFileUploadResourcesModel.keys.bijlageVerwijderenSpinnerTekst
        );
        tick();
        expect(spyRouter).toHaveBeenCalledWith(['../']);
        expect(spyFeedback).toHaveBeenCalled();
    }));

    it('should not save documents if there are no documents in array', fakeAsync(() =&gt; {
        const spy = spyOn(multiFileUploadService, 'syncFilesWithBackend').and.callThrough();
        const spyRouter = spyOn(router, 'navigate').and.callThrough();
        const spyFeedback = spyOn(feedbackStoreService, 'addSuccessMessageOnMainPortal');
        service.saveDocuments(1, [], MultiFileUploadResourcesModel.keys, '../', { key: 'da', value: 'fa' });
        expect(spy).not.toHaveBeenCalled();
        tick();
        expect(spyRouter).toHaveBeenCalledWith(['../']);
        expect(spyFeedback).toHaveBeenCalled();
    }));

    it('should save documents and report errors', fakeAsync(() =&gt; {
        multiFileUploadService.setResponse([{}, { error: {} }]);
        spyOn(multiFileUploadService, 'makeWarningMessageForUnsyncedFiles').and.returnValue('mock');
        const spyRouter = spyOn(router, 'navigate').and.callThrough();
        const spyFeedback = spyOn(feedbackStoreService, 'addWarningMessageOnMainPortal');
        const spy = spyOn(multiFileUploadService, 'syncFilesWithBackend').and.callThrough();
        service.saveDocuments(1, [{} as any], MultiFileUploadResourcesModel.keys, '../', { key: 'da', value: 'fa' });
        expect(spy).toHaveBeenCalledWith('api/support/cases/1/documents', [{}],
            MultiFileUploadResourcesModel.keys.bijlageToevoegenSpinnerTekst,
            MultiFileUploadResourcesModel.keys.bijlageVerwijderenSpinnerTekst
        );
        tick();
        expect(spyRouter).toHaveBeenCalledWith(['../']);
        expect(spyFeedback).toHaveBeenCalled();
    }));


    it('should get case by id', () =&gt; {
        const id = 66208014;
        const setupResponse = new CaseBaseModel({
            id,
            dateSubmitted: '',
            owner: caseOwnerEnum.caseManager,
            reference: 'ksjhkjshdf',
            status: caseStatusEnum.submitted,
            type: caseTypeEnum.revisionRequest,

        });
        afwHttpMock.setupOnlyResponse(setupResponse, 200);
        service.getCase(id, 'spinner').subscribe(r =&gt; {
            expect(r).toEqual(setupResponse);
        });
        afwHttpMock.returnSuccessResponse();
    });

    it('edit the case with model', () =&gt; {
        const spy = spyOn(service, 'editCase').and.callThrough();

        const caseUpdate = new CaseBaseModel({
            id: 100001075,
            dateSubmitted: '',
            owner: caseOwnerEnum.caseManager,
            reference: 'ksjhkjshdf',
            status: caseStatusEnum.submitted,
            type: caseTypeEnum.revisionRequest,

        });
        service.editCase('spinner', caseUpdate);
        expect(spy).toHaveBeenCalledWith('spinner', caseUpdate);
        expect(caseUpdate.id).toEqual(100001075);
    });
});
</code></pre>
",https://stackoverflow.com/questions/53504349/jasmine-test-with-selecting-items-from-list,"['javascript', 'angular', 'karma-jasmine']",1253,TRUE,4,1
"What is the difference between unit, integration and end-to-end tests in Angular?","<ol>
<li>What is the difference between Unit, Integration and End-to-end testing in Angular?</li>
<li>Which the principles or paradigms should I know to implement each kind of these tests, how it works?</li>
</ol>
<p>I found out that unit testing is for component class, integration testing is for component's class and template together.</p>
<p>But I didn't find how does end-to-end testing differ from these ones, how can I implement them in Angular, which are the principles and paradigms for these types of testing.</p>
",https://stackoverflow.com/questions/52606199/what-is-the-difference-between-unit-integration-and-end-to-end-tests-in-angular,"['angular', 'testing']",2244,TRUE,4,1
"Python asyncio: what satisfies `isinstance( (generator-based coroutune), ???) == True`?","<p>I'm baffled to find out neither of <code>typing.Awaitable</code> nor <code>collections.abc.Awaitable</code> cover a generator-based coroutine which is one of <em>awaitable</em>s defined in</p>

<ul>
<li><a href=""https://www.python.org/dev/peps/pep-0492/#await-expression"" rel=""noreferrer"">https://www.python.org/dev/peps/pep-0492/#await-expression</a></li>
</ul>

<p>As of Python 3.6, several <code>asyncio</code> APIs such as <code>sleep()</code> and <code>open_connection()</code> actually return generator-based coroutines. I usually have no problems with applying <code>await</code> keywords to the return values of them, but I'm going to handle a mixture of normal values and <em>awaitable</em>s and I'd need to figure out which ones require <code>await</code> to yield an actual value.</p>

<p>So here's my question, what satisfies <code>isinstance(c, ???) == True</code> for an arbitrary generator-based coroutine <code>c</code>?  I'm not insisting on using <code>isinstance</code> for this purpose, maybe <code>getattr()</code> can be a solution...</p>

<h2>Background</h2>

<p>I'm working on a tiny mock utility for unit testing of async function based on <a href=""https://blog.miguelgrinberg.com/post/unit-testing-asyncio-code"" rel=""noreferrer"">https://blog.miguelgrinberg.com/post/unit-testing-asyncio-code</a> which internally has a <code>asyncio.Queue()</code> of mocked return values, and I want to enhance my utility so that the queue can have <em>awaitable</em> elements, each of which triggering <code>await</code> operation. My code will look like</p>

<pre><code>async def case01(loop):
  f = AsyncMock()
  f.side_effect = loop, []
  await f()  # blocks forever on an empty queue

async def case02(loop):
  f = AsyncMock()
  f.side_effect = loop, ['foo']
  await f() # =&gt; 'foo'
  await f() # blocks forever

async def case03(loop):
  f = AsyncMock()
  f.side_effect = loop, [asyncio.sleep(1.0, 'bar', loop=loop)]
  await f() # yields 'bar' after 1.0 sec of delay
</code></pre>

<p>For usability reason, I don't want to manually wrap the return values with <code>create_task()</code>.</p>

<p>I'm not sure my queue will ever legitimely contain normal, non-coroutine generators; still, the ideal solution should be able to distinguish normal generators from generator-based coroutines and skip applying <code>await</code> operation to the former.</p>
",https://stackoverflow.com/questions/49346154/python-asyncio-what-satisfies-isinstance-generator-based-coroutune,"['python', 'async-await', 'generator', 'python-asyncio']",1754,TRUE,5,2
chai how to check that function returns a promise,"<p>I'm using sinon / chai and some other plugins, I can test promises and their results, etc, but how can I ensure that a function returns a promsie?</p>

<p>I realize that if other tests pass (eg. when you run the rest with return or await and get expected result) it means it is a promise, but is there something along the lines of:</p>

<pre><code>expect(foo).to.return.a('promise')
</code></pre>

<p><strong>EDIT:</strong> Unfortunately the suggested post did NOT answer my question with unit testing, but I did figure out the answer:</p>

<pre><code>let result = foo();
expect(result).to.be.a('promise');
</code></pre>
",https://stackoverflow.com/questions/49862496/chai-how-to-check-that-function-returns-a-promise,"['node.js', 'unit-testing', 'sinon', 'chai']",782,TRUE,4,1
How to use ArgumentCaptor in mockito,"<p>I'm learning Mockito and Unit Testing in general. I want to learn how to unit test better by using Argument Captor. I'm using jdbc to handle my SQL statement. I have a method that inserts a user into my DB.</p>

<pre><code>public void insert(User user) {
   String sql = ""INSERT INTO user (id) VALUES ?"";
   jdbcTemplate.update(new PreparedStatementCreator() {
     @Override
     public PreparedStatement createPreparedStatement(Connection connection) {
       final PreparedStatement ps = connection.prepareStatement(sql);
       ps.setString(1, user.getId().trim());
       return ps;
     }
   });
 }
</code></pre>

<p>Below is the test that I'm trying to write with ArgumentCaptor.</p>

<pre><code>    @Test
      public void testInsert() {
        User user = new User(""testID"");
        ArgumentCaptor&lt;PreparedStatementCreator&gt; captor = ArgumentCaptor.forClass(PreparedStatementCreator.class);
        insert(user);
        verify(mockJdbc, times(1)).update(captor.capture());
        PreparedStatementCreator actual = captor.getValue();
        assertEquals(??, actual.createPreparedStatement(??));
      }
</code></pre>

<p>Any advice or insight on what should be in the '??' for the assert statement or if this is the correct way to use Argument Captor?</p>

<p>Thank You</p>

<p>Edit:</p>

<pre><code>      @Test
      public void testInsert() throws SQLException {
            ArgumentCaptor&lt;PreparedStatementCreator&gt; captor = ArgumentCaptor.forClass(PreparedStatementCreator.class);
            PreparedStatement ps = mockConnection.prepareStatement(""INSERT INTO user (id) VALUES ?"";);
            ps.setString(1, user.getId().trim());
            insert(user);
            verify(mockJdbcTemplate, times(1)).update(captor.capture());
            PreparedStatementCreator actual = captor.getValue();
            assertEquals(ps, actual.createPreparedStatement(mockConnection));
          }
</code></pre>
",https://stackoverflow.com/questions/49355067/how-to-use-argumentcaptor-in-mockito,"['java', 'mockito']",10620,TRUE,1,1
How to test a method that is invoking methods of another class?,"<p>I'm trying to understand how to do unit testing with Mockito. 
All the cases that I found is when a class A depends on a class B, that is A has an attribute of type B. I understand well this case. But how to do the tests when A uses B without getting it as attribute.</p>

<p>Suppose I have this code:</p>

<pre><code>import package.classB;
public class A
{
    public int methodA(classB b) 
    {
    int x= b.methodB();
    //do something with x and then return the result
    }
}
</code></pre>

<p>How can I test the methodA?  Do I need to use mocks in this case?</p>
",https://stackoverflow.com/questions/48917543/how-to-test-a-method-that-is-invoking-methods-of-another-class,"['java', 'unit-testing', 'mocking']",1622,TRUE,1,1
"Angular unit test, mock property of provider","<p>I'm really new to unit testing and especially with Angular. I have a problem, in my <code>TestBed.configureTestingModule</code> I have provider which has private getter and this getter relies on an custom generic service which gets the value from a file. How can I mock this value without having to rely on the custom service which searches for a specific file? Lets say the getter is <code>url</code>. I've tried with </p>

<pre><code>{
   provide: SomeService, useValue: {
     url: 'www.test.com'
   }
},
</code></pre>

<p>But then I get error in my component <code>this.someService.SomeFunction is not a function</code>, what am I missing?</p>
",https://stackoverflow.com/questions/52819456/angular-unit-test-mock-property-of-provider,"['angular', 'karma-jasmine']",9069,TRUE,1,1
How to unit test API calls with axios() in react-native with Jest,"<p>I am developing Sample Application in React-native . I used Jest to use unit testing, i don't have an idea about Jest Api call 
I want to need without using Promises:
Here this is my Code:</p>

<p>this is My Function Code:</p>

<pre class=""lang-js prettyprint-override""><code>/**
 * @description Action to call nilpick service ,on success increment route as well as mark the location as fulfilled
 */

function nilPick() {
  return async (dispatch, getState) =&gt; {
    const currentState = getState();
    const { user, picking } = currentState;
    const { currentRouteIndex, pickRoute } = getState().picking.pickRouteInfo;
    const { workId } = picking.pickWorkInfo;
    const nilPickItem = pickRoute[currentRouteIndex];
    const currentItem = getCurrentItem(currentState);
    const currentTime = dateFunctions.getCurrentUTC();

    const nilpickedItem = [
      {
        orderId: nilPickItem.fulfillOrdNbr,
        lineNbr: nilPickItem.ordLine,
        pickUpcNbr: nilPickItem.upc,
        pickDisplayTs: currentTime,
        pickUom: currentItem.workDetail.uom,
        pickedLoc: nilPickItem.location,
        locationType: nilPickItem.locType,
        locId: nilPickItem.locId,
        pickByType: currentItem.workDetail.pickByType,
        exceptionPick: false,
        gtinPrefRankNbr: 0,
        pickUpcTypeCd: 5100
      }
    ];

    const { status, statusText } = await pickingService.nilPick(nilpickedItem, user, workId);
    if (status === 200 || statusText === 'Created') {
      console.info('Item nilpicked');
      if (currentRouteIndex &lt; pickRoute.length) {
        dispatch(incrementRoute());
      } else {
        Alert.alert(
          'Nilpick Complete',
          [
            {
              text: 'OK',
              onPress: () =&gt; {
                dispatch(endPicking());
              }
            }
          ],
          { cancelable: false }
        );
        console.log('End of pickwalk');
        return;
      }
    } else {
      console.info('error in nilpicking item ');
    }
  };
}
</code></pre>

<p>This is my code above method to Converting Like this below sample test Case:
    This is sample Test  i want to call Api How to implement in Jest</p>

<pre class=""lang-js prettyprint-override""><code>it('Test For nillPic', () =&gt; {
  const initialState = {
    picking: {
      pickRouteInfo: {
        ""fulfillOrdNbr"": pickRouteInfo.fulfillOrdNbr,
        ""orderLine"": '1',
        ""upc"": '4155405089',
        ""location"": 'A-1-1',
        ""availableLocsToPick"": '2',
        'suggSubPendingPicks?': 'N',
        'manualSubPendingPicks?': 'N',
        ""lineFullfilled"": 'false',
        ""currentRouteIndex"": 1,
        ""pickRoute"": ['r1', 'r2', 'r3']
      }
    }
  };
  // console.log(""state data..."", initialState);
  const store = mockStore(initialState);
  store.dispatch(actions.pickRouteActions.nilPickSuccess());
  const expectedAction = [{ type: 'INCREMENT_ROUTE' }];
  const localActions = store.getActions();
  expect(localActions).toEqual(expectedAction);
});
</code></pre>

<p>Finally This is my code Please . Thanks in Advance</p>
",https://stackoverflow.com/questions/50711349/how-to-unit-test-api-calls-with-axios-in-react-native-with-jest,"['react-native', 'redux', 'jestjs']",210,FALSE,1,0
unit test main.py with other modules,"<p>This is more a conceptual question. I am unit testing a script I wrote that has multiple modules. I have a main.py and a formatting.py. My coverage is at 100% for formatting but my main.py is at 30%. In my main, I just call all of the functions inside formatting. Do i need to just test them again in main directly? This seems like a waste of time? Maybe I am not understanding correctly. Thanks in advance</p>
",https://stackoverflow.com/questions/51292465/unit-test-main-py-with-other-modules,"['python', 'unit-testing']",149,TRUE,1,3
kotlin + aws lambda requiring empty constructor,"<p>I have the following class written in Kotlin+Guice that is invoked with a lambda</p>

<pre><code>class LambdaProcessor @Inject constructor(private val s3Util: S3Util) {

    fun lambdaInvokesThisMethod() {
        s3Util.DoSomething()
    }
}
</code></pre>

<p>That works great for unit testing, but lambda requires the class to have an empty constructor.</p>

<p>I can convert this same class to have an empty constructor by doing this:</p>

<pre><code>class LambdaProcessor {

    @Inject lateinit var s3Util: S3Util

    init {
        Guice.createInjector(GuiceDependencyInjector()).injectMembers(this)
    }

    fun lambdaInvokesThisMethod() {
        s3Util.DoSomething()
    }
}
</code></pre>

<p>That code now works great on lambda but I can't mock s3Util in my unit tests anymore because the init method gets called.</p>

<p>How can I get both scenarios to work together?</p>
",https://stackoverflow.com/questions/52999044/kotlin-aws-lambda-requiring-empty-constructor,"['kotlin', 'guice']",1062,TRUE,1,2
Test to verify that component element exists in DOM - Jasmine &amp; Angular,"<p>Hello Stack Overflow Community,</p>

<p>I’m having issues writing a simple Jasmine Unit Testing in Angular 5 to verify the existence of an element in the DOM for components. I have a successful test for standard HTML elements, such as p:  <code>expect(fixture.debugElement.query(By.css('p')).nativeElement).toBeTruthy();</code></p>

<p>But, this results in a TypeError: Cannot read property 'nativeElement' of null for Angular components. As an example, a Movie Component with a selector of app-movie:</p>

<p><code>it ('should have a element selector called app-root in DOM', () =&gt; {
    expect(fixture.debugElement.query(By.css(‘app-movie’)).nativeElement).toBeTruthy();</code></p>

<p>Can you please advise how to do this? Many thanks!</p>
",https://stackoverflow.com/questions/49976513/test-to-verify-that-component-element-exists-in-dom-jasmine-angular,"['angular', 'testing', 'angular5']",7422,TRUE,1,2
Angular Testing Getting Actual HTTP Response,"<p>I'm new to angular unit testing. What I want to do is getting actual results from my API. I checked <a href=""https://angular.io/guide/http#testing-http-requests"" rel=""nofollow noreferrer"">this</a> documentation but as I understand, I should create mock responses. Here is my code,</p>

<p><strong>myService.ts:</strong></p>

<pre><code>...

public GetAll = (apiname: string): Observable&lt;Object&gt; =&gt; {

return this._http.get(""foo/"" + apiname,{headers:this.options}); //this.options = newHttpHeaders({'ContentType':'application/json','Accept':'application/json'});
}
...
</code></pre>

<p><strong>myService.spec.ts:</strong></p>

<pre><code>...

beforeEach(() =&gt; {
    TestBed.configureTestingModule({
    imports: [
        HttpClientModule,
        HttpClientTestingModule
    ],
    providers: [
        MyService
    ]
    });  
});

afterEach(inject([HttpTestingController], (backend: HttpTestingController) =&gt; {
    backend.verify();
}));

it('GetAll() should work', () =&gt; {

    const testData = {id: ""123""};

    service.GetAll(""items"").subscribe(data =&gt; { 
        //console.log(JSON.stringify(data));
    });

    const req = httpTestingController.expectOne('foo/items');
    expect(req.request.method).toEqual('GET');

    req.flush(testData);
    httpTestingController.verify();
});
</code></pre>

<p>When I write the result in console, it writes 'testData' instead of 'data'. As I said before, I want to get actual result from my API, not mock result. Sorry if it is a silly question but how can I do that ? Thanks for advice.</p>
",https://stackoverflow.com/questions/49550041/angular-testing-getting-actual-http-response,"['angular', 'unit-testing', 'angular-http', 'angular-test']",7276,TRUE,4,3
Karma/Jasmine Angular Error: Cannot read property &#39;frmUser&#39; of undefined,"<p>I am new to unit testing and am trying to test a basic form in the app. It is just a form where a user signs up and submits some credentials. I am trying to test the validators but am having trouble running the unit test. I get this error when preforming the test:</p>

<pre><code>TypeError: Cannot read property 'frmUser' of undefined
TypeError: Cannot read property 'frmUser' of undefined
    at UserContext.&lt;anonymous&gt; (http://localhost:9876/_karma_webpack_/webpack:/src/app/components/user/user.component.spec.ts:54:29)
    at ZoneDelegate.webpackJsonp../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:388:1)
    at ProxyZoneSpec.webpackJsonp../node_modules/zone.js/dist/zone-testing.js.ProxyZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone-testing.js:288:1)
    at ZoneDelegate.webpackJsonp../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:387:1)
    at Zone.webpackJsonp../node_modules/zone.js/dist/zone.js.Zone.run (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:138:1)
    at runInTestZone (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone-testing.js:509:1)
    at UserContext.&lt;anonymous&gt; (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone-testing.js:524:1)
    at attempt (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?73bc53d3671677e6a093fc74e4f9bcde57e5f7ad:4289:46)
    at ZoneQueueRunner.QueueRunner.run (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?73bc53d3671677e6a093fc74e4f9bcde57e5f7ad:4217:20)
    at runNext (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?73bc53d3671677e6a093fc74e4f9bcde57e5f7a
</code></pre>

<p>Here is my component class where I make my form:</p>

<pre><code>  frmUser: FormGroup;
  userInfo: User;
  userId: number;
  fileType: any[] = [""Claim"", ""Policy""];
  programs: any;
  constructor(public dialog: MatDialog, public dialogRef: MatDialogRef&lt;UserComponent&gt;, @Inject(MAT_DIALOG_DATA) public data: any, private fb: FormBuilder, private httpService: HttpService, private httpClient: HttpClient) {
    this.userId = this.data.userId;

  }

  ngOnInit() {
    console.log(this.fileType);
    this.getPrograms();
    this.createUserForm();
    if (this.userId &gt; 0)
      this.loadUser();
  }
</code></pre>

<p>And here is where I create the input fields:</p>

<pre><code>createUserForm() {
    this.frmUser = this.fb.group(
      {
        UserID: [],
        FirstName: ["""", [Validators.required, Validators.maxLength(50)]],
        MiddleName: [],
        LastName: ["""", [Validators.required, Validators.maxLength(50)]],
        EmailAddress: [{ value: '', disabled: this.userId &gt; 0 }, [Validators.required, Validators.email]],
        UserAccessDetail: this.fb.array([this.createUserProgram()])
      }
    )
  }
</code></pre>

<p>My test class:</p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule, FormsModule, FormControl, FormBuilder, FormArray, FormGroup, Validators } from '@angular/forms';
import { UserComponent } from './user.component';
import { MatDialogRef, MAT_DIALOG_DATA, MatDialog } from '@angular/material/dialog';

import { MatDialogModule} from '@angular/material';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { HttpService } from '../../services/http.service';
import { HttpClient } from '@angular/common/http';
import { inject } from '@angular/core/testing';
import { User } from '../../models/user';


fdescribe(""Form User"", () =&gt; {
let component: UserComponent;
let fixture: ComponentFixture&lt;UserComponent&gt;;
beforeEach(async(() =&gt; {



  TestBed.configureTestingModule({
    declarations: [
      UserComponent
    ],

    imports: [FormsModule,ReactiveFormsModule],
    schemas: [ CUSTOM_ELEMENTS_SCHEMA ],

    providers: [
      { provide: MatDialog, useValue: {} },
      { provide: MatDialogRef, useValue: {} },
      { provide:  MAT_DIALOG_DATA, useValue: {} },
      { provide:  HttpService, useValue: {} },
      { provide:  HttpClient, useValue: {} },


  ]

  }).compileComponents();

beforeEach(() =&gt; {

  fixture = TestBed.createComponent(UserComponent);
  component = fixture.componentInstance;

  component.ngOnInit();
})

}));

it('Should prompt an invalid textbox validator', () =&gt; {



  let textField = component.frmUser.get('FirstName');

  textField.setValue('');

  expect(textField.valid).toBeFalsy();
})

})
</code></pre>

<p>Thank you!</p>
",https://stackoverflow.com/questions/50802756/karma-jasmine-angular-error-cannot-read-property-frmuser-of-undefined,"['angular', 'jasmine', 'automated-tests', 'karma-runner']",2490,FALSE,1,1
Must you join on a Thread to ensure its computation is complete,"<p>I have a utility method (used for unit testing, it so happens) that executes a <code>Runnable</code> in another thread. It starts the thread running, but does not wait for the <code>Thread</code> to finish, instead relying on a <code>Future</code>. A caller of the method is expected to <code>get()</code> that <code>Future</code>. But is that enough to ensure safe publication of the computation done by the <code>Runnable</code>?</p>

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

<pre><code>private static Future&lt;Void&gt; runInOtherThread(final CountDownLatch ready, final Runnable operation) {
    final CompletableFuture&lt;Void&gt; future = new CompletableFuture&lt;Void&gt;();
    final Thread thread = new Thread(() -&gt; {
        try {
            ready.await();
            operation.run();
        } catch (Throwable e) {
            future.completeExceptionally(e);
            return;
        }
        future.complete(null);
    });
    thread.start();
    return future;
}
</code></pre>

<p>After calling <code>Future.get()</code> on the returned <code>Future</code>, can the caller of the method safely assume that the <code>Runnable</code> has finished execution, and its results have been safely published?</p>
",https://stackoverflow.com/questions/53733735/must-you-join-on-a-thread-to-ensure-its-computation-is-complete,"['java', 'multithreading', 'future']",394,TRUE,6,2
Testing method in UITabBarController sets title correctly,"<p>I am currently trying to understand Unit Testing in Swift 4.
I have a class, with a method that setups my view controllers.</p>

<p>I would like to ensure that this method sets the title on the ViewController correctly. </p>

<p>However I cannot understand how to write this test?</p>

<p>This is my code and test so far.</p>

<p>Currently my tests fails with:</p>

<pre><code>XCTAssertEqual failed: (""nil"") is not equal to (""Optional(""Favourites"")"") - 
</code></pre>

<p>How is it possible to test this behaviour? Any help would be much appreciated. </p>

<p><strong>Controller</strong></p>

<pre><code>class MainTabBarController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        setupTabBar()
        setupViewControllers()
    }

    // MARK:- Setup

    fileprivate func setupViewControllers() {
        viewControllers = [
            generateNavigationController(with: UIViewController(), title: ""Favourites"", image: UIImage(imageLiteralResourceName: ""favorites"")),
            generateNavigationController(with: UIViewController(), title: ""Search"", image: UIImage(imageLiteralResourceName: ""search"")),
            generateNavigationController(with: UIViewController(), title: ""Downloads"", image: UIImage(imageLiteralResourceName: ""downloads""))
        ]
    }

    fileprivate func setupTabBar() {
        tabBar.tintColor = .purple
    }

    // MARK:- Helpers

    fileprivate func generateNavigationController(with rootViewController: UIViewController, title: String, image: UIImage) -&gt; UIViewController {

        let controller = UINavigationController(rootViewController: rootViewController)

        controller.tabBarItem.title = title
        controller.tabBarItem.image = image

        rootViewController.navigationItem.title = title
        navigationController?.navigationBar.prefersLargeTitles = true

        return controller
    }
}
</code></pre>

<p><strong>Tests</strong></p>

<pre><code>import Foundation
import XCTest

@testable import Podcasts

class MainTabBarControllerTests: XCTestCase {

    func testTheInitialViewControllerShouldHaveTitleFoo() {
        let sut = MainTabBarController()

       let _ = sut.viewDidLoad()

        XCTAssertEqual(sut.navigationItem.title, ""Favourites"")
    }
}
</code></pre>
",https://stackoverflow.com/questions/52579803/testing-method-in-uitabbarcontroller-sets-title-correctly,"['swift', 'unit-testing', 'xctest', 'xctestcase']",1229,TRUE,0,1
unable to test a method which uses Observable in Jasmine,"<p>My <code>Angular</code> application has a service <code>QuestionManagementService</code> which response on a <code>BackendService</code> to send <code>REST</code> messages. The <code>BackendService</code> in turn uses <code>HttpClient</code>. I am trying to test the <code>QuestionManagementService</code> in isolation. </p>

<p>The method I am testing is <code>addQuestion</code></p>

<pre><code>addQuestion(question:PracticeQuestion):any{
    console.log(""In QuestionManagementService: addQuestion: "",question);
   this.bs.createQuestion(question).subscribe((res)=&gt;{
      console.log(""add practice question - response is "",res);//I EXPECT THESE PRINTS TO SHOW BUT THEY DON'T
      let ev = &lt;HttpEvent&lt;any&gt;&gt;(res);
      if(ev.type === HttpEventType.Response) {
        console.log('response from server: returning body '+ev.body);
        let isResponseStructureOK: boolean = this.helper.validateServerResponseStructure(ev.body);
        if (isResponseStructureOK) {
          let response:ServerResponseAPI = ev.body;
          console.log(""received response from server: "" + response.result);
          this.addQuestionSubject.next(new Result(response.result,response['additional-info']));

        } else {
          console.log(""received incorrect response structure from server: "", ev.body);
          this.addQuestionSubject.next(new Result('error','Invalid response structure from server'));

        }
      }
      else {
        console.log(""not response. ignoring"");
      }
    },
    (error:ServerResponseAPI)=&gt;{
      console.log(""got error from the Observable: "",error);
      let errorMessage:string = this.helper.userFriendlyErrorMessage(error);
      this.addQuestionSubject.next(new Result('error',errorMessage));//TODOM - need to standardise errors

    },
    ()=&gt;{ //observable complete
        console.log(""observable completed"")
      });
  }
</code></pre>

<p>As I am doing unit testing of <code>addQuestion</code>, I thought that I can mock the <code>createQuestion</code> method of the <code>BackendService</code>. The <code>spec</code> I have written so far is the following but I don't think it is correct as I don't see any prints on the console when the mocked response of <code>createQuestion</code> is received.</p>

<pre><code>fit('should add a question',()=&gt;{
    let backendService = TestBed.get(WebToBackendInterfaceService);
    let questionService = TestBed.get(QuestionManagementService);
    let question = new PracticeQuestion(...);

    const responseData = { result: 'success', ['additional-info']: 'question added successfully' };
    let httpResponseEvent:HttpResponse&lt;any&gt; = new HttpResponse&lt;any&gt;({body:responseData});
    //mock response of WebToBackendInterfaceService
    spyOn(backendService,'createQuestion').and.returnValue(new Observable(()=&gt;{
      httpResponseEvent;
    }));

    questionService.addQuestion$.subscribe((res:Result)=&gt;{
      console.log('received response from Question Services',res);
      expect(res).toBeTruthy();
      let validResponse:boolean = ((res.result === 'success') || (res.result === 'initial')) ;
      expect(validResponse).toEqual(true);
    });
    questionService.addQuestion(question);
    expect(backendService.createQuestion).toHaveBeenCalled();
  });
</code></pre>
",https://stackoverflow.com/questions/53421302/unable-to-test-a-method-which-uses-observable-in-jasmine,"['angular6', 'angular-test']",1307,FALSE,0,1
Angular 6: Failed: Template parse errors: Can&#39;t bind to &#39;routerLink&#39; since it isn&#39;t a known property of &#39;a&#39;. (,"<p>I am testing my app using <code>npm test</code></p>

<p>I am getting the following error :</p>

<pre><code>Failed: Template parse errors:
Can't bind to 'routerLink' since it isn't a known property of 'a'. (""
    &lt;nav&gt;
      &lt;ul&gt;
        &lt;li&gt;&lt;a class=""nav-link active"" [ERROR -&gt;][routerLink]=""['/movies']"" routerLinkActive=""active-link"" [routerLinkActiveOptions]=""{exact: true}"" c""): ng:///DynamicTestModule/AppComponent.html@4:39
Can't bind to 'routerLinkActiveOptions' since it isn't a known property of 'a'. (""l&gt;
        &lt;li&gt;&lt;a class=""nav-link active"" [routerLink]=""['/movies']"" routerLinkActive=""active-link"" [ERROR -&gt;][routerLinkActiveOptions]=""{exact: true}"" class=""fa fa-home""&gt;&lt;span&gt;Home&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;""): ng:///DynamicTestModule/AppComponent.html@4:97
Can't bind to 'routerLink' since it isn't a known property of 'a'. (""uterLinkActiveOptions]=""{exact: true}"" class=""fa fa-home""&gt;&lt;span&gt;Home&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;a [ERROR -&gt;][routerLink]=""['/movies']"" class=""fa fa-film""&gt;&lt;span&gt;Best Movies 200's&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;a ""): ng:///DynamicTestModule/AppComponent.html@5:15
Can't bind to 'routerLink' since it isn't a known property of 'a'. (""routerLink]=""['/movies']"" class=""fa fa-film""&gt;&lt;span&gt;Best Movies 200's&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;a [ERROR -&gt;][routerLink]=""['/theatre']"" class=""fa fa-television""&gt;&lt;span&gt;Movies in Theatre&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
        ""): ng:///DynamicTestModule/AppComponent.html@6:15
Can't bind to 'routerLink' since it isn't a known property of 'a'. (""ink]=""['/theatre']"" class=""fa fa-television""&gt;&lt;span&gt;Movies in Theatre&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;a [ERROR -&gt;][routerLink]=""['/tvshows']"" class=""fa fa-video-camera""&gt;&lt;span&gt;Tv Shows&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;a ""): ng:///DynamicTestModule/AppComponent.html@7:15
'router-outlet' is not a known element:
1. If 'router-outlet' is an Angular component, then verify that it is part of this module.
2. If 'router-outlet' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. (""

&lt;div class=""container""&gt;
  [ERROR -&gt;]&lt;router-outlet&gt;&lt;/router-outlet&gt;
&lt;/div&gt;""): ng:///DynamicTestModule/AppComponent.html@15:2
</code></pre>

<p>here is the html page am using , app html</p>

<pre><code>&lt;section&gt;
  &lt;div class=""tabs tabs-style-fillup""&gt;
    &lt;nav&gt;
      &lt;ul&gt;
        &lt;li&gt;&lt;a class=""nav-link active"" [routerLink]=""['/movies']"" routerLinkActive=""active-link"" [routerLinkActiveOptions]=""{exact: true}"" class=""fa fa-home""&gt;&lt;span&gt;Home&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;a [routerLink]=""['/movies']"" class=""fa fa-film""&gt;&lt;span&gt;Best Movies 200's&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;a [routerLink]=""['/theatre']"" class=""fa fa-television""&gt;&lt;span&gt;Movies in Theatre&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;a [routerLink]=""['/tvshows']"" class=""fa fa-video-camera""&gt;&lt;span&gt;Tv Shows&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;a href=""#section-fillup-5"" class=""fa fa-gear""&gt;&lt;span&gt;Settings&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;
      &lt;/ul&gt;
    &lt;/nav&gt;
  &lt;/div&gt;&lt;!-- /tabs --&gt;
&lt;/section&gt;

&lt;div class=""container""&gt;
  &lt;router-outlet&gt;&lt;/router-outlet&gt;
&lt;/div&gt;
</code></pre>

<p>here is the main module , app module.ts</p>

<pre><code>    import { BrowserModule } from '@angular/platform-browser';
    import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
    import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
    import { FormsModule, ReactiveFormsModule } from '@angular/forms';
    import { HttpModule } from '@angular/http';
    import { HttpClientModule } from '@angular/common/http';
    import { RouterModule } from '@angular/router';
    import { AppComponent } from './app.component';
    import { MoviesComponent } from './movies/movies.component';
    import { AppRoutingModule } from './app-routing/app-routing.module';
    import { TheatreComponent } from './theatre/theatre.component';
    import { TvShowsComponent } from './tv-shows/tv-shows.component';
    import { DataFilterPipe } from './data-filter.pipe';
    import {MatTableModule} from '@angular/material/table';
    // tslint:disable-next-line:max-line-length
    import {MatFormFieldModule, MatSortModule, MatInputModule, MatAutocompleteModule, MatBadgeModule, MatBottomSheetModule, MatSelectModule} from '@angular/material';
    import {MatPaginatorModule} from '@angular/material/paginator';
    import { CdkTableModule } from '../..

/node_modules/@angular/cdk/table';
import { CdkTreeModule } from '../../node_modules/@angular/cdk/tree';
@NgModule({
  declarations: [
    AppComponent,
    MoviesComponent,
    TheatreComponent,
    TvShowsComponent,
    DataFilterPipe
  ],
  imports: [
    AppRoutingModule,
    BrowserModule,
    MatFormFieldModule,
    ReactiveFormsModule,
    MatSortModule,
    MatTableModule,
    MatPaginatorModule,
    MatSelectModule,
    CdkTableModule,
    CdkTreeModule,
    MatAutocompleteModule,
    MatBadgeModule,
    MatBottomSheetModule,
    MatInputModule,
    HttpModule,
    BrowserAnimationsModule,
    HttpClientModule,
    FormsModule,
    RouterModule
  ],
  schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code></pre>

<p>here is my custom module for routing app routing module</p>

<pre><code>import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { MoviesComponent } from '../movies/movies.component';
import { TheatreComponent } from '../theatre/theatre.component';
import { TvShowsComponent } from '../tv-shows/tv-shows.component';
import { CommonModule } from '@angular/common';
const routes: Routes = [
  {
    path: 'movies',
    component: MoviesComponent
  },
  {
    path: 'theatre',
    component: TheatreComponent
  },
  {
    path: 'tvshows',
    component: TvShowsComponent
  },
  {
    path: '',
    redirectTo: 'movies',
    pathMatch: 'full'
  }
];

@NgModule({
  imports: [CommonModule, RouterModule.forRoot(routes)],
  exports: [RouterModule],
  schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
export class AppRoutingModule { }
</code></pre>

<p>**</p>

<blockquote>
  <p>UPDATE</p>
</blockquote>

<p>**</p>

<p>Here is test spec .ts file </p>

<pre><code>import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () =&gt; {
  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));
  it('should create the app', async(() =&gt; {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  }));
  it(`should have as title 'app'`, async(() =&gt; {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app.title).toEqual('app');
  }));
  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('Welcome to movies-client!');
  }));
});
</code></pre>

<p>Note : I tried to add <code>CUSTOM_ELEMENTS_SCHEMA</code> to the app component.spec.ts stil the got the same error, tried different combination but nothing am I missing something in unit testing ? or what ? </p>

<p><strong>Question</strong></p>

<p>what is wrong with my codes? </p>
",https://stackoverflow.com/questions/51552795/angular-6-failed-template-parse-errors-cant-bind-to-routerlink-since-it-is,"['angular', 'typescript', 'unit-testing', 'bootstrap-4', 'karma-jasmine']",2266,TRUE,3,1
"How to initialize instance for test, when constructor call private method and return exception","<p>In my case,
Student.java</p>

<pre><code>public class Student{
    private String studentId;
    public Student(String name){
        super(name);
        setId();
        range();
    }
    private void range() throw Exception{
        final studentDetails = Loader.load(studentId);
    }

    private void setId(){
        final studentId = ""123"";
    }

    public void getAge(){};
}
</code></pre>

<p>Loader.load call read property file and throw file not exist exception.in this case Loader.load method is static.</p>

<p>When I write unit testing,</p>

<p>StudentTest.java</p>

<pre><code>public class StudentTest{
    private Student student;
    private String name;

    @BeforeMethod
    public void setUp() throws Exception{
        MockitoAnnotations.initMocks(this);
        name = ""Peter"";
        student = new Student(name);
    }

    @Test
    public void testGetAge(){
    }
}
</code></pre>

<p>In this scenario throw file not found exception in <code>setUp()</code>. I'm using TestNG, Java 8, Mockito.
How can I solve this problem. Is there a way to skip constructor call <code>range()</code> method in it initialising on test class? My project doesn't use PowerMockito.
please consider provided code is example of my real problem.</p>
",https://stackoverflow.com/questions/48763558/how-to-initialize-instance-for-test-when-constructor-call-private-method-and-re,"['java', 'unit-testing', 'constructor', 'mockito', 'testng']",550,TRUE,0,3
Jest/Enzyme Unit Test on Axios Requests in ComponentDidMount(),"<p>I am trying to perform some unit testing on my existing react application with Jest and Enzyme. I am totally new to this stuff and accurately I do not know how to approach such test scenarios. I know that to test API request calls I have to perform some &quot;mocking&quot;, but how should I write the test for that?. What will be the steps that needs to be followed?</p>
<p>Following is the code snippet I am looking to test.</p>
<p>Home.js</p>
<pre><code>import React,{Component} from 'react'
import axios from 'axios';
import {Link} from 'react-router-dom';
import FacilityModal from '../Table/FacilityModal';

class Home extends Component {
  state = {
    cities:[],
    name:''
  }
 
  componentDidMount() {
    axios.get('/cities').then(res =&gt; {
      this.setState({cities:res.data})
      console.log(&quot;Oza&quot; + JSON.stringify(res))
    });
    console.log(this.state.cities)
  }
 
  render() {
    let postList = this.state.cities.map(city =&gt; {
      return(
        &lt;div key = {city.id}&gt;
          &lt;p&gt;
            &lt;Link to = {'/'+city.id}&gt;{city.name}&lt;/Link&gt;
          &lt;/p&gt;
        &lt;/div&gt;
      )
    })
    return(
      &lt;div className = 'align'&gt;All Facilities (NCAL)
        &lt;div className=&quot;hr-sect&quot;&gt;OR&lt;/div&gt;
        &lt;div className = 'Modal'&gt;
          {postList}
        &lt;/div&gt;
        &lt;FacilityModal cityname = {this.props} /&gt;
      &lt;/div&gt;
    )
  }
}
</code></pre>
",https://stackoverflow.com/questions/52745388/jest-enzyme-unit-test-on-axios-requests-in-componentdidmount,"['reactjs', 'jestjs', 'enzyme']",6743,TRUE,3,2
ImportError: cannot import name &#39;isclose&#39;,"<p>I am running into a weird error when unit testing my Python module:</p>

<p>⅔ of the builds are passing normally, but one of them is failing to import <code>isclose</code> from the standard <code>math</code> library.</p>

<p>The error is reproduced below:</p>

<pre><code>==================================== ERRORS ====================================
______________________ ERROR collecting tests/test_yau.py ______________________
ImportError while importing test module '/home/travis/build/Benjamin-Lee/squiggle/tests/test_yau.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
tests/test_yau.py:5: in &lt;module&gt;
    from math import isclose
E   ImportError: cannot import name 'isclose'
!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!!
=========================== 1 error in 0.29 seconds ============================
The command ""pytest --cov=squiggle"" exited with 2.
</code></pre>

<p>There is no file named <code>math.py</code> in the same directory (or at all in my package). What could be causing this?</p>

<p>Restarting the build multiple times has not fixed this error and it is only showing up in Python 3.4.</p>

<p>The full logs are accessible <a href=""https://travis-ci.org/Benjamin-Lee/squiggle/jobs/401137812"" rel=""nofollow noreferrer"">here</a>.</p>
",https://stackoverflow.com/questions/51220068/importerror-cannot-import-name-isclose,"['python', 'math', 'travis-ci', 'python-3.4', 'pytest']",1875,TRUE,3,2
How to manage spark session creation on real projects,"<p>I am new to scala/spark world. I normally run jobs on local so I use --master as local[k] but how to manage spark session/spark context for whole project in real world applications?</p>

<p>I am looking in-terms of how code structured around sparkSession object creation. For example create a trait for creating sparkSession object and use all over project and also for the unit testing, any better way to do?</p>

<p>Example code would be appreciated.</p>
",https://stackoverflow.com/questions/50889218/how-to-manage-spark-session-creation-on-real-projects,"['scala', 'apache-spark']",814,TRUE,-2,3
Path cannot contain slash,"<p>I'm trying to make unit testing in C using Python and CFFI module. It's pretty much working, but I can't use it into a sub directory.</p>

<p>While testing, my project looks like :</p>

<pre><code>$ tree tests
tests/
├── sum.c
├── sum.h
├── tests_units.py
...

$ python3 tests_unit.py

...

OK
</code></pre>

<p>But when I'm converting it for my project :</p>

<pre><code>$ tree
.
├── Makefile
├── src
│   ├── sum.c
│   └── sum.h
│   └── ...
└── tests
    └── tests_units.py
</code></pre>

<p>My <code>make check</code>run the following :</p>

<pre><code>check:
    python3 tests/tests_units.py
</code></pre>

<p>And I've so to adapt my test file :</p>

<pre><code>import unittest
import cffi
import importlib

def load(filename):
    # load source code
    source = open(filename + '.c').read()
    includes = open(filename + '.h').read()

    # pass source code to CFFI
    ffibuilder = cffi.FFI()
    ffibuilder.cdef(includes)
    ffibuilder.set_source(filename + '_', source)
    ffibuilder.compile()

    # import and return resulting module
    module = importlib.import_module(filename + '_')

    return module.lib


class SumTest(unittest.TestCase):
    def setUp(self):
        self.module = load('src/sum')

    def test_zero(self):
        self.assertEqual(self.module.sum(0), 0)

if __name__ == '__main__':
    unittest.main()
</code></pre>

<p>Pay attention to this line :</p>

<pre><code>self.module = load('src/sum')
</code></pre>

<p>So my log is</p>

<pre><code>...
Traceback (most recent call last):
File ""tests/tests_units.py"", line 28, in setUp
  self.module = load('src/sum')
File ""tests/tests_units.py"", line 17, in load
  ffibuilder.set_source(filename + '_', source)
File ""/usr/local/lib/python3.6/site-packages/cffi/api.py"", line 625, in set_source
raise ValueError(""'module_name' must not contain '/': use a dotted ""
ValueError: 'module_name' must not contain '/': use a dotted name to make a 'package.module' location
...
</code></pre>

<p>But it's not a module, it's a simple directory.</p>

<p>Can you have a solution ?</p>

<p>Regards.</p>
",https://stackoverflow.com/questions/53205758/path-cannot-contain-slash,"['python', 'c', 'unit-testing', 'testing', 'cffi']",327,FALSE,0,1
angular 5 unit tests fail when rxjs switchmap used,"<p>I am trying to test a component where an action is dispatched on store and then some data  is returned from inside this switchmap</p>

<p>this issue is with unit testing this component. if I remove switchmap the code runs fine otherwise it fails with </p>

<pre><code>undefined is not a constructor
</code></pre>

<p>here is my spec file</p>

<pre><code>    it('should dispatch xyz action oninit', async(() =&gt; {
    mockStore.select.and.returnValue(MockService.xyz);

    component.ngOnInit();
    expect(mockStore.select).toHaveBeenCalledTimes(1);
    expect(mockStore.select).toHaveBeenCalledWith(fromStore.xyz);
    expect(component.data$).toEqual(Observable.of(MockService.xyz));
}));
</code></pre>

<p>here is component oninit method</p>

<pre><code>ngOnInit(): void {
    this.data$ = this.store.select(fromStore.xyz)
        .switchMap((val) =&gt; { return Observable.of{zyz};}
}
</code></pre>

<p>if i remove this switchmap test runs fine  the error i see here is </p>

<pre><code>undefined is not a constructor (evaluating 'this.store.select(fromStore.zyz)
                .switchMap')
</code></pre>

<p>I am using phantomjs and jasmine to run my specs</p>
",https://stackoverflow.com/questions/51194962/angular-5-unit-tests-fail-when-rxjs-switchmap-used,"['angular', 'redux', 'jasmine', 'angular5', 'karma-jasmine']",1429,TRUE,0,1
Test driven development for react js,"<p>Just started learning the React js.Some of testing libraries such as chai,Sinon,Enzyme and mocha is used for unit testing. Is there any testing library is available for test driven development practices in react js. One more question how to test the page navigation in react js since the state and props will be updated once the page is submitted. Note:Through react router it would navigate to other page. how to write the test cases for integration testing.</p>
",https://stackoverflow.com/questions/50908923/test-driven-development-for-react-js,"['reactjs', 'tdd', 'integration-testing']",144,FALSE,0,1
Error: StaticInjectorError(DynamicTestModule)[NGXLogger -&gt; LoggerConfig],"<p>I have following problem.
When I unit test a project ""A"" I get 45 from 45 item green.
Now I add a component ""B"". 
When I start the unit testing now,
I get a two error <strong>on a component of project ""A""</strong>.</p>

<p>The error looks like that:</p>

<pre><code> MainNavComponent should render some nav links   Error:
      StaticInjectorError(DynamicTestModule)[NGXLogger -&gt; LoggerConfig]:   
   StaticInjectorError(Platform: core)[NGXLogger -&gt; LoggerConfig]: 
       NullInjectorError: No provider for LoggerConfig!
    Error: StaticInjectorError(DynamicTestModule)[NGXLogger -&gt; LoggerConfig]: 
      StaticInjectorError(Platform: core)[NGXLogger -&gt; LoggerConfig]:  
    NullInjectorError: No provider for LoggerConfig!
</code></pre>

<p>As I said, the ""<code>MainNavComponent</code>"" is part of project ""A"", which was without errors without the new component ""B"".</p>

<p><strong>How it could come?
How to clear this problem?</strong></p>

<p>Thanks,
Frank</p>
",https://stackoverflow.com/questions/49692275/error-staticinjectorerrordynamictestmodulengxlogger-loggerconfig,"['angular', 'unit-testing']",4297,TRUE,-1,2
"Getting EXC_BAD_ACCESS (code=2, address=0x16afa3fe0) in Reachability","<p>I am using Reachability class for network status check in my iOS application, but during the unit testing i turn of the WIFI of iPhone device and run the code but i am getting a crash in Reachability class in in 'reachabilityWithAddress' function, i am stuck here why this crash is happening i am not getting any point to solve this. My code is given below, some one please help me out this. Thank in advance.</p>

<pre><code>+ (instancetype)reachabilityWithAddress:(const struct sockaddr  *)hostAddress
 {

  SCNetworkReachabilityRef reachability =    
  SCNetworkReachabilityCreateWithAddress                                                     
  (kCFAllocatorDefault, hostAddress);

Reachability* returnValue = NULL;

if (reachability != NULL)
{
    returnValue = [[self alloc] init];
    if (returnValue != NULL)
    {
        returnValue-&gt;_reachabilityRef = reachability;
    }
    else {
        CFRelease(reachability);
    }
  }
  return returnValue;
}
</code></pre>
",https://stackoverflow.com/questions/48804443/getting-exc-bad-access-code-2-address-0x16afa3fe0-in-reachability,"['ios', 'objective-c', 'iphone', 'xcode', 'reachability']",119,FALSE,0,0
Pyqt5 with pyqtgraph building two graphs,"<p>I am trying to build an application using the PyQt5 and pyqtgraph framework. Essentially I am trying to put two graphs in a QWidget within the QMainwindow. I am unit testing right now, and I am having a hard time coding the graphs using PlotWidget, GraphicsWindow, or GraphicsObject. Essentially two identical glasses to be call in third, that will be centralized in a fourth class. This is what I have so far.</p>

<pre><code>import sys
from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QApplication)
import pyqtgraph as pg

class CustomPlot(pg.GraphicsObject):
    def __init__(self):
        pg.GraphicsObject.__init__(self)
        self.x = np.random.normal(size=1000) * 1e-5
        self.y = self.x * 500 + 0.005 * np.random.normal(size=1000)
        self.y -= self.y.min() - 1.0
        self.mask = self.x &gt; 1e-15
        self.x = self.x[self.mask]
        self.y = self.y[self.mask]
        self.plot(self.x, self.y, pen='g', symbol='o', symbolPen='g', symbolSize=1))

# a class for the second plot to be displayed underneath the first via 
# QVBoxLayout

class CustomPlot1(pg.GraphicsObject):
    def __init__(self):
        pg.GraphicsObject.__init__(self)
        self.x = np.random.normal(size=1000) * 1e-5 #
        self.y = self.x * 750 + 0.005 * np.random.normal(size=1000)
        self.y -= self.y.min() - 1.0
        self.mask = self.x &gt; 1e-15
        self.x = self.x[self.mask]
        self.y = self.y[self.mask]
        self.plot(self.x, self.y, pen='g', symbol='t', symbolPen='g', symbolSize=1)

# The top container/widget for the graphs
class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI() # call the UI set up

    # set up the UI
    def initUI(self):

        self.layout = QVBoxLayout(self) # create the layout
        self.guiplot = pg.PlotWidget() # create an instance of plotwidget 1
        self.guiplot1 = pg.PlotWidget() # create an instance of plotwidget 2
        self.pgcustom = CustomPlot() # class abstract both the classes
        self.pgcustom1 = CustomPlot1() # """" """" """"
        self.layout.addWidget(self.guiplot) # add the first plot widget to the layout
        self.guiplot.addItem(self.pgcustom) # now add the plotItem to the plot widget 
        self.layout.addWidget(self.guiplot1) # add the second plot widget to the layout


        self.guiplot1.addItem(self.pgcustom1)  # now add the plotItem to the plot widget 
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = Window()
    sys.exit(app.exec_())
</code></pre>

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

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

<p>Should I class PlotWidget instead GraphicsObject?</p>
",https://stackoverflow.com/questions/50070752/pyqt5-with-pyqtgraph-building-two-graphs,"['python', 'pyqt', 'pyqt5', 'pyqtgraph']",3068,TRUE,0,1
NoWhenBranchMatchedException with exhaustive `when` block in Kotlin,"<p>I have the following sealed class in Kotlin</p>

<pre><code>sealed class Result&lt;T, E&gt; {
    class Success&lt;T, E&gt;(val result: T) : Result&lt;T, E&gt;()
    class Failure&lt;T, E&gt;(val failure: E) : Result&lt;T, E&gt;()
}
</code></pre>

<p>and am returning an entity of Result from a <code>create()</code> function</p>

<p>and using the following with RxJava2,</p>

<pre><code>    return Single.fromCallable { repository.create(details) }
            .map {
                return@map when(result) {
                        is Result.Success -&gt; CreatedState.Success(result.result)
                        is Result.Failure -&gt; CreatedState.Error(result.failure)
                }
            }
</code></pre>

<p>The functionality seems to be working as intended as far as I can tell. However when I am unit testing this,</p>

<pre><code>    val testSubscriber = underTest.create(newDetails).test()
</code></pre>

<p>I get a <code>java.lang.IllegalStateException</code> and see a <code>kotlin.NoWhenBranchMatchedException</code> in the list of exceptions (when doing an <code>assertComplete()</code>), which I cannot understand how it would happen as my when check is exhaustive. Or am I missing something there?</p>

<p>TIA!</p>
",https://stackoverflow.com/questions/52246024/nowhenbranchmatchedexception-with-exhaustive-when-block-in-kotlin,"['android', 'kotlin', 'rx-java2']",3307,TRUE,3,2
Spring Tests Without Migrations/DBs?,"<p>I'm using Spock with Spring Test for Unit Testing controllers and services - but in order for the Unit Tests to successfully execute a connection to a DB is required. In all tests I've mocked out any required repositories - so there is no dependency on the DBs.</p>

<p>Does anyone know how to successfully execute tests without migrations and an active connection to a DB?</p>

<p>I've annotated all test classes with <code>@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)</code></p>

<p>and I'm using <code>MockMvc</code> for mocking the MVC setup:</p>

<pre><code>MockMvc mockMvc = MockMvcBuilders.standaloneSetup(controller)
                .apply(SecurityMockMvcConfigurers.springSecurity(springSecurityFilterChain))
                .setControllerAdvice(new RestResponseIssueHandler())
                .addFilter(new SessionFilter())
                .build();
</code></pre>
",https://stackoverflow.com/questions/51844250/spring-tests-without-migrations-dbs,"['java', 'spring', 'unit-testing', 'spock', 'spring-test']",42,FALSE,0,0
Grunt override init task from register task,"<p>I've grunt file with init etc, I want to create some register task which override some configuration (init etc) how it's suggested to do it ? </p>

<p>I've found the following but not sure if it's good to use it for my purpose 
<a href=""https://www.npmjs.com/package/grunt-config-merge"" rel=""nofollow noreferrer"">https://www.npmjs.com/package/grunt-config-merge</a></p>

<p>e.g. I've <strong>threshold</strong> for unit testing and I want to be able to update it via <strong>task and not manually ...</strong></p>

<p>For example I want to create task which modify the <strong>dest value</strong></p>

<pre class=""lang-js prettyprint-override""><code>    pkg: grunt.file.readJSON('package.json'),
    copy: {
        production: {
            files: [
                {
                    expand: true,
                    flatten: true,
                    src: [""test/testcontent/plugins/*""],
                    dest: ""plugins/""
                }
            ]
        }
    },
</code></pre>
",https://stackoverflow.com/questions/49976668/grunt-override-init-task-from-register-task,['gruntjs'],39,FALSE,0,0
AWS Codebuild fails while downloading source. Message: Access Denied,"<p>I created a CodeBuild Project that uses a <a href=""https://hub.docker.com/r/brooksn/aws-codebuild-nodejs-8/"" rel=""noreferrer"">docker image for node8</a>. The purpose of this CodeBuild project is to do unit testing. It takes an input artifact from CodeCommit. And in the buildspec.yml it runs a test command.</p>
<p>This is my (simple) buildspec file:</p>
<pre><code>version: 0.2

phases:
  install:
    commands:
     - echo &quot;install phase started&quot;
     - npm install
     - echo &quot;install phase ended&quot;
  pre_build: 
    commands:
     - echo &quot;pre_build aka test phase started&quot;
     - echo &quot;mocha unit test&quot;
     - npm test
     - echo &quot;mocha unit test ended&quot;
  build:
    commands:
     - echo &quot;build phase started&quot;
     - echo &quot;build complete&quot;
</code></pre>
<p>The build is failing at the DOWNLOAD_SOURCE phase with the following:</p>
<blockquote>
<p>PHASE - DOWNLOAD_SOURCE</p>
<p><strong>Start time</strong> 2 minutes ago</p>
<p><strong>End time</strong> 2 minutes ago</p>
<p><strong>Message</strong>  Access Denied</p>
</blockquote>
<p>The only logs in the build logs are the following</p>
<blockquote>
<p>[Container] 2018/01/12 11:30:22 Waiting for agent ping</p>
<p>[Container] 2018/01/12 11:30:22 Waiting for DOWNLOAD_SOURCE</p>
</blockquote>
<p>Thanks in advance.</p>
<p>Screenshot of the CodeBuild policies.</p>
<p><a href=""https://i.stack.imgur.com/i1fu6.jpg"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/i1fu6.jpg"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/48225778/aws-codebuild-fails-while-downloading-source-message-access-denied,"['node.js', 'amazon-web-services', 'amazon-elastic-beanstalk', 'aws-codepipeline', 'aws-codebuild']",26751,TRUE,19,6
How could we do unit test of a function which uses DOM?,"<p><strong><em>Hello and thank you for your time reading my question!</em></strong></p>

<p>I would like to ask, because I am starting with unit testing in Javascript, and I am using Jasmine/Karma.</p>

<p>I am trying to test a function:</p>

<pre><code>    export function setRenderer() {
    threeD = document.getElementById('container');
    renderer = new THREE.WebGLRenderer({
        antialias: true,
        alpha: true,
    });
    renderer.setSize(threeD.clientWidth, threeD.clientHeight);
    let blueColor = 0x607d8b;
    let alpha = 1;
    renderer.setClearColor(blueColor, alpha);
    threeD.appendChild(renderer.domElement);
}
</code></pre>

<p>The previous function is being loaded into the index.html:</p>

<pre><code>&lt;!DOCTYPE html&gt;
&lt;html lang=""en""&gt;

&lt;head&gt;
    &lt;meta charset=""utf-8""&gt;
    &lt;meta name=""viewport"" content=""width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0""&gt;
    &lt;title&gt;AMI - Lesson 04&lt;/title&gt;

    &lt;link rel=""stylesheet"" type=""text/css"" href=""demo.css""&gt;

    &lt;script type=""text/javascript"" src=""https://use.edgefonts.net/source-code-pro.js""&gt;&lt;/script&gt;
    &lt;script type=""text/javascript"" src=""https://cdn.rawgit.com/dataarts/dat.gui/master/build/dat.gui.min.js""&gt;&lt;/script&gt;
    &lt;script type=""text/javascript"" src=""https://cdn.rawgit.com/mrdoob/stats.js/master/build/stats.min.js""&gt;&lt;/script&gt;
    &lt;script type=""text/javascript"" src=""https://cdnjs.cloudflare.com/ajax/libs/three.js/87/three.min.js""&gt;&lt;/script&gt;

    &lt;!-- AMI --&gt;
    &lt;script type=""text/javascript"" src=""https://cdnjs.cloudflare.com/ajax/libs/ami.js/0.0.22/ami.min.js""&gt;&lt;/script&gt;
    ##
&lt;/head&gt;

&lt;body&gt;
&lt;div id=""my-gui-container""&gt;
&lt;/div&gt;
&lt;div id=""my-lut-container""&gt;
    &lt;div&gt;CT
        &lt;div id=""my-lut-canvases-l0"" class=""my-lut-canvases""&gt;&lt;/div&gt;
    &lt;/div&gt;
    &lt;div&gt;Segmentation
        &lt;div id=""my-lut-canvases-l1"" class=""my-lut-canvases""&gt;&lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;
&lt;div id=""container""&gt;&lt;/div&gt;

&lt;script src=""stats.js""&gt;&lt;/script&gt;
&lt;script src=""loader.js""&gt;&lt;/script&gt;
&lt;script src=""handleSeries.js""&gt;&lt;/script&gt;
&lt;script src=""scene.js""&gt;&lt;/script&gt;
&lt;script src=""gui.js""&gt;&lt;/script&gt;
&lt;script src=""dicomDataUrl.js""&gt;&lt;/script&gt;
&lt;script src=""controls.js""&gt;&lt;/script&gt;
&lt;script src=""camera.js""&gt;&lt;/script&gt;
&lt;script src=""renderer.js""&gt;&lt;/script&gt;
&lt;script src=""animator.js""&gt;&lt;/script&gt;
&lt;script type=""text/javascript"" src=""demo.js""&gt;&lt;/script&gt;

&lt;!-- google analytics --&gt;

&lt;/body&gt;

&lt;/html&gt;
</code></pre>

<p>Which uses a div to manipulate it creating a renderer.</p>

<p>Also, because of it could really help here I post the k<em>arma.conf.js</em>:</p>

<pre><code>const packageJSON = require('./package.json');

('use strict');

process.env.CHROME_BIN = require('puppeteer').executablePath()

module.exports = function (karma) {
    karma.set({
        // frameworks to use
        frameworks: ['jasmine', 'sinon'],

        // list of files / patterns to load in the browser
        files: [
            'https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/6.16.0/polyfill.min.js',
            `https://cdnjs.cloudflare.com/ajax/libs/three.js/${packageJSON.config.threeVersion}/three.js`,
            // ,
            // 'src/core/*.spec.js',
            //'specs/**/*.spec.js',
            'mySpecs/**/*.spec.js',
            {pattern: 'data/**/*', included: false, watched: false, served: true}
        ],

        reporters: ['spec'],

        // preprocess matching files before serving them to the browser
        // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
        preprocessors: {
            'mySpecs/**/*.spec.js': ['webpack']
            //'specs/**/*.spec.js': ['webpack']
            // 'src/core/*.spec.js': ['browserify']
        },

        browsers: ['ChromeHeadless'],

        // web server port
        // port: 9876,
        // colors: true,
        // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
        logLevel: karma.LOG_WARN,

        autoWatch: false,
        singleRun: true,
        colors: true,

        webpack: {
            module: {
                rules: [
                    {
                        test: /\.js$/,
                        loader: 'babel-loader',
                        exclude: [/node_modules/, 'external/**/*']
                    }
                ]
            }
        },
        webpackMiddleware: {
            // webpack-dev-middleware configuration
            // i. e.
            stats: 'errors-only'
        }
    });
};
</code></pre>

<p>I have tried the following:</p>

<pre><code>    /* globals describe, it, expect, beforeEach*/

import {setRenderer} from '../../lessons/04/renderer'

describe('Configuration', () =&gt; {
    it('should true be true', () =&gt; {
        expect(true).toBe(true);
    });
});
describe('Renderer', () =&gt; {
    it('should be created', () =&gt; {
        var newDiv = document.createElement(""div"");
        newDiv.id = 'container';
        document.body.appendChild(newDiv);

        setRenderer();

        expect(document.getElementById('container').toBe(newDiv);
    });
});
</code></pre>

<p>The first test is because of I am checking if Karma and Jasmine are well configured, and they are, because it passes.</p>

<p>The point is that the tests output:</p>

<pre><code> Configuration
    V should true be true

  Renderer
    × should be created
        ReferenceError: threeD is not defined
            at setRenderer (mySpecs/lesson04/test.spec.js:101:12)
            at UserContext.&lt;anonymous&gt; (mySpecs/lesson04/test.spec.js:88:90)


    HeadlessChrome 0.0.0 (Windows 8.1 0.0.0): Executed 2 of 2 (1 FAILED) (0.033 secs / 0.011 secs)
    TOTAL: 1 FAILED, 1 SUCCESS


    1) should be created
         Renderer
         ReferenceError: threeD is not defined
        at setRenderer (mySpecs/lesson04/test.spec.js:101:12)
        at UserContext.&lt;anonymous&gt; (mySpecs/lesson04/test.spec.js:88:90)


    error Command failed with exit code 1.
    info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
</code></pre>

<p>I thought it was because of the expectation was failing, however it looks like <strong>the cause is different</strong>, because of if I change the expectation for a trivial true.toBe.false, the output is:</p>

<pre><code>    HeadlessChrome 0.0.0 (Windows 8.1 0.0.0): Executed 2 of 2 (1 FAILED) (0.034 secs / 0.013 secs)
TOTAL: 1 FAILED, 1 SUCCESS


1) should be created
     Renderer
     ReferenceError: threeD is not defined
    at setRenderer (mySpecs/lesson04/test.spec.js:101:12)
    at UserContext.&lt;anonymous&gt; (mySpecs/lesson04/test.spec.js:88:90)


error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
</code></pre>

<p><em>I am trying to learn how to do unit testing because I think is a good way to programm, however I do not know how to continue with this example.</em></p>

<p>Here is the test in the repo: <a href=""https://github.com/AtlasULPGC/AtlasULPGC.github.io/blob/master/mySpecs/lesson04/test.spec.js"" rel=""nofollow noreferrer"">https://github.com/AtlasULPGC/AtlasULPGC.github.io/blob/master/mySpecs/lesson04/test.spec.js</a></p>

<p>Renderer function:
<a href=""https://github.com/AtlasULPGC/AtlasULPGC.github.io/blob/master/lessons/04/renderer.js"" rel=""nofollow noreferrer"">https://github.com/AtlasULPGC/AtlasULPGC.github.io/blob/master/lessons/04/renderer.js</a></p>

<p>The index.html
<a href=""https://github.com/AtlasULPGC/AtlasULPGC.github.io/blob/master/lessons/04/index.html"" rel=""nofollow noreferrer"">https://github.com/AtlasULPGC/AtlasULPGC.github.io/blob/master/lessons/04/index.html</a></p>

<p>Thank you for taking time reading the question!</p>
",https://stackoverflow.com/questions/48383052/how-could-we-do-unit-test-of-a-function-which-uses-dom,"['javascript', 'unit-testing']",286,FALSE,3,0
Ability to set up multiple spies on the same method,"<p>We are trying to do unit testing with Jasmine to isolate a method or component that we need to test and see how it behaves under a variety of circumstances.</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>return Promise.resolve(referenceObject()) //afraid this might execute out of order so force it inside promise chain.
           .then(() =&gt; this._apiClient.postRequest('putquestions', requestParametersPutSamples, questionInfo))
           .then(() =&gt; this._apiClient.postRequest('putitems', requestParametersPutNewSamples, { item: itemInfo }))
           .then((res: Array&lt;any&gt;) =&gt; this.expectEachResponseToBeOk(res));
   }
   
   </code></pre>
</div>
</div>
</p>

<p>We are using spyOn for the existing methods as shown in the code above.
We have forced it inside a promise chain because this might execute out of order.</p>

<p>Any ideas on how can we spyOn on the same method which has been called twice but with different parameters?</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/49253678/ability-to-set-up-multiple-spies-on-the-same-method,"['javascript', 'unit-testing', 'promise', 'jasmine', 'spyon']",112,FALSE,2,0
Angular Jasmine testing - onLangChange callback not executed,"<p>I've just started writing unit tests for my Angular project, and I'm experiencing some problems with testing if the language is set.</p>

<p>This is the code of my app.component.ts:</p>

<pre><code>ngOnInit() {
    this.translateService.setDefaultLang('en');

    this.translateService.onLangChange.subscribe((langChangeEvent: LangChangeEvent) =&gt; {
        this.localStorageService.setItem(LocalStorageService.languageKey, langChangeEvent.lang);
    });
    this.translateService.use('en');  &lt;---- The subscribe callback should be called
}
</code></pre>

<p>This is the code of my app.component.spec.ts:</p>

<pre><code>  describe('ngOnInit', () =&gt; {
    it('should set default language as en', () =&gt; {
      const translateService = fixture.debugElement.injector.get(TranslateService);
      spyOn(translateService, 'setDefaultLang');
      component.ngOnInit();
      expect(translateService.setDefaultLang).toHaveBeenCalledWith('en');
  }); &lt;----- This part of test is successful



    it('should set new lang key to localStorageService on TranslateService.onLangChange observable emit', () =&gt; {
      const localStorageService = fixture.debugElement.injector.get(LocalStorageService);
      spyOn(localStorageService, 'setItem');
      component.ngOnInit();
      translateService.use('de');
      expect(localStorageService.setItem).toHaveBeenCalledWith(LocalStorageService.languageKey, 'de');
  });&lt;-------------This test throws error (see below)

}); 
</code></pre>

<p>I am getting this error:</p>

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

<p>I tested in the app that the subscribe callback gets executed, however the test says it doesn't. Am I totally misunderstanding the whole unit testing concept here? What am I doing wrong?</p>

<p><strong>EDIT:</strong></p>

<p>As requested by dmcgrandle - posting the full app.component.spec.ts:</p>

<pre><code>import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
import {TranslateModule ,TranslateService, LangChangeEvent} from ""@ngx-translate/core"";
import {LocalStorageService} from ""./core/local-storage.service"";
import {OAuthService, UrlHelperService} from ""angular-oauth2-oidc"";
import {HttpClientModule} from ""@angular/common/http"";
import {ConfigurationService} from ""./core/configuration.service"";
import {MockConfigurationService} from './testing/mock-services/configuration.service.mock';
import { of } from 'rxjs/observable/of';
import * as fastClick from 'fastclick';

describe('AppComponent', () =&gt; {
  const mockFastClick = jasmine.createSpyObj('fastClick', ['attach']);
  let component : AppComponent;
  let fixture;
  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
      imports: [
        RouterTestingModule.withRoutes([]),
        TranslateModule.forRoot(),
        HttpClientModule

      ],
      providers:[
        TranslateService,
        LocalStorageService,
        OAuthService,
        UrlHelperService,
        { provide: fastClick, useValue: mockFastClick },
        { provide: ConfigurationService, useValue: MockConfigurationService }
      ]
    }).compileComponents();
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.debugElement.componentInstance;
  });

  it('should create the app', () =&gt; {
    expect(component).toBeTruthy();
  });

  describe('ngOnInit', () =&gt; {
    it('should call fastClick.attach', () =&gt; {
        spyOn(fastClick, 'attach');
        component.ngOnInit();
        expect(fastClick.attach).toHaveBeenCalledWith(document.body, null);
    });
    it('should have loaded config', () =&gt; {
      fixture.detectChanges();
      const appConfig = fixture.debugElement.injector.get(ConfigurationService);
      expect(component.appConfig).toEqual(appConfig.config);
    });
    it('should set default language as en', () =&gt; {
      const translateService = fixture.debugElement.injector.get(TranslateService);
      spyOn(translateService, 'setDefaultLang');
      component.ngOnInit();
      expect(translateService.setDefaultLang).toHaveBeenCalledWith('en');
  });
   it('should set new lang key to localStorageService on TranslateService.onLangChange observable emit', () =&gt; {
      const localStorageService = fixture.debugElement.injector.get(LocalStorageService);
      spyOn(localStorageService, 'setItem');
      component.ngOnInit();
      expect(localStorageService.setItem).toHaveBeenCalledWith(LocalStorageService.languageKey, 'de');
  });

});

});
</code></pre>
",https://stackoverflow.com/questions/53855094/angular-jasmine-testing-onlangchange-callback-not-executed,"['angular', 'jasmine', 'rxjs', 'karma-jasmine']",2809,TRUE,2,1
xUnit: how to Assert other event of types then EventHandler&lt;EventArgs&gt;,"<p>I'm a beginner in unit testing and I've been searching the net for couple of hours now and I still can't find the answer to my simple question.</p>

<p>I have a class with the following event:</p>

<pre><code>event Action&lt;ITagData&gt; OnTagHandled
</code></pre>

<p>Now I want to write a unit test to assert if the event has been raised but when I write something like:</p>

<pre><code>Assert.Raises&lt;EventArgs&gt;(handler =&gt; m_rssiHander.OnTagHandled += handler,
    handler =&gt; m_rssiHander.OnTagHandled -= handler, () =&gt; { });
</code></pre>

<p>I get an error like: </p>

<blockquote>
  <p>Cannot implicitly convert type System.EventHandler to System.Action</p>
</blockquote>

<p>Can someone tell me how I can assert an event of type <code>Action&lt;T&gt;</code>?</p>
",https://stackoverflow.com/questions/52956862/xunit-how-to-assert-other-event-of-types-then-eventhandlereventargs,"['c#', 'unit-testing', 'xunit']",1536,TRUE,2,2
"Cloud Functions v1, wildcards not working in functions.firestore.onCreate, empty context.params","<p>I updated Firebase Cloud Functions to v1.0.1 and decided to give it a go using the new Unit Testing features.</p>

<p>There is one issue for which I could not find a solution:</p>

<pre><code>exports.updateBestTime = functions.firestore
   .document(""users/{userId}/exercises/{exercise}/times/{timeId}"")
   .onCreate((snap, context) =&gt; {

       console.log(context) 

       ...
</code></pre>

<p>When this function gets called, <code>snap</code> is correct, <code>snap.ref</code> point to the document I passed. <code>context.params</code> which should contain the wildcards value for <code>userId</code>, <code>exercise</code> and <code>timeId</code>, is empty. 
This is the output from <code>console.log(context)</code>:</p>

<pre><code>   { service: 'firestore.googleapis.com',
     name: 'projects/focos-debug/databases/(default)/documents/users/userId5/exercises/exercise4/times/timeId6' },
     eventType: 'providers/cloud.firestore/eventTypes/document.create',
     timestamp: '2018-04-07T09:17:42.500Z',
     params: {} }
</code></pre>

<p>I don't have much experience with JavaScript so it's probably my fault. Could you help me?</p>

<p>Here's the code I use for testing:</p>

<pre><code>const handstandTimePath = 'users/OLlJ3NFcgYXqS8T5vetYVKjzFbo1/exercises/handstand/times/test';

const snap = test.firestore.makeDocumentSnapshot(
    {time: 30},
    handstandTimePath
);

// Call the wrapped function with the constructed snapshot.
const wrapped = test.wrap(myFunctions.updateBestTime);
return wrapped(snap).then(function() {
    return firestore.doc(handstandTimePath).get();
}).then(function(createdSnap) {
    assert.property(createdSnap.data(), 'dateAndTime');
    assert.property(createdSnap.data(), 'time');
    assert.include(createdSnap.data(), {time: 30});
})
</code></pre>
",https://stackoverflow.com/questions/49705909/cloud-functions-v1-wildcards-not-working-in-functions-firestore-oncreate-empty,"['javascript', 'firebase', 'google-cloud-firestore', 'google-cloud-functions']",500,TRUE,2,1
Phantom js doesn&#39;t support Arrow function ( =&gt; ),"<p>I am working on unit testing of Angular app using Jasmine.
Everything was working fine on the Chrome until i started using PhantomJs for the headless browser testing or test output on the console.</p>

<p>After 2 days, I found that PhantomJs doesn't support lambda expression.
There isn't any problem with the unit tests but it was with lambda expression and PhantomJs.</p>

<p>I am using -</p>

<ol>
<li><p>AngularJs - 1.6.6</p></li>
<li><p>Jasmine - 2.9.1</p></li>
<li><p>PhantomJs - 2.1.1</p></li>
</ol>

<p>Can anyone help me with this?</p>

<p>Thank you in advance.</p>
",https://stackoverflow.com/questions/48580544/phantom-js-doesnt-support-arrow-function,"['javascript', 'angularjs', 'lambda', 'jasmine', 'phantomjs']",1073,TRUE,2,3
angular 7: how to unit test retries on an http interceptor,"<p>I've got an HTTP interceptor that is used for adding headers (authentication) and for performing logging when an error happens. Currently, it uses a custom retry strategy which will try to call the web service 3 times before generating an error. Here's the code that is used in the intercept method:</p>

<pre><code>intercept(req: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {
    const headers = this.obtemHeaders();
    const requestClonado = req.clone({ headers });
    return next.handle(requestClonado).pipe(
                    retryWhen(this.retryStrategy()),
                    catchError(err =&gt; {
                        console.error(err);
                        let msgErro: string;
                        if(err instanceof HttpErrorResponse &amp;&amp; this._servicoAutenticacao.trataErroFimSessao(err)) {
                            msgErro = ""A sua sessão terminou. Vai ser redirecionado para a página de login"" ;
                        }
                        else if(err.status === 503 ) {
                            msgErro = ""O servidor não devolveu uma resposta válida (503)."";
                        }
                        else {
                            msgErro = err.error &amp;&amp; err.error.message ? err.error.message : ""Ocorreu um erro no servidor."";
                        }
                        if(err.status !== 503) {
                            this._logger.adicionaInfoExcecao(msgErro).subscribe();
                        }
                        return throwError(msgErro);
                    }
                ));
}
</code></pre>

<p>What's the best approach for unit testing the retry attempts? I've tried writing something like this:</p>

<pre><code>it(""deve efetuar retry e chamar logging antes redirecionar"", fakeAsync((done) =&gt; {
    httpClient.get(""/error"").subscribe( _ =&gt; {},
        err =&gt; {
            expect(err).toBeTruthy();
            done();
            } );
    const request = httpMock.expectOne(""/error"");
    request.error(new ErrorEvent(errorMsg));
    tick(500);
    tick(500);
    tick(500);

    expect(trataFimSessaoSpy).toHaveBeenCalled();
    expect(trataLogging).toHaveBeenCalledWith({msg: errorMsg});
});
</code></pre>

<p>Unfortunately, it doesn't work. Can anyone help and point me in the right direction?</p>

<p>thanks</p>
",https://stackoverflow.com/questions/53154539/angular-7-how-to-unit-test-retries-on-an-http-interceptor,"['angular', 'unit-testing', 'rxjs', 'angular-httpclient', 'retrywhen']",1048,TRUE,1,1
modify private data members using spyon.and.callFake in Jasmine,"<p>I have a public method A() in service which modifies a private data member of that service. </p>

<pre><code>A() {
  //call http
  // change private data member using call's result
}
</code></pre>

<p>I am unit testing a component that uses this service and thus want to  change the data member by using spyOn.and.callFake() functionality of Jasmine. However, as the data member is private, I can't access it in the component using the service object. I don't want to make the data member public for the purpose of a test.</p>

<p>What should be the best practice here?</p>
",https://stackoverflow.com/questions/51313762/modify-private-data-members-using-spyon-and-callfake-in-jasmine,"['angular', 'unit-testing', 'jasmine', 'spy']",759,TRUE,1,1
Spring Boot application - build process with Angular does not update Angular part,"<p>My Spring Boot application contains a Java part and an Angular part. The Angular part (with an index.html,etc) is generated into the folder src/main/resources/static. Works fine. I noticed that when building the final JAR often (?) the static part is lost. </p>

<p>How come? What can I do to get the static / HTML part into the final Spring Boot JAR? </p>

<p>My &lt;build&gt; part of the pom.xml is shown below. All not-interesting parts (like unit testing, etc) is removed. </p>

<pre><code>&lt;build&gt;
    ... 
    &lt;plugin&gt;
    &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt;
    &lt;artifactId&gt;exec-maven-plugin&lt;/artifactId&gt;
    &lt;version&gt;1.6.0&lt;/version&gt;
    &lt;executions&gt;
      &lt;execution&gt;
        &lt;id&gt;npm install&lt;/id&gt;
        &lt;goals&gt;
          &lt;goal&gt;exec&lt;/goal&gt;
        &lt;/goals&gt;
        &lt;phase&gt;initialize&lt;/phase&gt;
        &lt;configuration&gt;
          &lt;executable&gt;npm&lt;/executable&gt;
          &lt;arguments&gt;
            &lt;argument&gt;install&lt;/argument&gt;
          &lt;/arguments&gt;
        &lt;/configuration&gt;
      &lt;/execution&gt;
      &lt;execution&gt;
        &lt;id&gt;build Angular production code&lt;/id&gt;
        &lt;goals&gt;
          &lt;goal&gt;exec&lt;/goal&gt;
        &lt;/goals&gt;
        &lt;phase&gt;compile&lt;/phase&gt;
        &lt;configuration&gt;
          &lt;executable&gt;npm&lt;/executable&gt;
          &lt;arguments&gt;
            &lt;argument&gt;run&lt;/argument&gt;
            &lt;argument&gt;build&lt;/argument&gt;
            &lt;argument&gt;--prod&lt;/argument&gt;
          &lt;/arguments&gt;
        &lt;/configuration&gt;
      &lt;/execution&gt;
    &lt;/executions&gt;
  &lt;/plugin&gt;
  ...
&lt;/build&gt;
</code></pre>
",https://stackoverflow.com/questions/53731955/spring-boot-application-build-process-with-angular-does-not-update-angular-par,"['maven', 'spring-boot']",1244,TRUE,1,2
How to use Dependency Injection in case of no start up class C#?,"<p>I have the child-parent class relationship but I <strong>don’t have any startup class</strong> to resolve the dependency explicitly. In addition, I <strong>don't want to remove empty constructor</strong> from child class as it has a dependency. How and Where can I configure my containers to achieve dependency injection implementation?</p>

<p>Currently, I am achieving it using below logic for unit testing mocking purpose.</p>

<p>Is it possible to dynamically resolve dependency using MEF C# or through base lass. Any help appreciated.</p>

<p>e.g.</p>

<pre><code> public class child : Parent
 {
       private ILogger _logger;
       public child() : this(new FileLogger()) { }

       public child(ILogger logger)
       {
            _logger = logger;
       }

       public void DoWork()
       {
             //Perform Work.
             _logger.Log(""Log Work Here"");
       }
 }

public abstract class Parent
{
        //Common Operations
}

public interface ILogger
{
        void Log(string message);
}

//Multiple Inplementation for ILogger
public class FileLogger : ILogger
{
      public void Log(string message)
      {
            //Log into file.
      }
}
</code></pre>
",https://stackoverflow.com/questions/49622534/how-to-use-dependency-injection-in-case-of-no-start-up-class-c,"['c#', 'dependency-injection', 'mef', 'dependency-management']",708,FALSE,1,0
Laravel faking file in the factory not working,"<p>I am developing a Web application using Laravel. I am unit testing my application that involves file operation. Have a look at my scenario below.</p>

<p>I have a download file action in the controller like this</p>

<pre><code>public function downloadPersonalDetails(Order $order)
{
    if (! auth()-&gt;user()-&gt;can('downloadPersonalDetails', $order)) {
        abort(401);
    }

    return Storage::download($order-&gt;path);
}
</code></pre>

<p>I have the factory like this OrderFactory.php</p>

<pre><code>$factory-&gt;define(Application::class, function (Faker $faker) {
    return [
        'first_name' =&gt; $faker-&gt;firstName,
        'last_name' =&gt; $faker-&gt;lastName,
        'email' =&gt; $faker-&gt;email,
        //other fields ....
        'path' =&gt; $faker-&gt;file('public/assets/files'),
});
</code></pre>

<p>This is my unit test to that download action</p>

<pre><code>public function test_download_personal_details_file()
    {
        $user = //created a authorized valid user

        $order = factory(Order::class)
            -&gt;create([
               'user' =&gt; $user-&gt;id
            ]);


        $this-&gt;actingAs($user)-&gt;get(route('order.personal_info.download', $order))-&gt;assertStatus(200);
    }
</code></pre>

<p>When I run the test I am getting error saying file does not exist.</p>

<pre><code>File not found at path: tmp/439fe03f-f1c7-3b84-b123-d627d0395bd8.pdf
</code></pre>

<p>Why is that not working? How can I fix it and what is wrong with my code.</p>
",https://stackoverflow.com/questions/52928710/laravel-faking-file-in-the-factory-not-working,"['laravel', 'file', 'unit-testing', 'faker', 'laravel-testing']",6058,TRUE,1,1
How does one write an automated integration test?,"<p>I read a lot about unit testing and integration testing, and the unit testing part I understand fairly well - isolate the object under test, and mock out dependencies using interfaces and inject those. (Or use seams to inject testable behavior). </p>

<p>However something that is still a mystery to me even after searching is integration testing. Every blog and link talks about testing various components together, do's and dont's, CI Servers, etc, but there's not much explanation in the way of how this is to be done. </p>

<p>Is an integration test automated? Or is this a manual effort? If it is automated, do I write this as code in the native language my app is in? How do I check or verify if the integration test is working as expected?</p>

<p>For example, if I have 4 services (a Socket Client, a Socket Server, a Database, and a Web Application) and I want to do some integration testing on how these 4 services interact with each other. How exactly how would I approach this? I know that some dummy data will be involved, but which part of my integration test is checking if the systems are working together correctly? This part is really unclear to me.</p>
",https://stackoverflow.com/questions/48176991/how-does-one-write-an-automated-integration-test,"['unit-testing', 'integration-testing']",1308,TRUE,2,1
Jest - ReferenceError: define is not defined,"<p>I'm trying to use jest to start doing some unit testing but I've come across this error that a lot of people seem to be getting but I can't seem to figure it out.</p>

<p>Here's is what I'm trying to do (and I realize requirejs isn't supported):</p>

<pre><code>jest.mock(""../widgets/"", () =&gt; {
  return &lt;button&gt;button&lt;/button&gt;;
});

describe('TextInput', () =&gt; {
  describe('when user inputs a value', () =&gt; {
    it('calls correct function to handle change', () =&gt; {
      const handleChange = jest.fn();
      const value = ""test""
      const wrapper = shallow(&lt;TextInput handleChange={handleChange} /&gt;);
      const textInputElement = wrapper.find(""#textfield"");
      textInputElement.simulate('change', {target: { value }})

      expect(handleChange).toHaveBeenCalledTimes(1);
    });
  });
});

import React from ""react"";
import ReactDOM from ""react-dom"";
import * as TestUtils from ""react-dom/test-utils"";
import { TextInput } from ""../widgets/"";
</code></pre>

<p>and here is my <code>package.json</code></p>

<pre><code>""jest"": {
    ""collectCoverageFrom"": [
      ""src/**/*.js""
    ],
    ""setupFiles"": [

    ],
    ""testMatch"": [
      ""**/src/**/?(*.)+(test).js""
    ],
    ""testEnvironment"": ""node"",
    ""testURL"": ""http://localhost"",
    ""transform"": {
      ""^.+\\.(js)$"": ""./node_modules/babel-jest"",
      ""^.+\\.css$"": ""./config/jest/cssTransform.js"",
      ""^(?!.*\\.(js|jsx|mjs|css|json)$)"": ""./config/jest/fileTransform.js""
    },
    ""transformIgnorePatterns"": [
      ""[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs)$""
    ],
    ""moduleNameMapper"": {
      ""^react-native$"": ""react-native-web""
    },
    ""moduleFileExtensions"": [
      ""web.js"",
      ""js"",
      ""json"",
      ""web.jsx"",
      ""jsx"",
      ""node"",
      ""mjs""
    ]
 }
</code></pre>

<p>Upon running jest, I get the error <code>ReferenceError: define is not defined</code> and here is a more detailed error:
<a href=""https://i.stack.imgur.com/zwUZu.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/zwUZu.png"" alt=""errorMsg""></a></p>

<p>I would appreciate any help! Been pulling my hair out over this for the past few days :-(</p>
",https://stackoverflow.com/questions/53017146/jest-referenceerror-define-is-not-defined,"['javascript', 'reactjs', 'jestjs']",3164,TRUE,1,1
Stubbing in Sinon,"<p>I am very new to unit testing. That goes to writing modular testable code as well.</p>

<p>I am struggling to implement a stub to mimic whats happened in page.evaluate(). The page object is injected from an outer function using the ‘puppeteer’ library. </p>

<p>Been reading up on sinonjs for this.. But i havent been able to wrap my head around this.</p>

<pre><code>async function cinemasfromState(page, state) {
  const CINEMA_STATE_SELECTOR = `div.top-select div.slider span.state[data-state-selector=$[STATE]]`;
  const CINEMA_SELECTOR = `div[data-state=$[STATE]] div.top-select-option a.eccheckbox`;

  await page.click(CINEMA_STATE_SELECTOR.replace(""$[STATE]"", state));

  let res = await page.evaluate(
    (elementPath, state) =&gt; {
      return Array.from(document.querySelectorAll(elementPath))
        .map(
          function(cin, index) {
            let result = {
              cinemaState: this.state,
              cinemaId: cin.getAttribute(""data-id""),
              cinemaName: cin.getAttribute(""data-name""),
              cinemaURL: cin.getAttribute(""data-url"")
            };
            return result;
          },
          { state }
        )
        .reduce((acc, cur) =&gt; Object.assign(acc, { [cur.cinemaId]: cur }), {});//filter dupes

    },
    CINEMA_SELECTOR.replace(""$[STATE]"", state),
    state
  );

  return res;
}
</code></pre>

<p>Wondering if you could help/point in the right direction. Also any comments on testability of this code is appreciated</p>
",https://stackoverflow.com/questions/53232208/stubbing-in-sinon,"['javascript', 'unit-testing', 'sinon', 'stub']",114,FALSE,1,0
How do I validate the DI container in ASP.NET Core?,"<p>In my <code>Startup</code> class I use the <code>ConfigureServices(IServiceCollection services)</code> method to set up my service container, using the built-in DI container from <code>Microsoft.Extensions.DependencyInjection</code>.</p>

<p>I want to validate the dependency graph in an unit test to check that all of the services can be constructed, so that I can fix any services missing during unit testing instead of having the app crash at runtime. In previous projects I've used Simple Injector, which has a <code>.Verify()</code> method for the container. But I haven't been able to find anything similar for ASP.NET Core.</p>

<p><strong>Is there any built-in (or at least recommended) way of verifying that the entire dependency graph can be constructed?</strong></p>

<p>(The dumbest way I can think of is something like this, but it will still fail because of the open generics that are injected by the framework itself):</p>

<pre><code>startup.ConfigureServices(serviceCollection);
var provider = serviceCollection.BuildServiceProvider();
foreach (var serviceDescriptor in serviceCollection)
{
    provider.GetService(serviceDescriptor.ServiceType);
}
</code></pre>
",https://stackoverflow.com/questions/49149065/how-do-i-validate-the-di-container-in-asp-net-core,"['c#', 'asp.net-core', 'dependency-injection']",11987,TRUE,33,4
JUnit testing returning primitive types,"<p>I am working on unit testing with JUnit. For this particular test case we check if our basket or list is empty then we should return a price of <code>0.0</code>. If the calculatePrice method of the checkout is passed an empty Basket, it should return a price, as a double of <code>0.0</code>.
Im just not sure how to go about this. I'm more or less trying to ensure that the price is <code>0.0</code> when you check the basket but I feel totally off on something.</p>
<pre class=""lang-java prettyprint-override""><code>public class Basket {
    
    private List&lt;Object&gt; bookList = new ArrayList&lt;Object&gt;();
    
    public List&lt;Object&gt; getBooksInBasket() {
        return bookList;
    }

}
</code></pre>
<pre class=""lang-java prettyprint-override""><code>public class CheckOut {
    
    private double price = 0.0;
    
    public double getCheckOutPrice() {
        return price;
    }

    double calculatePrice(Basket basket) {
        Basket basket1 = new Basket();
        if(((List&lt;Object&gt;) basket1).size()==0)
            return basket.price1=0.0;
        return price;
        
        //return null;
    }
}
</code></pre>
<pre class=""lang-java prettyprint-override""><code>public class CheckOutTest {

    @Test
    public void test_CalculatePrice_ReturnsDoubleZeroPointZeroWhenPassedAnEmptyBasket() {
        //Arrange
        Basket basket = new Basket();
        CheckOut checkout = new CheckOut();
        
        //Act       
        checkout.calculatePrice(basket);
        
        //Assert
        
        //assertEquals(0.0,checkout.price);
    }
}
</code></pre>
",https://stackoverflow.com/questions/51490362/junit-testing-returning-primitive-types,"['java', 'list', 'junit', 'double', 'tdd']",864,TRUE,1,1
Mokito with akka actors,"<p>I am using the akka framework with its Java API and mockito + Testkit for unit testing the actor</p>

<p>Here is the actor</p>

<pre><code>public class K8sDeploymentCreator extends AbstractActor {
  private final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this);


  @Override
  public Receive createReceive() {
    return receiveBuilder().match(createK8sDeployment.class, msg -&gt; {
      KubeNamespace kubenamespace = new KubeNamespace();
      KubeDeployment kubeDeployment = new KubeDeployment();
      Namespace namespace = kubenamespace.createNamespace(msg.kubeClient, msg.service);
      Deployment deployment = kubeDeployment.createDeployment(msg.service, msg.kubeClient, namespace);
      log.info(""sending complete depl msg"");

      getSender().tell(new K8sDeploymentComplete(deployment), getSelf());
    })
        .matchAny(o -&gt; log.info(""received unknown message"")).build();
  }

}
</code></pre>

<p>And here is the test class</p>

<pre><code>public class K8sDeploymentCreatorTest extends JUnitSuite {

  static ActorSystem system;


  @Before
  public  void setup() {
    system = ActorSystem.create();
    KubeDeployment mockKubeDeployment = mock(KubeDeployment.class);
    KubeNamespace mockKubeNamespace = mock(KubeNamespace.class);
    Deployment deployment = Mockito.mock(Deployment.class);
    Namespace namespace = Mockito.mock(Namespace.class);
    KubernetesClient kubeClient = Mockito.mock(KubernetesClient.class);
    Service serviceTodeploy = new Service(""group"",""artifact"",""version"");
    DeployEnvironment deployEnvironment = new DeployEnvironment();
    deployEnvironment.setName(""K8sDeploymentCreatorTest"");
    serviceTodeploy.setDeployEnvironment(deployEnvironment);
    when(mockKubeNamespace.createNamespace(kubeClient, serviceTodeploy)).thenReturn(namespace);
    when(mockKubeDeployment.createDeployment(serviceTodeploy, kubeClient, namespace)).thenReturn(deployment);

  }


  @AfterClass
  public static void teardown() {
    TestKit.shutdownActorSystem(system);
    system = null;
  }

  @Test
  public void testK8sDeployment() {

    new TestKit(system) {
      {
        final Props props = Props.create(K8sDeploymentCreator.class);
        final ActorRef underTest = system.actorOf(props);
        KubeDeployment mockKubeDeployment = mock(KubeDeployment.class);
        KubeNamespace mockKubeNamespace = mock(KubeNamespace.class);
        Deployment deployment = Mockito.mock(Deployment.class);
        Namespace namespace = Mockito.mock(Namespace.class);
        KubernetesClient kubeClient = Mockito.mock(KubernetesClient.class);
        DeployEnvironment deployEnvironment = new DeployEnvironment();
        deployEnvironment.setName(""K8sDeploymentCreatorTest"");
        Service serviceTodeploy = new Service(""group"",""artifact"",""version"");
        serviceTodeploy.setDeployEnvironment(deployEnvironment);

        createK8sDeployment msg = new createK8sDeployment(serviceTodeploy, kubeClient);
        underTest.tell(msg, getRef());
expectMsg(K8sDeploymentComplete)

      }
    };
  }

}
</code></pre>

<p>This fails with a NPE (NullPointerException) trying to execute code inside createNamespace(). This method has been mocked, should it skip the excution and just return whatever the when statement says it should return?</p>

<p>Is this because I am instantiating a new objec of KubeNamspace and also KubeDeployment where as the contact is for mocks?</p>
",https://stackoverflow.com/questions/49497065/mokito-with-akka-actors,"['java', 'mocking', 'mockito', 'akka']",524,TRUE,0,1
React Native + Jest + Enzyme: Why does Enzyme not recognize some components?,"<p>I'm currently learning unit testing with Enzyme.</p>

<p>There seems to be a weird behavior: Enzyme seemingly randomly does not recognize certain components. Let me give you the examples:</p>

<p>Here is my <code>SafeContainer</code> component:</p>

<pre><code>import React from ""react"";
import { SafeAreaView } from ""react-native"";
import { PropTypes } from ""prop-types"";

import styles from ""./styles"";

const SafeContainer = ({ children }) =&gt; {
  return &lt;SafeAreaView style={styles.container}&gt;{children}&lt;/SafeAreaView&gt;;
};

SafeContainer.propTypes = {
  children: PropTypes.any
};

export default SafeContainer;
</code></pre>

<p>And here is my <code>AuthInput</code> component:</p>

<pre><code>import React, { PureComponent } from ""react"";
import { Text, TextInput, View } from ""react-native"";
import PropTypes from ""prop-types"";

import colors from ""../../config/constants/themes"";
import styles from ""./styles"";

class AuthInput extends PureComponent {
  handleChange = value =&gt; {
    const { onChange, name } = this.props;
    onChange(name, value);
  };

  handleTouch = () =&gt; {
    const { onTouch, name } = this.props;
    onTouch(name);
  };

  render() {
    const { placeholder, error } = this.props;
    return (
      &lt;View&gt;
        &lt;TextInput
          autoCapitalize=""none""
          autoCorrect={false}
          style={[styles.input, error ? styles.errorInput : null]}
          placeholder={placeholder}
          placeholderTextColor={colors.$lightGrey}
          onChangeText={this.handleChange}
          underlineColorAndroid=""transparent""
          onBlur={this.handleTouch}
          {...this.props}
        /&gt;
        {error &amp;&amp; &lt;Text style={styles.errorText}&gt;{error}&lt;/Text&gt;}
      &lt;/View&gt;
    );
  }
}

AuthInput.propTypes = {
  placeholder: PropTypes.string,
  name: PropTypes.string,
  error: PropTypes.string,
  onChange: PropTypes.func,
  onTouch: PropTypes.func
};

export default AuthInput;
</code></pre>

<p>Now here is how I test that the <code>SafeContainer</code> uses the SafeAreaView:</p>

<pre><code>import React from ""react"";
import { shallow } from ""enzyme"";
import SafeContainer from ""./SafeContainer"";

describe(""SafeContainer"", () =&gt; {
  describe(""rendering"", () =&gt; {
    let wrapper;
    beforeEach(() =&gt; {
      wrapper = shallow(&lt;SafeContainer /&gt;);
    });

    it(""should render a &lt;SafeAreaView /&gt;"", () =&gt; {
      expect(wrapper.find(""SafeAreaView"")).toHaveLength(1);
    });
  });
});
</code></pre>

<p>I tried do use the same thing to test that the <code>AuthInput</code> wraps it's inner component inside a <code>&lt;View /&gt;</code>:</p>

<pre><code>describe(""AuthInput"", () =&gt; {
  describe(""rendering"", () =&gt; {
    let wrapper;
    beforeEach(() =&gt; {
      wrapper = shallow(&lt;AuthInput /&gt;);
    });

    it(""should render a &lt;View /&gt;"", () =&gt; {
      expect(wrapper.find(""View"")).toHaveLength(1);
    });
  });
});
</code></pre>

<p>But somehow this test fails. If I use the same structure to test for the <code>&lt;TextInput ... /&gt;</code> it works. </p>

<p>What am I missing?</p>
",https://stackoverflow.com/questions/51234671/react-native-jest-enzyme-why-does-enzyme-not-recognize-some-components,"['reactjs', 'unit-testing', 'react-native', 'jestjs', 'enzyme']",822,TRUE,3,1
Jestjs - database connection created in beforeEach block becomes undefined in test block,"<p>I have setup my project so that once a database connection is made an event is emitted. The app starts after this.</p>

<p>When unit testing I setup a local variable, create the database connection inside <code>beforeEach</code> and save the connection to the local variable.</p>

<p>Within this <code>beforeEach</code> block I can see that the database is connected. However, if I check inside a <code>test</code> block the local variable returns <code>undefined</code>. What is the correct approach for this?</p>

<pre><code>- db.config.ts -
export async function connectToDatabase(mediator: EventEmitter) {
  const connectionOptions = await getConnectionOptions();

  const dbConnection = await createConnection(connectionOptions);

  mediator.emit('db.ready', dbConnection);
}

- index.ts -
const mediator = new EventEmitter();

connectToDatabase(mediator);

mediator.on('db.ready', (db: Connection) =&gt; {
  app.listen(3000);
  console.log('app started');
});
</code></pre>

<p>Test</p>

<pre><code>describe('Jest Tests', () =&gt; {
    const mediator = new EventEmitter();
    let dbConnection: Connection;

    beforeEach(async () =&gt; {
        connectToDatabase(mediator);

        mediator.on('db.ready', (db: Connection) =&gt; {
           dbConnection = db;
           console.log(dbConnection.isConnected); // **returns TRUE**
        }
    }

    test('Testing db connection', () =&gt; {
        console.log(dbConnection.isConnected); // **dbConnection undefined**
    }
}
</code></pre>

<p>I also tried placing the local variables outside the <code>describe</code> block.</p>
",https://stackoverflow.com/questions/51845364/jestjs-database-connection-created-in-beforeeach-block-becomes-undefined-in-te,"['node.js', 'typescript', 'jestjs', 'typeorm']",619,TRUE,0,2
Entity Framework mocking requires global context,"<p>I have recently began to dig into Entity Framework unit-testing with Entity Framework 6 mocking. </p>

<p>I have noticed the following thing: </p>

<p>Entity Framework mocking forces me to create a global context in my BL class, for example:</p>

<pre><code>public class RefundRepayment : IDisposable
{
    protected DbContext _dbContext = new DbContext();

    /* more properties and class code */

    public void Dispose()
    {
        _dbContext.Dispose();
    }
}
</code></pre>

<p>I can't quite figure it out, as I'd rather implement the <code>using</code> statement in every method in order to deal with the <code>DbContext</code>, my code will look like:</p>

<pre><code>public class RefundRepayment
{
    /* more properties and class code */
    public void AccessDb() 
    {
        using(DbContext dbContext = new DbContext())
        {
            /* db code here */
        }
    }
}
</code></pre>

<p>Is there any specific reason why should we initialize a global context instead of implementing the <code>using</code> statement?</p>
",https://stackoverflow.com/questions/52025368/entity-framework-mocking-requires-global-context,"['c#', 'entity-framework', 'unit-testing', 'entity-framework-6', 'dbcontext']",272,TRUE,0,1
Make a unit test with jest for a function,"<p>I have start my first unit test in react with jest this afternoon. The 5 firsts tests that i have to do are about testing the return functions. No so difficult. </p>

<p>But i have difficulty to understand how to unit test my function login that return something i dont understand yet. Is someone see what i have to put in my action.test.js, show me and explain me ?</p>

<p>How can i unit testing login and what represent the dispatch that return the login function ? </p>

<pre><code>**In action.js**

&lt;pre&gt;
import { userConstants } from '../shared/constants';
import { userService } from '../shared/services';
import { history } from '../shared/helpers';

function request(user) {
  return { type: userConstants.LOGIN_REQUEST, user };
}
function success(user) {
  return { type: userConstants.LOGIN_SUCCESS, user };
}
function failure(error) {
  return { type: userConstants.LOGIN_FAILURE, error };
}

function login(username, password) {
  return (dispatch) =&gt; {
    dispatch(request({ username }));

    userService.login(username, password).then(
      (user) =&gt; {
        dispatch(success(user));
        history.push('/');
      },
      (error) =&gt; {
        dispatch(failure(error));
        console.error(error); // eslint-disable-line no-console
      },
    );
  };
}

function logout() {
  userService.logout();
  return { type: userConstants.LOGOUT };
}

function oldLogin() {
  return { type: userConstants.OLD_LOGIN };
}

export const userActions = {
  login,
  logout,
  oldLogin,
};
&lt;/pre&gt;

**In service.js**

&lt;pre&gt;
function logout() {
  // remove user from local storage to log user out
  if (localStorage.getItem('user')) {
    localStorage.removeItem('user');
  }
}

function handleResponse(response) {
  return response.text().then((text) =&gt; {
    const data = text &amp;&amp; JSON.parse(text);

    if (!response.ok) {
      if (response.status === 401) {
        // auto logout if 401 response returned from api
        logout();
        window.location.reload(true);
      }

      const error = (data &amp;&amp; data.message) || response.statusText;
      return Promise.reject(error);
    }

    return data;
  });
}


function login(username, password) {
  return fetch(
    'https://mon-api',
    {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        username,
        password,
        context: {
          deviceToken: '1cb1b51d19665cb45dc1caf254b02af',
        },
      }),
    },
  )
    .then(handleResponse)
    .then((user) =&gt; {
      // login successful if there's a jwt token in the response
      if (user.sessionToken) {
        // store user details and jwt token in local storage to
        // keep user logged in between page refreshes
        localStorage.setItem('user', JSON.stringify(user));
      }

      return user;
    });
}

export const userService = {
  login,
  logout,
};
&lt;/pre&gt;
</code></pre>
",https://stackoverflow.com/questions/53787811/make-a-unit-test-with-jest-for-a-function,"['javascript', 'reactjs', 'unit-testing', 'jestjs']",410,FALSE,-1,1
using a dependency injection for &#39;URLSession&#39; causes a &quot;BAD ACCESS&quot; infinite loop error,"<p>Currently I'm adding a dependency injection into my code so it can be unit tested with a mock 'URLSession'.  I used this article as reference: <a href=""https://medium.com/flawless-app-stories/the-complete-guide-to-network-unit-testing-in-swift-db8b3ee2c327"" rel=""nofollow noreferrer"">Guide to network unit testing swift</a> This is what the code looks like (minus the mock data):</p>

<pre><code>// Protocol for MOCK/Real
protocol URLSessionProtocol {
    typealias DataTaskResult = (Data?, URLResponse?, Error?) -&gt; Void

    func dataTask(with request: NSURLRequest, completionHandler: @escaping DataTaskResult) -&gt; URLSessionDataTaskProtocol
}

protocol URLSessionDataTaskProtocol {
    func resume()
}

//MARK: HttpClient Implementation
class HttpClient {

    typealias completeClosure = ( _ data: Data?, _ error: Error?)-&gt;Void

    private let session: URLSessionProtocol

    init(session: URLSessionProtocol) {
        self.session = session

    }

    func get( url: URL, callback: @escaping completeClosure ) {
        let request = NSMutableURLRequest(url: url)
        request.httpMethod = ""GET""
        let task = session.dataTask(with: request) { (data, response, error) in
            callback(data, error)
        }
        task.resume()
    }

}

//MARK: Conform the protocol
extension URLSession: URLSessionProtocol {
    func dataTask(with request: NSURLRequest, completionHandler: @escaping DataTaskResult) -&gt; URLSessionDataTaskProtocol

    {
        return dataTask(with: request, completionHandler: completionHandler) as URLSessionDataTaskProtocol

    }
}

extension URLSessionDataTask: URLSessionDataTaskProtocol {}
</code></pre>

<p>I'm trying to run it with ""URLSession.shared"" first to make sure it runs in a real environment:</p>

<pre><code>let HTTP = HttpClient(session: URLSession.shared)

HTTP.get(url: URL(string: ""https://sampleUrl"")!) { (data, error) in}
</code></pre>

<p>The error ""BAD ACCESS"" occurs here:</p>

<pre><code>extension URLSession: URLSessionProtocol {
    func dataTask(with request: NSURLRequest, completionHandler: @escaping DataTaskResult) -&gt; URLSessionDataTaskProtocol

    {
        return dataTask(with: request, completionHandler: completionHandler) as URLSessionDataTaskProtocol//This is where the error happens

    }
}
</code></pre>

<p>I can see in the debug navigator <code>URLSession.dataTask(with:completionHandler)</code> is repeated over and over again until it crashes.</p>
",https://stackoverflow.com/questions/49038598/using-a-dependency-injection-for-urlsession-causes-a-bad-access-infinite-loo,"['ios', 'mocking', 'swift4', 'nsurlsession', 'exc-bad-access']",400,FALSE,0,1
UI Test for AVFoundation&#39;s Camera,"<p>I'm trying to create a UI test for QR reader. I'm using AVFoundation's barcode types to decode QR. When user pressed the button QR Reader will appear. If the camera captures QR code with the correct form it has to present another view. How can I test it? Should I create UI test?</p>

<p>I've created Unit Testing for decoding QR function but I need to create a scenario for presenting other View Controller if camera decodes QR code which is in correct form.</p>
",https://stackoverflow.com/questions/51174818/ui-test-for-avfoundations-camera,"['xcode', 'xcode-ui-testing', 'ui-testing']",1069,TRUE,0,1
LoginServices unit Test,"<p>I'm new to angular unit testing and want to test my services file. How can  I do that?.</p>

<p>Tried testing the void methods but still confuse where to start.
How can I use <code>stub()</code> to mock data or if there's any other way to do it?. Here's my code.</p>

<pre><code>import { Injectable, Inject } from '@angular/core';
import { AUTH_API_URL, AuthenticationService } from 'ngx-login- 
client';
import { Router } from '@angular/router';
import { Broadcaster } from 'ngx-base';

@Injectable({
  providedIn: 'root'
})
export class LoginService {

static readonly REDIRECT_URL_KEY = 'redirectUrl';
static readonly DEFAULT_URL = '/_home';
static readonly LOGIN_URL = '/login';

constructor(
  private authService: AuthenticationService,
  private broadcaster: Broadcaster,
  private router: Router,
  @Inject(AUTH_API_URL) private authApiUrl: string
  ) {
  this.broadcaster.on('authenticationError').subscribe(() =&gt; {
    this.logout();
  });
}

redirectToAuth(): void {
  const redirectUrl = encodeURIComponent(window.location.href);
  const loginUrl = `${this.authApiUrl}login?redirect=${redirectUrl}`;
  window.location.href = loginUrl;
}

redirectAfterLogin(): void {
  const url = this.redirectUrl;
  this.router.navigateByUrl(url);
}

redirectToLogin(currentUrl: string): void {
  this.redirectUrl = currentUrl;
  window.location.href = LoginService.LOGIN_URL;
}

login(): void {
  const query = window.location.search.substr(1);
  const result: any = {};
  query.split('&amp;').forEach(function(part) {
    const item: any = part.split('=');
    result[item[0]] = decodeURIComponent(item[1]);
  });

  if (result['error']) {
    console.log(result['error']);
  }

  if (result['token_json']) {
    // Handle the case that this is a login
    this.authService.logIn(result['token_json']);
    console.log('token is :' + result);
    // Navigate back to the current URL to clear up the query string
    // this.router.navigateByUrl(this.router.url);
  } else if (this.authService.isLoggedIn()) {
    // Handle the case the user is already logged in
    this.authService.onLogIn();
  }
}

logout(): void {
  this.authService.logout();
  window.location.href = '/';
}

set redirectUrl(value: string) {
  if (value) {
    localStorage.setItem(LoginService.REDIRECT_URL_KEY, value);
  }
}

get redirectUrl(): string {
  const res = localStorage.getItem(LoginService.REDIRECT_URL_KEY);
  localStorage.removeItem(LoginService.REDIRECT_URL_KEY);
  return res;
  }
}
</code></pre>

<p>I don't know where to start from.If someone can help me in telling how to unit test any function that is given in this code,then I can get an idea of how to start.</p>
",https://stackoverflow.com/questions/53920693/loginservices-unit-test,"['angular', 'unit-testing', 'rxjs', 'angular6', 'angular7']",337,TRUE,0,1
Rendering React component issues,"<p>I'm having trouble rendering. Here is how I set up my files so far. First here is the app.js file:</p>

<pre><code>import React from 'react';
import MainPage from './MainPage';

export class App extends React.Component {
  render() {
    return (
      &lt;div&gt;
        &lt;MainPage /&gt;
      &lt;/div&gt;
    )
  }
}
</code></pre>

<p>Here is the second associated file called index.js:</p>

<pre><code>import React from 'react';
import ReactDOM from 'react-dom';
import { App } from './App';

ReactDOM.render(&lt;App /&gt;, document.getElementById('app'));
</code></pre>

<p>Lastly in the MainPage component I'm importing this:</p>

<pre><code>import App from ""./app"";
</code></pre>

<p>Is there a reason why this doesn't work with the file structure set as is? I know I can just put the ReacDOM.render in the app.js file as an alternative, but due to unit testing purposes, the file structure has to be similar to this. </p>
",https://stackoverflow.com/questions/48862494/rendering-react-component-issues,"['javascript', 'reactjs']",81,FALSE,0,2
Dropwizard testing - ResourceTestRule throwing NoClassDefFoundError: ch/qos/logback/core/filter/Filter,"<p>I am using dropwizard 1.2.4 with log4j 1.2.17. I have followed the instructions as mentioned below</p>

<p><a href=""https://github.com/arteam/dropwizard-nologback/"" rel=""nofollow noreferrer"">https://github.com/arteam/dropwizard-nologback/</a></p>

<p>It is throwing the exception like below during unit testing.</p>

<pre><code>java.lang.NoClassDefFoundError: ch/qos/logback/core/filter/Filter

    at io.dropwizard.testing.junit.ResourceTestRule.&lt;clinit&gt;(ResourceTestRule.java:34)
    at com.vnera.restapilayer.api.resources.ApiInfoControllerTest.&lt;clinit&gt;(ApiInfoControllerTest.java:25)
    at sun.misc.Unsafe.ensureClassInitialized(Native Method)
    at sun.reflect.UnsafeFieldAccessorFactory.newFieldAccessor(UnsafeFieldAccessorFactory.java:43)
    at sun.reflect.ReflectionFactory.newFieldAccessor(ReflectionFactory.java:156)
    at java.lang.reflect.Field.acquireFieldAccessor(Field.java:1088)
    at java.lang.reflect.Field.getFieldAccessor(Field.java:1069)
    at java.lang.reflect.Field.get(Field.java:393)
    at org.junit.runners.model.FrameworkField.get(FrameworkField.java:73)
    at org.junit.runners.model.TestClass.getAnnotatedFieldValues(TestClass.java:230)
    at org.junit.runners.ParentRunner.classRules(ParentRunner.java:255)
    at org.junit.runners.ParentRunner.withClassRules(ParentRunner.java:244)
    at org.junit.runners.ParentRunner.classBlock(ParentRunner.java:194)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:362)
    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: java.lang.ClassNotFoundException: ch.qos.logback.core.filter.Filter
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 19 more
</code></pre>

<p>My test code looks like below</p>

<pre><code>import io.dropwizard.testing.junit.ResourceTestRule;
import org.junit.Assert;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import javax.ws.rs.core.Response;

import static org.mockito.Mockito.mock;

@Category(value = UnitTest.class)
public class ApiInfoControllerTest {
    private static ApiNonFunctionalHandler nonFunctionalHandler = mock(ApiNonFunctionalHandler.class);
    private static ApiFilter apiFilter = new ApiFilter(nonFunctionalHandler);
    private static final String authToken = ""NetworkInsight xTyAGJmZ8nU8yJDP7LnA8Q=="";

    @ClassRule
    public static final ResourceTestRule resources = ResourceTestRule.builder()
            .addResource(new ApiInfoController())
            .addProvider(apiFilter).build();

    @Test
    public void testApiVersion() throws Exception {
        Response response = resources.client()
                .target(ApiConstants.INFO_BASE_URL + ""/version"")
                .request()
                .header(""Authorization"", authToken)
                .buildGet().invoke();

        Assert.assertNotNull(response);
        Assert.assertEquals(response.toString(), Response.Status.OK.getStatusCode(), response.getStatus());
        final VersionResponse actualError = response.readEntity(VersionResponse.class);
        Assert.assertEquals(actualError.getApiVersion(), ApiConstants.API_VERSION);
    }
}
</code></pre>

<p>My main application is working fine. The <code>configuration.yaml</code> for main application looks like below</p>

<pre><code># Change default server ports
server:
  applicationConnectors:
  - type: http
    port: 8123
  adminConnectors:
  - type: http
    port: 8124
  requestLog:
    type: external
logging:
  type: external
</code></pre>

<p>Can someone let me know what could be going wrong and how can I get around this?</p>

<p><strong>EDIT</strong>
 Output of <code>mvn dependency:tree</code> is placed <a href=""https://gist.github.com/debraj-manna/9a58d98726e01523c737a99fa40483a4"" rel=""nofollow noreferrer"">here</a> as I am hitting the character limit here.</p>
",https://stackoverflow.com/questions/50065899/dropwizard-testing-resourcetestrule-throwing-noclassdeffounderror-ch-qos-logb,"['java-8', 'dropwizard']",850,TRUE,0,1
PHPUnit testing in PhpStorm token mismatch exception,"<p>I am running unit testing on a <strong>Laravel</strong> project through <strong>PhpStorm inbuilt test environment</strong>. I am getting <strong>token mismatch exception</strong>.</p>

<p>All the configurations are correct and it was working fine. Suddenly this error showed up. I tried with the terminal and it works fine. I am developing this projects under Vagrant.</p>

<p>What can I do to solve this issue? </p>

<p>I googled and found out that changing Laravel's VerifyCsrfToken as below will solve this issue. But I need this to be default as well.
 <code>$except = ['/*']</code> </p>
",https://stackoverflow.com/questions/50809270/phpunit-testing-in-phpstorm-token-mismatch-exception,"['laravel', 'phpunit', 'phpstorm']",1625,TRUE,0,2
Spark Dataframe Write to Postgres Column Name in Double Quotes,"<p>I am trying to write a Dataframe into Postgres, where the column names in the Dataframe are codes in UPPERCASE. But the table in Postgres has column names in lowercase. When the </p>

<pre><code>dataframe.write.jdbc -&gt; java.sql.BatchUpdateException: Batch entry 0 INSERT INTO xxxxxxxx (""USE_CASE_ID"",""CUSTOMER_CODE"",""HOLDOUT"",""REFERENCE_ID"",""TAG_FIELDS"",""COMMS_RUN_ID"",""PRIMARY_OFFER_ID"") VALUES

ERROR: column ""USE_CASE_ID"" of relation ""xxxxxxxx"" does not exist
</code></pre>

<p>How can I make this work for any database in the future. I am not sure why Spark SQL puts """" for column names?</p>

<p>Another problem is, for unit testing I used H2 database, which expects the column names to be in UPPERCASE. So i ll have to satisfy for multiple databases.</p>
",https://stackoverflow.com/questions/50635094/spark-dataframe-write-to-postgres-column-name-in-double-quotes,"['postgresql', 'scala', 'apache-spark', 'rdbms']",852,FALSE,0,0
Python unit test - Mocking a class property,"<p>I'm coming from a java background and new to python. In Java, if a class initializes its own property like (this is bad for unit testing):</p>

<pre><code>class TestMe {
    Logger logger;
    public TestMe() {
        this.logger = new Logger();
    }

    //...stuff
}
</code></pre>

<p>I'd refactor it so I can provide a mocked dependency and test the class without creating a real instance of Logger:</p>

<pre><code>class TestMe {
    Logger logger;
    public TestMe(ILogger logger) {
        this.logger = logger;
    }

    //...stuff
}
</code></pre>

<p>But python is a very different language and there may be a way to mock that property without refactoring:</p>

<pre><code>import Logger

class TestMe:
    def __init__(self):
        self.logger = Logger()

    # stuff
</code></pre>

<p>is there a way to mock Logger in above python class without a refactor?</p>
",https://stackoverflow.com/questions/53855202/python-unit-test-mocking-a-class-property,"['python', 'unit-testing']",205,FALSE,0,1
PHP/Laravel How To Prevent All Functions Under One File,"<p>There is a helper file that should not be run when the unit testing is running. What is the best way to prevent all functions from being executed when the unit test is running without having to put condition on every function in the helper?</p>

<p>I tried to <code>return false</code> on constructor along with <code>App::runningUnitTests()</code>, but as many of you know, the constructor in php does not return anything, therefore it does not work.</p>

<p>Any suggestion or advice would be appreciated.
Thank you in advance.</p>
",https://stackoverflow.com/questions/53518399/php-laravel-how-to-prevent-all-functions-under-one-file,"['php', 'laravel', 'laravel-5', 'php-7', 'php-7.2']",54,FALSE,0,0
Junit test for saving data with JPA,"<p>Am trying to make a junit test to save data with JPA. Below is my entity class</p>

<pre><code>@Entity
@Table(name=""book"")
public class test {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name=""BOOK_REF_ID"",nullable=false)
private int bookRefId;
@Column(name=""BOOK_CODE"",nullable=false)
private String bookCode;
@Column(name=""BOOK_NAME"",nullable=false)
private String bookDescription;

public int getBookRefId() {
    return bookRefId;
}
public void setBookRefId(int bookRefId) {
    this.bookRefId = bookRefId;
}
public String getBookCode() {
    return bookCode;
}
public void setBookCode(String bookCode) {
    this.bookCode = bookCode;
}
public String getBookDescription() {
    return bookDescription;
}
public void setBookDescription(String bookDescription) {
    this.bookDescription = bookDescription;
}
}
</code></pre>

<p>Service class is</p>

<pre><code>public interface BookService()
    {
     public Book create(Book book); 
    }
</code></pre>

<p>Repository class is </p>

<pre><code>    public interface BookRepository extends 
    JpaRepository&lt;Book,Integer&gt;
    {  }
</code></pre>

<p>Service Implementation class is</p>

<pre><code>    public BookServiceImpli implements BookService()
    {
     @Resource
     BookRepository repository;
    @Override
    public Book create(Book book) {
    // TODO Auto-generated method stub
    return repository.save(book);
    }
    }
</code></pre>

<p>Now my test class is </p>

<pre><code>    @RunWith(SpringRunner.class)
    @DataJpaTest
    @SpringBootTest(classes= {JPAConfig.class})
    @AutoConfigureTestDatabase(replace=Replace.NONE)
    @TestPropertySource(
      locations = ""classpath:application.properties"")
    public class TestBook {
    @Autowired
    private BookService bookService ;
    @Test
    public void test() {
    Book book = new Book();
    book.setBookCode(""abc"");
    book.setBookDescription(""safd"");
    bookService.create(book);
    }
</code></pre>

<p>Application properties contains password and database details and JPAConfig contain JPA configuration details such as entity scan database details. When am trying to run the test case am getting an error like</p>

<pre><code>     A component required a bean of type 
    'com.repository.sample.BookRepository' that could not be found.
</code></pre>

<p>I don't have main method in it.Am new to unit testing please anyone help me to solve the issue.</p>
",https://stackoverflow.com/questions/51491348/junit-test-for-saving-data-with-jpa,"['spring', 'jpa', 'junit']",2359,FALSE,0,0
Angular unit test doesn&#39;t give expected result,"<p>I am a starter of Angular unit testing with Jasmine and Karma. To test I have written a small component. My component is following:</p>

<pre><code>import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-input',
  template: `{{ message }}`,
  styleUrls: ['./input.component.css']
})
export class InputComponent implements OnInit {
  @Input() message: string;

  constructor() { }

  ngOnInit() {
  }
}
</code></pre>

<p>I have the following test spes to test the above component: </p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { InputComponent } from './input.component';

describe('InputComponent', () =&gt; {
  let component: InputComponent;
  let fixture: ComponentFixture&lt;InputComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ InputComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(InputComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });

  it('should correctly render the passed @Input value', () =&gt; {
    component.message = 'Hi there';
    fixture.detectChanges();
    expect(fixture.debugElement.nativeElement.innerHTML).toBe('Hi there');
  });
});
</code></pre>

<p>This is alright, and the test gives the expected result. But when I separated my HTML in template file, the test runner gives following error:</p>

<blockquote>
  <p>Expected 'Hi there ' to be 'Hi there'.</p>
</blockquote>

<p>After separation, my component and template file looks like following:</p>

<pre><code>import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-input',
  templateUrl: './input.component.html',
  styleUrls: ['./input.component.css']
})
export class InputComponent implements OnInit {
  @Input() message: string;

  constructor() { }

  ngOnInit() {
  }
}
</code></pre>

<p>Content of my template file is:</p>

<pre><code>{{ message }}
</code></pre>
",https://stackoverflow.com/questions/53826959/angular-unit-test-doesnt-give-expected-result,"['angular', 'unit-testing']",782,TRUE,0,2
"In Google Test, can I call GetParam() from the constructor?","<p>The Google Test C++ unit testing framework provides the ability to do <a href=""https://github.com/google/googletest/blob/master/googletest/docs/advanced.md#value-parameterized-tests"" rel=""noreferrer"">parameterised tests</a>. To access the parameter of a given test, the docs tell me to derive a subclass and call <code>GetParam()</code>:</p>

<pre><code>class FooTest : public ::testing::TestWithParam&lt;const char*&gt; {
  // You can implement all the usual fixture class members here.
  // To access the test parameter, call GetParam() from class
  // TestWithParam&lt;T&gt;.
};
</code></pre>

<p>I cannot find anything more specific than this in either the docs or the source code (inasmuch as I understand it).</p>

<p>Exactly where (or when) can I call <code>GetParam()</code>? I know I can call it in the body of a <code>TEST_P(...) { ... }</code> macro, but what about:</p>

<ul>
<li>In the <code>SetUp()</code> method for <code>FooTest()</code>?</li>
<li>In the constructor for <code>FooTest()</code>?</li>
<li>In the intialisation list for <code>FooTest()</code>?</li>
</ul>
",https://stackoverflow.com/questions/50920765/in-google-test-can-i-call-getparam-from-the-constructor,"['c++', 'googletest']",4257,TRUE,5,1
How to throw an exception on an CompletableFuture.get() call?,"<p>Is there a way to have mockito throw an exception on the <code>CompletableFuture.get()</code> call and not just the asynchronous method?</p>

<p>For example, given the following (incorrect) test case:</p>

<pre class=""lang-java prettyprint-override""><code>@Test
public void whenRunnerThrows_thenReturn5xx() throws Exception {
    when(service.runAsync(any(),any())).thenThrow(new Exception(""""));

    mvc.perform(post(""/test"")
            .contentType(MediaType.APPLICATION_JSON)
            .content(""{\""name\"":\""test\""}""))
            .andExpect(status().is5xxServerError());
}
</code></pre>

<p>When <code>service.runAsync()</code> is called during testing, an exception is thrown, which makes sense. But when the (Spring Boot) application is run, then the same exception will only be thrown as a an <code>ExecutionException</code> cause on the returned <code>CompletableFuture::get</code>.</p>

<p>What is the correct way to write a test like this one so that the exception is thrown at the same time in unit testing as it is when running the application?</p>
",https://stackoverflow.com/questions/51251747/how-to-throw-an-exception-on-an-completablefuture-get-call,"['java', 'spring-boot', 'mockito', 'completable-future']",4447,TRUE,5,1
Mocking only one variable inside function with gtest,"<p>I'm coding in C and using gtest for C++ for unit testing.</p>

<p>I'd like to test situation where some variable gets integer overflow but incrementing that variable takes too long in UT. This variable is counter being written to directly only during initialization and is incremented on some events. My idea is to mock the counter to the maximum integer value during initialization, but I don't want to mock the function where counter is initialized because various other data important for UT is initialized in this function.</p>

<p>Is something like this possible with gtest or do I need to implement a stub which will have all the functionalities of real function and initialize wanted counter value to counter?</p>

<p>I cannot share the code since it's copyrighted, but here is excerpt showing general idea:</p>

<pre><code>typedef struct {
    some_variable;
    another_variable;
    counter;
} data_structure_defined_only_in_this_file;

...

// check_some_parameters() isn't exported in header files
void check_some_parameters(data_structure_defined_only_in_this_file *container) {
    if (something == true)
        container-&gt;counter++;
}

...

// initialization() isn't exported in header files
void initialization() {
    data_structure_defined_only_in_this_file *container;
    ...
    container = (struct data_structure_defined... *)calloc(1, sizeof(struct data_structure_defined...));
}
</code></pre>

<p>I made another function during initialization after allocating memory to container. This function returned value which was assigned to counter as initial value.</p>

<p>source_file.c</p>

<pre><code>// init_counter_val() IS exported to header file included in UT
int init_counter_val() { return 0; }

void initialization() {
    data_structure_defined_only_in_this_file *container;
    ...
    container = (struct data_structure_defined... *)calloc(1, sizeof(struct data_structure_defined...));
    container-&gt;counter = init_counter_val();
}
</code></pre>

<p>unit_test.cc</p>

<pre><code>...
ON_CALL(mockObj, init_counter_val()).WillByDefault(Return(INT_MAX));
...
</code></pre>

<p>I mocked that function for unit test to return max integer value on function call but that solution wasn't accepted since production code would be changed to enable unit testing. But since neither data structure type nor functions where counter is written to aren't exported from source file, I believe mocking is impossible.</p>
",https://stackoverflow.com/questions/48667817/mocking-only-one-variable-inside-function-with-gtest,"['c++', 'unit-testing', 'googletest', 'googlemock']",703,FALSE,0,0
"Class method outputs string message, can&#39;t unit test due error citing conversion from void to string not applicable","<p>I'm quite new to unit testing. So far, I'm able to successfully unit test methods that return a data type, such as enum types, integer types, and string types. However, I can't seem to unit test void return type methods that outputs a string, it says unable to convert 'void' to string. There isn't a return type. The code below should clarify my problem.
This is the method:</p>

<pre><code>public void Details()
    {
        if (_type == AccountType.FixedDeposit)
        {
            Console.WriteLine(String.Format(""Fixed Deposit Account:{0,-5}Balance:{1}"", _accNumber, _balance));
        }
        else
        {
            Console.WriteLine(String.Format(""{0,-13} Account:{1,-5}Balance:{2}"", _type, _accNumber, _balance));
        }
</code></pre>

<p>This is the unit test code:</p>

<pre><code>[TestCase]
    public void TestDetails()
    {
        BankAccount b = new BankAccount(111, AccountType.Saving);
        b.Deposit(1000);
        b.Withdraw(500);
        StringAssert.AreEqualIgnoringCase(""Saving       Account:111  Balance:500"", b.Details());
    }
</code></pre>

<p>I expected it to output a string that is able to compare too.</p>
",https://stackoverflow.com/questions/52332516/class-method-outputs-string-message-cant-unit-test-due-error-citing-conversion,"['c#', 'unit-testing', 'compiler-errors']",294,TRUE,2,1
"NullReferenceException in unittesting with NUnit, NSubstitute, and async method","<p>I'm doing some unit testing in C# using NUnit and NSubstitute. I have a class called <code>Adapter</code>, which has a method, <code>GetTemplates()</code>, I want to unit test. <code>GetTemplates()</code> uses <code>httpclient</code>, which I have mocked out using an interface.</p>

<p>The call in <code>GetTemplates</code> looks something like:</p>

<pre><code>public async Task&lt;List&lt;Template&gt;&gt; GetTemplates()
{
    //Code left out for simplificity. 

    var response = await _client.GetAsync($""GetTemplates"");

    if (!response.IsSuccessStatusCode)
    { 
        throw new Exception();
    }

}
</code></pre>

<p>I want <code>_client.GetAsync</code> to return a <code>HttpResponseMessage</code> with a <code>HttpStatusCode.BadRequest</code> so that I can test if the exception is being thrown.</p>

<p>The test method looks like:</p>

<pre><code>[Test]
public void GetTemplate_ReturnBadRequestHttpMessage_ThrowException()
{
     //Arrange.
     var httpMessage = new HttpResponseMessage(HttpStatusCode.BadRequest);
     _client.GetAsync("""").Returns(Task.FromResult(httpMessage));

     //Act.
     var ex = Assert.ThrowsAsync&lt;Exception&gt;(async () =&gt; await _Adapter.GetSigningTemplates());

     //Assert.
     Assert.IsInstanceOf&lt;Exception&gt;(ex);
 }
</code></pre>

<p>When the method has run, it returns</p>

<blockquote>
  <p>System.NullReferenceException: Object reference not set to an instance of an object.</p>
</blockquote>

<p>What did I do wrong?</p>
",https://stackoverflow.com/questions/53296372/nullreferenceexception-in-unittesting-with-nunit-nsubstitute-and-async-method,"['asp.net', 'unit-testing', 'async-await', 'nunit', 'nsubstitute']",1192,TRUE,2,1
Is it possible to use typeclasses to change `ReaderT (IO a) IO a` into `ReaderT (i a) IO a`?,"<p>I'm learning Haskell and I've got the following code thanks to help from <a href=""https://stackoverflow.com/questions/53939191/how-to-flatten-io-io/53939660#53939660"">this answer</a>, which is just an <code>echo</code> program. It works great, but I want to make some improvements to it and am running into trouble.</p>

<pre><code>userInput :: MonadIO m =&gt; ReaderT (IO String) m String
userInput = ask &gt;&gt;= liftIO -- this liftIO eliminates your need for join

echo :: MonadIO m =&gt; ReaderT (IO String) m ()
echo = userInput &gt;&gt;= liftIO . putStrLn -- this liftIO is just so you can use putStrLn in ReaderT

main :: IO ()
main = runReaderT echo getLine
</code></pre>

<p>What I'd like to do is change <code>ReaderT (IO String)</code> to <code>ReaderT (i String)</code> and make it more general so I can swap it out for unit testing. The problem is, because we use <code>liftIO</code> inside <code>userInput</code> it sort of <em>ties</em> <code>i</code> together with <code>IO</code>. Is there some way to replace <code>liftIO</code> with something else to make the following code work?</p>

<pre><code>class Monad i =&gt; MonadHttp i where
  hole :: MonadIO m =&gt; i a -&gt; ReaderT (i a) m a

instance MonadHttp IO where
  hole = liftIO

newtype MockServer m a = MockServer
  { server :: ReaderT (String) m a }
  deriving (Applicative, Functor, Monad, MonadTrans)

instance MonadIO m =&gt; MonadHttp (MockServer m) where
  -- MockServer m a -&gt; ReaderT (MockServer m a) m1 a
  hole s = s -- What goes here?

userInput :: (MonadHttp i, MonadIO m) =&gt; ReaderT (i String) m String
userInput = ask &gt;&gt;= hole

echo :: (MonadHttp i, MonadIO m) =&gt; ReaderT (i String) m ()
echo = userInput &gt;&gt;= \input -&gt;
         ((I.liftIO . putStrLn) input)

main = runReaderT echo (return ""hello"" :: MockServer IO String)
</code></pre>
",https://stackoverflow.com/questions/53972614/is-it-possible-to-use-typeclasses-to-change-readert-io-a-io-a-into-readert,"['unit-testing', 'haskell', 'monads', 'typeclass', 'monad-transformers']",102,TRUE,2,1
angular @Input() binding on attribute component for tr html tag failing unit tests,"<p>I am using an attribute selector component called <strong>app-product-row</strong> on a <strong>tr</strong> tag and im passing <strong>product</strong> in an @Input() as follows;</p>

<p><strong>class</strong></p>

<pre><code>@Component({
  selector: '[app-product-row]',
  templateUrl: './product-row.component.html',
  styleUrls: ['./product-row.component.scss']
})
export class ProductRowComponent {
  @Input() public product = null;
}
</code></pre>

<p><strong>TestBed</strong></p>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { ProductRowComponent } from './product-row.component';

describe('ProductRowComponent', () =&gt; {
  let component: ProductRowComponent;
  let fixture: ComponentFixture&lt;ProductRowComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ ProductRowComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(ProductRowComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>

<p><strong>markup</strong></p>

<pre><code>&lt;tr *ngFor=""let product of searchResults""
    [product]=""product""
    (showPipelineModalChange)=""onShowPipelineModalChange($event)""
    app-product-row&gt;
&lt;/tr&gt;
</code></pre>

<p>the code compiles successfully upon <strong>ng serve</strong> and everything works as expected on the browser however unit tests are throwing</p>

<pre><code>Chrome 63.0.3239 (Mac OS X 10.13.3)
Can't bind to 'product' since it isn't a known property of 'tr'
</code></pre>

<p>My implementation took inspiration from <a href=""https://stackoverflow.com/questions/34556277/angular2-table-rows-as-component"">Angular2 table rows as component</a> however in that example <strong>@Input()</strong>'s dont seem to be used and there is no mention of unit testing either.</p>

<p>could someone please point me in the right direction?</p>
",https://stackoverflow.com/questions/48444184/angular-input-binding-on-attribute-component-for-tr-html-tag-failing-unit-tes,"['javascript', 'angular']",729,TRUE,2,3
What are &quot;Branch indexing&quot; activities in Jenkins BlueOcean,"<p>I'm setting a Multi-Branch pipeline in jenkins blue ocean. Everything is starting to work nice.</p>

<p>One thing I've noticed is that once a while, I get an execution of the job named: ""Branch indexing"" running.</p>

<p>My build contains some heavy unit testing and code coverage, that take ~4h30 to be executed, so having this job randomly executed 2 times is not really good(not even taking in account that we have 6-8 active branches, so it would mean that the executions will only stacks.</p>

<p>So:</p>

<p>1) What are those executions?
2) Is this absolutely required? 
3) Can I disable it?</p>
",https://stackoverflow.com/questions/51082279/what-are-branch-indexing-activities-in-jenkins-blueocean,"['jenkins', 'jenkins-pipeline', 'jenkins-blueocean']",11696,TRUE,10,1
Is it possible to test jest tests?,"<p>I want to make a tool that test different exercises. One exercise is unit-testing. Therefore I need to test whether the tests that are made by the student are good tests. So for example the student has the following code:</p>

<pre><code>export class HelloWorld {
  public static showHello(): string {
    return 'Hello World!';
  }
}
</code></pre>

<p>With the following jest test:</p>

<pre><code>import { HelloWorld } from '..';

describe(Hello World exercise, () =&gt; {
  test('Check function is defined', () =&gt; {
    expect(HelloWorld.showHello()).toBeDefined();
  });

  test('Empty input results in Hello World!', () =&gt; {
    expect(HelloWorld.showHello()).toBe('Hello World!');
  });
});
</code></pre>

<p>How can I test that the student did indeed test these two tests? I thought about </p>

<pre><code>export const firstTest = test()...
</code></pre>

<p>And then test whether firstTest test the right thing. But the disadvantage is that you have to export every test for this solution.</p>
",https://stackoverflow.com/questions/53320397/is-it-possible-to-test-jest-tests,"['node.js', 'typescript', 'testing', 'jestjs']",110,FALSE,2,1
JEST component testing,"<p>I am new to unit testing with Jest. I am testing a component in a React app. There are two components: <code>Home</code> and <code>LogOutButton</code></p>

<p>This is The Home component:</p>

<pre><code>import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/css/bootstrap-theme.css';
import React from 'react';
import ReactDOM from 'react-dom';
import { LogOutButton } from './LogOutButton.js';

class Home extends React.Component {
  displayName = Home.name;

  state = {
    result: 0,
    val1: 0,
    val2: 0,
  };

  handleChangeOne = event =&gt; {
    this.setState({ val1: event.target.value });
  };

  handleChangeTwo = event =&gt; {
    this.setState({ val2: event.target.value });
  };

  add = () =&gt; {
    this.setState({ 
      result: parseInt(this.state.val1) + parseInt(this.state.val2)
    });
  };

  onLogoutClick = () =&gt; {
    window.location.href = 'https://www.MICROSOFT.com';
  }

  render() {
    return (
      &lt;div&gt;
        &lt;h1&gt;Hello world! The result is: {this.state.result}&lt;/h1&gt;
        &lt;input type=""text"" onChange={this.handleChangeOne} /&gt;
        +
        &lt;input type=""text"" onChange={this.handleChangeTwo} /&gt;
        = &lt;br /&gt;
        &lt;button onClick={this.add}&gt;Add&lt;/button&gt;
        &lt;br/&gt;&lt;br/&gt; 
        &lt;LogOutButton onLogout={this.onLogoutClick} /&gt; 
      &lt;/div&gt;
    );
  }
}

export default Home;
const rootElement = document.getElementById(""root"");
ReactDOM.render(&lt;Home /&gt;, rootElement);
</code></pre>

<p><code>Home</code> component can get 2 numbers and render their sum. Where it also imports <code>LogOutButton</code> Component and when it is clicked, it should redirect you to Microsoft website.</p>

<p>I want to test a scenario where the user click <code>LogOut</code>.</p>

<p>This is my suggestion:</p>

<pre><code>describe('Home /&gt;', () =&gt; {
  it('Directing to Microsoft site when LogOut is clicked', () =&gt; {
     const homeWrapper = shallow(&lt;Home /&gt;);
     homeWrapper.find('LogOutButton').simulate('click');
     homeWrapper.update();
     expect(homeWrapper.html).toEqual('https://www.MICROSOFT.com');
  });
}
</code></pre>

<p>This does not work..
I am looking for an assistance to write the right test method.
Thanks in advance </p>
",https://stackoverflow.com/questions/53536427/jest-component-testing,"['reactjs', 'unit-testing', 'jestjs', 'enzyme']",734,FALSE,1,2
How to Test APIs in Swift 4?,"<p>I am new to Unit Testing. I have tested a lot of functions and I understood the concept, now I want to check the APIs. Is it possible? I guess so. This is the API:</p>

<pre><code>func sendRequest(path: String, params: Dictionary&lt;String, Any&gt;, showSpinner: Bool, completionHandler: @escaping (JSON, Error?) -&gt; Void) {
    if Constants.IS_SIMULATOR {
        print(""Path: \(path)"")
        print(""Params: \(params)"")
    }

    if Constants.APP_DEL.reachability?.connection == .none {
        completionHandler(JSON.null, NSError(domain: ""No internet"", code: 4, userInfo: nil))
        return
    }

    UIApplication.shared.isNetworkActivityIndicatorVisible = true

    if showSpinner {
        HUD.show(.labeledProgress(title: ""Loading..."", subtitle: ""Please wait""))
    }

    if let jsonData = try? JSONSerialization.data(withJSONObject: params, options: .prettyPrinted) {

        let url = NSURL(string: String(format: ""%@%@"", Constants.TEST_URL, path))!
        let request = NSMutableURLRequest(url: url as URL)
        request.httpMethod = ""POST""
        request.httpBody = jsonData
        request.timeoutInterval = 120

        let task = URLSession.shared.dataTask(with: request as URLRequest){ data, response, error in
            DispatchQueue.main.async {
                if error != nil {
                    print("" ........ \(String(describing: error?.localizedDescription))"")
                    UIApplication.shared.isNetworkActivityIndicatorVisible = false

                    if showSpinner {
                        HUD.flash(.labeledError(title: ""Server issue"", subtitle: ""Invalid response""), delay: 2.0)
                    }

                    completionHandler(JSON.null, NSError(domain: ""Invalid response"", code: 420, userInfo: nil))
                    return
                }


                if (data?.isGzipped)! {
                    let decompressedData: Data = try! data!.gunzipped()
                    var json: JSON = JSON.null
                    do {
                        json = try JSON(data: decompressedData)
                    }
                    catch {
                        print(error)
                    }

                    if Constants.IS_SIMULATOR {
                        print(""Response: \(json)"")
                    }

                    UIApplication.shared.isNetworkActivityIndicatorVisible = false


                    if json[""status""].int == 200 {
                        if showSpinner {
                            HUD.flash(.success, delay: 0.5)
                        }
                        completionHandler(json[""data""], nil)
                    }
                    else if json[""status""].int == 202 {
                        if showSpinner {
                            HUD.hide()
                        }
                        completionHandler(JSON.null, NSError(domain: json[""message""].string!, code: json[""status""].int!, userInfo: nil))
                    }
                    else if json[""status""].int == 310 {
                        if showSpinner {
                            HUD.hide()
                        }
                        completionHandler(json[""data""], nil)
                    }
                    else if json[""status""].int == 403 {
                        if showSpinner {
                            HUD.hide()
                        }

                        GeneralHelper.sharedInstance.displayAlertMessage(titleStr: ""Session expired"", messageStr: ""Kindly login again."")

                        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: {

                            let domain = Bundle.main.bundleIdentifier!
                            UserDefaults.standard.removePersistentDomain(forName: domain)
                            UserDefaults.standard.synchronize()
                            Constants.APP_DEL.navC?.popToRootViewController(animated: false)
                        })
                        completionHandler(JSON.null, NSError(domain: json[""message""].string!, code: json[""status""].int!, userInfo: nil))
                    }
                    else {
                        if showSpinner {
                            HUD.flash(.labeledError(title: """", subtitle: json[""message""].string!), delay: 2.0)
                        }
                        completionHandler(JSON.null, NSError(domain: json[""message""].string!, code: json[""status""].int!, userInfo: nil))
                    }
                }
                else {
                    let backToString = String(data: data!, encoding: String.Encoding.utf8) as String?
                    if Constants.IS_SIMULATOR {
                        print(""Invalid response: \(String(describing: backToString))"")
                    }
                    UIApplication.shared.isNetworkActivityIndicatorVisible = false


                    if showSpinner {
                        HUD.flash(.labeledError(title: ""Server issue"", subtitle: ""Invalid response""), delay: 2.0)
                    }
                    completionHandler(JSON.null, NSError(domain: ""Invalid response"", code: 420, userInfo: nil))
                }
            }
        }

        task.resume()
    }
}
</code></pre>

<p>So, to test this I have done this:</p>

<pre><code>func testAPIWorking() {
    params = [""ios_token"": ""dq6YJkKwEx0:APA91bFeOTfJRFd5G78xMkv3AvjSLA7ey2dJxTZZAtMuuC50CqWILNzNjdgqVpNpDn7R4I0DLoydIVDYKubpGfgfu1bwz1H3VNU4D88ek8PJTAjxrd3CWkW78g0sNv6EZDLlTqUFeNxh"", ""api_token"": ""kfRSHL0bVP1fSmxNY3NfEGs8g0ktKCbTsPRRbfarh3a5ISIcZLu3qdK07MJ9H4rJ"", ""player_id"": 8083]

    ServiceHelper.sharedInstance.sendRequest(path: ""home"", params: self.params, showSpinner: false) { (result, error) in
        if error != nil {
            XCTFail(""Fail"")
        }
        else {

        }       
    }
}
</code></pre>

<p>I have added a breakpoint at task and it prints the task but then when I try to move to next line, instead of going into <code>Dispatch</code> it takes me out of that and stops at <code>task.resume()</code> and because of this I am not able to test the <code>errors</code> or expected <code>results</code>. Any help?</p>
",https://stackoverflow.com/questions/53116903/how-to-test-apis-in-swift-4,"['ios', 'swift', 'xcode', 'unit-testing']",9107,TRUE,4,1
"Oracle JDBC exception, in webapp, in Tomcat deployment: No suitable driver at java.sql.DriverManager.getDriver","<p>I am unit-testing my jersey web-service through jersey client using eclipse Oxygen.3a, Tomcat 9,  JDK 1.8, and ojbc14.jar in my WEB-INF/lib of my web-app in eclipse. I do not have any ojdbc.jar's in my Tomcat/lib dir. So there is single copy of my ojdbc jar file, i.e. ojdbc14.jar. My JDBC URL is <code>jdbc:oracle:thin:@mcname.com:1521:orcl1</code>.</p>

<p>My request is failing due to the following error:</p>

<blockquote>
  <p>Exception when obtaining connection
  java.sql.SQLException: No suitable driver
    at java.sql.DriverManager.getDriver(DriverManager.java:315)
      at 
  :</p>
</blockquote>

<p>Code:</p>

<pre><code>DriverManager.getDriver(""jdbc:oracle:thin:@"" + url);
</code></pre>
",https://stackoverflow.com/questions/51696290/oracle-jdbc-exception-in-webapp-in-tomcat-deployment-no-suitable-driver-at-ja,"['eclipse', 'java-8', 'ojdbc', 'jersey-1.0', 'tomcat9']",400,FALSE,1,1
H2 HEXTORAW gives chinese char output,"<p>I'm trying to write a dbunit test with the H2 database for a query using the HEXTORAW function</p>

<pre><code>select hextoraw('79E6AAA933FA493990CC7502B5167D49')
</code></pre>

<p>gives me </p>

<blockquote>
  <p>秦ꪩ㏺䤹郌甂딖絉</p>
</blockquote>

<p>as output on H2, the real oracle database where the code will run gives me </p>

<blockquote>
  <p>79  e6  aa  a9  33  fa  49  39  90  cc  75  02  b5  16  7d  49</p>
</blockquote>

<p>Do I need to configure H2 differently so I get the right output ?  This currently blocks my unit testing and I don't see a way out of it.</p>
",https://stackoverflow.com/questions/48077726/h2-hextoraw-gives-chinese-char-output,"['sql', 'h2', 'dbunit']",490,TRUE,1,1
"JUnit test class with persistent, non-static field","<p>Straight forward question: in JUnit can I make a non-static field of a test class persist throughout the execution of each test method? </p>

<p>My goal is to be able to instantiate an expensive external resource only once over the execution of the entire test class, but due to our inheritance structure a static field with @ClassRule won't cut it. </p>

<p>I admit my question is against the principles of unit testing independence, and therefore may be impossible by definition.</p>

<p>Any suggestions much appreciated, thanks SO!</p>
",https://stackoverflow.com/questions/51029572/junit-test-class-with-persistent-non-static-field,"['junit', 'static', 'integration-testing']",58,FALSE,1,0
Error: &lt;spyOn&gt; : could not find an object to spy upon for Roles(),"<p>I'm writing my first Angular 6 unit test. I follow this source <a href=""https://www.youtube.com/watch?v=lTKhB6uAmno"" rel=""nofollow noreferrer"">https://www.youtube.com/watch?v=lTKhB6uAmno</a> to construct my test file and I ended up with the error which I couldn't resolve. I found a <a href=""https://stackoverflow.com/questions/49427564/spyon-could-not-find-an-object-to-spy-upon-for-login-angular-testbed"">similar question</a> in SO but that wasn't obtained an answer unfortunately. Please guide me to sort this error out. Thanks. Here are my files,</p>

<p><strong>component.ts</strong>  </p>

<pre><code>import { Component } from '@angular/core';
import { InputModel } from '../model/formInput';
import { APIService } from '../service/APIService';

@Component({
    selector: 'results-component',
    templateUrl: './result.component.html',
    styleUrls: ['./result.component.css']
})

export class ResultComponent {
    constructor(private apiService: APIService) { }
    sendTask(model: InputModel) {
        this.apiService.getRoles(model.TaskName)
            .subscribe(
                res =&gt; {
                    console.log(res)
                }, err =&gt; { console.log(err) });
    }
}
</code></pre>

<p><strong>service.ts</strong></p>

<pre><code>import {Injectable} from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { ApiResponse } from '../model/ApiResponse';
import { Observable, throwError } from 'rxjs';
import { map, catchError } from 'rxjs/operators';

@Injectable()

export class APIService{

    private url:string = 'http://localhost:1/api/default';
    result:ApiResponse;
    private http:HttpClient;

    constructor(){}

    getRoles(taskName:string):Observable&lt;ApiResponse&gt;{
        var params = this.getParams(taskName);
        return this.http.get&lt;ApiResponse&gt;(this.url,{ params })
        .pipe(
            map((data:ApiResponse)=&gt;data),
            catchError((err:ApiResponse)=&gt;throwError(err))
            )
        }

    private getParams(taskName:string){
        let param = new HttpParams().set('taskName', taskName);
        return param;
    }
}
</code></pre>

<p><strong>component.spec.ts</strong></p>

<pre><code>import { ResultComponent } from ""./result.component"";
import {ComponentFixture, TestBed, inject} from '@angular/core/testing';
import { APIService } from ""../service/APIService"";
import { of } from ""rxjs"";
import { ApiResponse } from ""../model/ApiResponse"";
import { InputModel } from ""../model/formInput"";
import { HttpClientTestingModule } from ""@angular/common/http/testing"";

describe('ResultComponent', ()=&gt;{
    let fixture:ComponentFixture&lt;ResultComponent&gt;;
    let component:ResultComponent;
    let apiService:APIService;
    let model:InputModel = new InputModel();
    let mockResponse : ApiResponse=
    {
        code:'0',
        data:{
            permissionsList:[
                {
                    orgRoles:'Edit Access TRUE',
                    roleType:'OPTIONAL'
                }
            ]
        },
        message:'',
        status:'success'
    };

    beforeEach(()=&gt;{
        TestBed.configureTestingModule({
            imports:[HttpClientTestingModule],
            declarations:[ResultComponent],
            providers:[APIService]//,
            //{provide:HttpClient}]
        }).compileComponents();

        fixture = TestBed.createComponent(ResultComponent);
        component = fixture.componentInstance;
        apiService=TestBed.get(APIService);

        model.TaskName='Edit';
    });

    it('test service response', ()=&gt;{
        spyOn(apiService, 'getRoles').and.returnValue(of(mockResponse));
         component.sendTask(model);
        expect(apiService.getOrgRoles).toHaveBeenCalled();
    });
})
</code></pre>

<p>If i use fake service, the unit testing is working fine. I'm not able to find out what i miss in my spec file.</p>
",https://stackoverflow.com/questions/52069355/error-spyon-could-not-find-an-object-to-spy-upon-for-roles,"['angular', 'typescript', 'jasmine']",10563,TRUE,1,1
How to Inject Clock.getInstance() in Spring Boot?,"<p>I want to unit test some code that calls <code>System.currentTimeMillis()</code>. As <a href=""https://stackoverflow.com/questions/2001671/override-java-system-currenttimemillis-for-testing-time-sensitive-code#answer-2001696"">this answer</a> points out, a good way to do this is to replace calls to <code>System.currentTimeMillis()</code> with <code>Clock.getInstance().currentTimeMillis()</code>. Then, you can perform dependency injection on <code>Clock.getInstance()</code>, for example to replace it with a mock in unit testing.</p>

<p>So, my question is a follow-up to that. How do you configure <strong>Spring Boot</strong> to inject <code>Clock.getInstance()</code> at runtime?</p>

<p>If possible, I'd prefer to do this with annotations instead of XML.</p>

<p>Also, if possible, I'd like to do this in such a way that I can simply use <code>@Mock</code> and <code>@InjectMocks</code> with <code>MockitoJUnitRunner</code> to inject a mock clock into a unit test.</p>
",https://stackoverflow.com/questions/49634941/how-to-inject-clock-getinstance-in-spring-boot,"['java', 'spring', 'unit-testing', 'spring-boot']",11569,TRUE,9,2
How to capture the output on stderr of a logger using a StreamHandler?,"<p>Redirecting the output of normal logging works fine:</p>

<pre><code>import contextlib
import io
import logging

std_out_capture = io.StringIO()
with contextlib.redirect_stderr(std_out_capture):
    logging.error('Hi.')

output = std_out_capture.getvalue()
print(f'output: {output}')
</code></pre>

<p>output:</p>

<pre><code>output: ERROR:root:Hi.
</code></pre>

<p>However when changing the log format using <code>logging.basicConfig</code></p>

<pre><code>import contextlib
import io
import logging

log_format = '[%(threadName)s] [%(levelname)s] %(message)s'
logging.basicConfig(format=log_format)

std_out_capture = io.StringIO()
with contextlib.redirect_stderr(std_out_capture):
    logging.error('Hi.')

output = std_out_capture.getvalue()
print(f'output: {output}')
</code></pre>

<p>the output is:</p>

<pre><code>output: 
[MainThread] [ERROR] Hi.
</code></pre>

<p>So the output is not captured any more.</p>

<p>My guess is this is because</p>

<blockquote>
  <p>logging.basicConfig(**kwargs): Does basic configuration for the logging system by creating a StreamHandler with a default Formatter and adding it to the root logger.</p>
</blockquote>

<p>(<a href=""https://docs.python.org/3/library/logging.html#logging.basicConfig"" rel=""nofollow noreferrer"">https://docs.python.org/3/library/logging.html#logging.basicConfig</a>)</p>

<p>and <code>StreamHandler</code> is working in a separate thread, so it's output is not captured.</p>

<p>For unit testing I would like to capture it anyways. How can I do this?</p>
",https://stackoverflow.com/questions/51841368/how-to-capture-the-output-on-stderr-of-a-logger-using-a-streamhandler,"['python', 'python-3.x', 'logging', 'stdout', 'stderr']",269,TRUE,4,1
Uncaught Syntax Error when running Vue.Js Unit Tests with Karma,"<p>I'm trying to get unit testing set up for my Vue JS project with Karma and Mocha (with vue-cli, I originally used Jest but I'm switching to Karma). I try to run my test with <code>karma start; karma run</code> and I keep getting:</p>

<pre><code>09 03 2018 17:02:49.778:INFO [karma]: Karma v2.0.0 server started at http://0.0.0.0:9876/
09 03 2018 17:02:49.786:INFO [launcher]: Launching browser Chrome with unlimited concurrency
09 03 2018 17:02:49.797:INFO [launcher]: Starting browser Chrome
09 03 2018 17:02:54.410:INFO [Chrome 64.0.3282 (Windows 10.0.0)]: Connected on socket mvbOII8qli3NiwBMAAAA with id 62867001
Chrome 64.0.3282 (Windows 10.0.0) ERROR
  {
""message"": ""Uncaught SyntaxError: Unexpected identifier\nat specs/PdfView.spec.js:3:8\n\nSyntaxError: Unexpected identifier"",
""str"": ""Uncaught SyntaxError: Unexpected identifier\nat specs/PdfView.spec.js:3:8\n\nSyntaxError: Unexpected identifier""
  }
</code></pre>

<p>The test runner starts, but I'm guessing some config issue is preventing the test from running properly. Also, it's not this just one component that will give me those errors.</p>

<p>My karma.conf.js file:</p>

<pre><code>var webpackConfig = require('../../build/webpack.test.conf')

module.exports = function karmaConfig (config) {
  config.set({
browsers: ['Chrome'],
frameworks: ['mocha'],
reporters: ['spec', 'coverage'],
files: ['specs/**/*.spec.js'],
preprocessors: {
  'test/unit/spec/**/*.spec.js': [ 'webpack', 'sourcemap' ]
},
plugins: [
  // Launchers
  'karma-chrome-launcher',

  // Test Libraries
  'karma-mocha',
  // 'karma-sinon-chai',

  // Preprocessors
  'karma-webpack',
  'karma-sourcemap-loader',

  // Reporters
  'karma-spec-reporter',
  'karma-coverage'
],
webpack: webpackConfig,
webpackMiddleware: {
  noInfo: true
},
singleRun: true,
coverageReporter: {
  dir: './coverage',
  reporters: [
    { type: 'lcov', subdir: '.' },
    { type: 'text-summary' }
  ]
}
  })
}
</code></pre>

<p>My .babelrc file:</p>

<pre><code>{
  ""presets"": [
[""env"", {
  ""modules"": false,
  ""targets"": {
    ""browsers"": [""&gt; 1%"", ""last 2 versions"", ""not ie &lt;= 8""]
  }
}],
""stage-2""
 ],
""plugins"": [""transform-vue-jsx"", ""transform-runtime""],
""env"": {
""test"": {
  ""presets"": [""env"", ""stage-2""],
  ""plugins"": [""transform-vue-jsx"", ""transform-es2015-modules-commonjs"", ""dynamic-import-node""]
}
}
}
</code></pre>

<p>My webpack.test.conf.js:</p>

<pre><code>'use strict'
const utils = require('./utils')
const webpack = require('webpack')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')

const webpackConfig = merge(baseWebpackConfig, {
  // use inline sourcemap for karma-sourcemap-loader
 module: {
rules: utils.styleLoaders(),
loaders: [
  {
    test: /\.js$/,
    loader: 'babel-loader',
    exclude: /node_modules/
  },
  {
    test: /\.vue$/,
    loader: 'vue-loader'
  }
]
},
devtool: '#inline-source-map',
  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'
}
},
plugins: [
 new webpack.DefinePlugin({
  'process.env': require('../config/test.env')
})
 ]
})


delete webpackConfig.entry

module.exports = webpackConfig
</code></pre>

<p>PdfView.spec.js</p>

<pre><code>import Vue from 'vue';

import Test from '@/components/Submission/PdfView';

describe('Test', () =&gt; {
it(`should render`, () =&gt; {

const Constructor = Vue.extend(Test);

const comp = new Constructor({}).$mount();

expect(comp.$el.textContent)
  .to.equal('Test Text');
});
});
</code></pre>

<p>Webpack ^3.6.0, 
Karma ^2.0.0, 
Vue ^2.5.2</p>
",https://stackoverflow.com/questions/49203137/uncaught-syntax-error-when-running-vue-js-unit-tests-with-karma,"['unit-testing', 'webpack', 'vue.js', 'karma-runner', 'karma-mocha']",494,FALSE,1,1
Jest testing a function with no return,"<p>I am in the process of unit testing a function using Jest that merely passes on its parameters to another function by calling it and has no return.</p>

<p>I have googled and tried a bunch of suggested mock implementations, but can't seem to get it to work.</p>

<p><strong>Imported File:</strong></p>

<pre><code>export const firstFunc = (dataObj) =&gt; {
  secondFunc('anything', dataObj)
}

export const secondFunc = (str, dataObj) =&gt; {
  // Does something with the dataObj but also doesn't return anything.
}
</code></pre>

<p>Essentially what I want to test for is that <code>firstFunc</code> calls <code>secondFunc</code>, but am not able to get it to work. </p>

<p>Thank you in advance. Also, open to suggestions for any other tests that I could run in this situation.</p>
",https://stackoverflow.com/questions/50866632/jest-testing-a-function-with-no-return,"['javascript', 'unit-testing', 'testing', 'jestjs']",10055,TRUE,1,1
Angular 2 jest input delegate test,"<p>I have a problem with the unit-testing delegate component, which should block special keys and allow the input of data matching the regular expression.</p>

<p>The directive component code is:</p>

<pre><code>import {Directive, ElementRef, HostListener, Input} from '@angular/core';
@Directive({
  selector: '[w2NumberLimit]',
})
export class NumberLimitDirective {
  @Input() public integerLimit: number = 10;
  @Input() public fractionalLimit: number = 0;
  @Input() public decimalMark: string = ',';

  constructor(private el: ElementRef) { }

  @HostListener('keypress', ['$event']) public onKeyPress(event) {
     const next: string = current.concat(event.key);
     const regexp = RegExp(this.setRegexp(), 'g');

     if (next &amp;&amp; !String(next).match(regexp)) {
         event.preventDefault();
     }
  }

private setRegexp() {
    let regexp: string = '^[0-9]';

    // set integer part limit
    regexp = regexp + ((this.integerLimit) ? `{0,${this.integerLimit}}` : '*');

    // set fractionalLimit
    regexp = regexp + ((this.fractionalLimit &gt; 0) ? `(\\${this.decimalMark}[0-9]{0,${this.fractionalLimit}})?` : '');

    return regexp + '$';
  }
}
</code></pre>

<p>Unit test code:</p>

<pre><code>describe('Directive: NumberLimitDirective', () =&gt; {
  let component: TestNumberLimitComponent;
  let fixture: ComponentFixture&lt;TestNumberLimitComponent&gt;;
  let inputAutoFocusEl: DebugElement;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [NumberLimitDirective, TestNumberLimitComponent],
      imports: [FormsModule],
    }).compileComponents();
    fixture = TestBed.createComponent(TestNumberLimitComponent);
    component = fixture.componentInstance;
    inputAutoFocusEl = fixture.debugElement.query(By.css('input'));
  });

  beforeEach(async () =&gt; {
    fixture.detectChanges();
    fixture.whenStable();
  });

  function sendInput(inputElement: any, text: number | string) {
    const value = inputElement.nativeElement.value;
    inputElement.nativeElement.value = value.concat(text);
    const event = new Event('input');
    inputElement.nativeElement.dispatchEvent(event);
    fixture.detectChanges();
    return fixture.whenStable();
  }

  function sendKeyDown(inputElement: any, event: any) {
    inputElement.nativeElement.dispatchEvent(event);
    fixture.detectChanges();
    return fixture.whenStable();
  }

  function testInput(inputElement: any, text: number | string) {
    const oneKeyDown = new KeyboardEvent('keypress', {key: `${text}`});
    sendKeyDown(inputElement, oneKeyDown);
    if (!oneKeyDown.defaultPrevented) {
      sendInput(inputElement, text);
    }
  }

  test('Check valid input for default input.', async () =&gt; {
    fixture.detectChanges();
    const testLocator = fixture.debugElement.query(By.css('#default'));
    expect(testLocator).not.toBe(null);
    await testInput(testLocator, 1);
    await testInput(testLocator, ',');
    await testInput(testLocator, 0);
    jest.runAllTicks();
    expect(testLocator.nativeElement.value).toBe('01');
  });
});
</code></pre>

<p>Test component code:</p>

<pre><code>@Component({
  template: `
    &lt;div&gt;
      &lt;input id=""default"" w2NumberLimit [value]=""test"" [(ngModel)]=""test"" #input=""ngModel""&gt;
    &lt;/div&gt;`
})
export class TestNumberLimitComponent {
  public test = 0;
}
</code></pre>

<p>By default this component should ignore "","" and ""0"". So output value should be ""01"", but preventDefault field of event doesn't change its value to ""true"".</p>

<p>In the same time this directive works with input directly when i use it in my application. With same input it blocks last "","" and ""0"" inputs.</p>
",https://stackoverflow.com/questions/50275615/angular-2-jest-input-delegate-test,"['angular', 'unit-testing', 'angular5', 'angular2-directives', 'jestjs']",322,FALSE,1,0
How to unit test a reactive component where ngControl is decorated with @Self,"<p>I've written a reactive component by injecting the NgControl and which is decorated using the @Self decorator. My problem is related to unit testing of such component.
Please look at the code below:</p>

<p>Disclaimer: I've quickly copied the code and made some inline changes. So, this might not be a compiler happy code.</p>

<p>My Reactive Component:</p>

<pre><code>@Component({
  selector: 'text-input',
  templateUrl: '&lt;input type=""text"" class=""native_input"" /&gt;'
})
class TextInput implements ControlValueAccessor {
  protected constructor(@Self() public controlDir: NgControl) {

    this.controlDir.valueAccessor = this;
  }

  // ...followed by other ControlValueAccessor methods

}
</code></pre>

<p>Unit Test:</p>

<pre><code>describe('TextInput -', () =&gt; {

   let fixture: ComponentFixture&lt;TextInputHost&gt;;
   let textInput: TextInput;

   let inputElement: HTMLInputElement;

   beforeEach(async(() =&gt; {
     TestBed.configureTestingModule({
       declarations: [
         TextInput, TextInputHost
       ],
       imports: [
         FormsModule, ReactiveFormsModule
       ]
     });
  }));

  beforeEach(fakeAsync(() =&gt; {
    fixture = getTestBed().createComponent(TextInputHost);
    textInput = fixture.componentInstance.textInputComponent;
    textInput.writeValue('TestValue');
    inputElement = fixture.debugElement
       .query(By.css('native_input')).nativeElement;
    fixture.detectChanges();
    tick();
  }));

  it('Should have the initial value applied.', () =&gt; {
    expect(inputElement.value).toBe('TestValue');
  });

});

// Host component
@Component({
  template: `
   &lt;form [formGroup]=""pageForm""&gt;
    &lt;text-input formControlName=""testInput""&gt;
    &lt;/text-input&gt;
   &lt;/form&gt;`
})
class TextInputHost {
   @ViewChild(TextInput)
   public textInputComponent: TextInput;

   public pageForm: FormGroup = new FormGroup({
     testInput: new FormControl('Initial Value')
   });
}
</code></pre>

<p>Whenever I try to run the above unit test. It fails with the following error:
<code>
Template parse errors: No provider for NgControl --&gt; &lt;text-input&gt;....&lt;/text-input&gt;
</code></p>

<p>So I'm looking for a way to successfully run the above unit test. What, I'm looking for is a way to inject the NgControl to the <code>TextInput</code> component.</p>
",https://stackoverflow.com/questions/52931778/how-to-unit-test-a-reactive-component-where-ngcontrol-is-decorated-with-self,"['angular', 'unit-testing', 'angular-reactive-forms', 'angular-components']",3177,TRUE,9,2
How to make Entity Framework DbContext generic for dynamic connection string?,"<p>This is my method in the business layer:</p>

<pre><code>public async task&lt;model&gt; GetMemberList(CancellationToken cancelToken, string connString){
    try
    {
        await Task.Run(() =&gt;
        {
             using (var dbContext = DbContext.Create(connString))
                {
                   Code Goes Here....
                }
        }, cancelToken);
      }
      catch
      {
         Throw New Exception(); 
      }
    }
</code></pre>

<p>we have different clients databases. we pass connString from mvc controller to  business layer methods to initialize new instance of dbContext to connect relevant client database. You can see in my method we used  <code>DbContext.Create(connString)</code> to create a connection with database always when this methods run. 
My problem is I can't use moq Framework for unit testing because of this situation. Is there a way to generalize this for dynamic connection string and move dbContext initialization outside the method?</p>
",https://stackoverflow.com/questions/51870821/how-to-make-entity-framework-dbcontext-generic-for-dynamic-connection-string,"['c#', 'asp.net-mvc', 'entity-framework', 'moq']",238,FALSE,1,0
How to unit test time based functions without adding parameters,"<p>I created a function that returns seconds left until the next occurrence of that time, but I came across a problem writing a unit test for it. How do people test this type of function that has a call to <code>datetime.now()</code> in it? </p>

<p>Adding another parameter (<code>current_time</code>) seems wrong just to test it as it changes the initial requirements of the function.</p>

<p>function to test is.</p>

<pre><code>from datetime import datetime, time, timedelta

def get_time_left(target_time):
    '''return float of number of seconds left until the target_time'''

    if not isinstance( target_time, time ):
        raise TypeError(""target_time must be datetime.time"")

    curr_time = datetime.now()
    target_datetime = datetime.combine( datetime.today(), target_time )
    if curr_time &gt; target_datetime:
        target_datetime = curr_time + timedelta(1)

    seconds_left = (curr_time - target_datetime).total_seconds()

    return seconds_left
</code></pre>

<p>The test for it is.</p>

<pre><code>class TestDTime(unittest.TestCase):

    def test_time_left(self):
        dt_now = datetime.now()
        tm_5sec_future = ( dt_now + timedelta(0,5) ).time()
        self.assertEqual( dtime.get_time_left(tm_5sec_future), 5.0)
</code></pre>

<p>The result is.</p>

<pre><code>======================================================================
FAIL: test_time_left (__main__.TestDTime)
----------------------------------------------------------------------
Traceback (most recent call last):
  File ""tests/ctatest.py"", line 37, in test_time_left
    self.assertEqual( dtime.get_time_left(tm_5sec_future), 5.0)
AssertionError: -4.999985 != 5.0
</code></pre>

<p>What is best approach to unit testing something like this without adding any args to the function?</p>
",https://stackoverflow.com/questions/50660497/how-to-unit-test-time-based-functions-without-adding-parameters,"['python', 'unit-testing', 'datetime', 'mocking', 'assert']",489,TRUE,3,1
How to import local scripts into jest test,"<p>I have some local scripts that are referenced in my index.html. As a result, my react components can access it globally without needing a proper definition.</p>

<p>During unit testing , it fails with undefined reference because it isn't imported.
The module in question is Kendo ui and is kept locally. How do I make kendo a global reference?</p>

<p>I attempted the following, as this worked for global jquery reference in my setupTests file.</p>

<pre><code>import * as kendo from '../public/scripts/kendo/kendo.all.min.js';
global.kendo = kendo;
</code></pre>

<p>However, the unit test just seems to hang and does not run.</p>

<p>The code calls it by</p>

<pre><code>// eslint-disable-next-line no-undef
return new kendo.data.HierarchicalDataSource({...options});
</code></pre>
",https://stackoverflow.com/questions/49925575/how-to-import-local-scripts-into-jest-test,"['javascript', 'reactjs', 'jestjs']",725,FALSE,3,0
"Unit test for server polling using RxJava, Kotlin","<p>I'm trying to create a test using JUnit and Mockito for the following scenario: make a call to the server, in case the response is not successful, retry the request. </p>

<pre><code>repository.uploadModel(model)
                .subscribeOn(schedulers.io())
                .observeOn(schedulers.ui())
                .repeatWhen (repeatTimer)
                .subscribe({
                    if (it.isSuccessful) {
                        mvpView?.showUploadComplete()
                    } else {
                        mvpView?.showGeneralUploadError()
                    }
                }, {
                     it.printStackTrace()
                })
</code></pre>

<p>So far I came up with this:</p>

<pre><code>val model = Mockito.mock(Model::class.java)
val errorResponse = Response.error&lt;Any&gt;(500, ResponseBody.create(null, """"))

whenever(repository.uploadModel(model))           
    .thenReturn(Flowable.just(errorResponse))

presenter?.uploadModel()
testScheduler?.triggerActions()

verify(view, atLeast(5)).pendingUpload()
</code></pre>

<p><strong>What actually happens</strong>: <code>showGeneralUploadError()</code> is called only once and then the test ends and fails.
<strong>What I want to happen</strong>: call <code>showGeneralUploadError()</code> multiple times</p>

<p>Extra info:</p>

<ol>
<li><code>repeatTimer</code> is defined as <code>{ it: Flowable&lt;Any&gt; -&gt; it.delay(0, TimeUnit.SECONDS)}</code> for unit testing</li>
<li><code>repeatTimer</code> is defined as <code>{ it: Flowable&lt;Any&gt; -&gt; it.delay(5, TimeUnit.SECONDS)}</code> for production</li>
<li>This is only sample code to demonstrate the problem, not actual code</li>
</ol>
",https://stackoverflow.com/questions/50863395/unit-test-for-server-polling-using-rxjava-kotlin,"['android', 'unit-testing', 'kotlin', 'mockito', 'rx-java2']",600,TRUE,0,2
Error when trying to use Simple-JNDI,"<p>For unit testing purposes, I'm trying to set up JNDI to connect to a HSQLDB without  using Tomcat. To do this I am using <a href=""https://github.com/h-thurow/Simple-JNDI"" rel=""nofollow noreferrer"">Simple-JNDI</a> and following this <a href=""http://%20http://www.briskbee.com/2010/07/setting-up-datasource-in-jndi.html"" rel=""nofollow noreferrer"">website</a>. </p>

<p>So first I created a class that will initialize the a JNDI Data Source:</p>

<pre><code>import org.hsqldb.jdbc.JDBCDataSource;    
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class JndiDataSource {
    public void Initialize() throws NamingException {
        // Create initial context
        System.setProperty(Context.INITIAL_CONTEXT_FACTORY, ""org.osjava.sj.MemoryContextFactory"");
        System.setProperty(""org.osjava.sj.jndi.shared"", ""true"");
        InitialContext ic = new InitialContext();

        ic.createSubcontext(""java:/comp/env/jdbc"");

        // Construct DataSource
        JDBCDataSource ds = new JDBCDataSource();
        ds.setDatabase(""jdbc:hsqldb:hsql://localhost/xdb"");
        ds.setUser(""SA"");
        ds.setPassword("""");

        // Put datasource in JNDI context
        ic.bind(""java:/comp/env/jdbc/myDS"", ds);
    }
}
</code></pre>

<p>Then in a unit test I'm calling <code>Initialize()</code> and just attempting to lookup the Data Source. </p>

<pre><code>import org.junit.jupiter.api.Test;    
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class JndiDataSourceTest {
    @Test
    public void testInitialize() throws NamingException {
        JndiDataSource jds = new JndiDataSource();
        jds.Initialize();

        InitialContext ic = new InitialContext();
        DataSource ds = (DataSource)ic.lookup(""java:/comp/env/jdbc/myDS"");
    }
}
</code></pre>

<p>Unfortunately, when I try to debug this unit test it fails on the lookup, <code>(DataSource)ic.lookup(""java:/comp/env/jdbc/myDS"");</code> The debugger says, </p>

<p><code>javax.naming.NameNotFoundException: java:/comp/env/jdbc/myDS</code></p>

<p>So the question is, what am I doing wrong?</p>
",https://stackoverflow.com/questions/51911367/error-when-trying-to-use-simple-jndi,"['java', 'unit-testing', 'jndi', 'hsqldb', 'in-memory-database']",2460,TRUE,0,2
Unit test in Node js,"<p>I'm learning unit testing in node js using Tape.js, and so far I only find it useful to test the result returned by a function, but what what about to test if a callback has been called exactly n times? </p>

<p>I have this function which calls a callback function n times:</p>

<pre><code>    const repeatCallback = (n, cb) =&gt; {
        for (let i = 0; i &lt; n; i++) {
            cb();
        }
    }

module.exports = repeatCallback;
</code></pre>

<p>And the tape test: </p>

<pre><code>const repeatCallback = require('./repeatCallback.js');
    const test = require('tape');



    test('repeat callback tests', (t) =&gt; {
    t.plan(3);
        repeatCallback(3, () =&gt; {console.log('callack called');})
    });
</code></pre>

<p>And I'm getting the error : not ok 1 plan != count</p>

<p>How do I update in my test the count to match the number of times that have been called?</p>

<p>THanks</p>
",https://stackoverflow.com/questions/50506592/unit-test-in-node-js,"['javascript', 'unit-testing', 'node.js-tape']",106,FALSE,0,1
system test - how to test database without saving data actually,"<p>I currently use   using (TransactionScope scope = new TransactionScope()) for 
 c# testing database insertion so that it doesn't actually save into database for unit testing. But for system testing which I am currently testing on different server to test the status code for different scenarios. Each time I run the test, it is actually saving data into database and next time I ran the test it is failing as it is duplicate record. I tried to use transaction scope , but doesn't seem to work. Please help.</p>
",https://stackoverflow.com/questions/53497682/system-test-how-to-test-database-without-saving-data-actually,"['c#', 'testing', 'system-testing']",244,FALSE,0,0
Jest React Redux Testing,"<p>I am new to redux and I want to know how to test Actions and Reducers.</p>

<p>I have attached a copy of both the files and would like anyone to help with a common pattern which I can use.</p>

<p>I am using Jest for unit testing.</p>

<p>URL is <a href=""http://localhost:30001"" rel=""nofollow noreferrer"">http://localhost:30001</a>.</p>

<p>Just want to know how the testing can be done and how I can use fetch in my test cases and what can I put as my expected result.</p>

<p>Actions page</p>

<pre><code>import {
  REQUEST_CHARITIES,
  REQUEST_PAYMENT,
  SHOW_DONATION_AMOUNT_LIST,
  UPDATE_DONATION_AMOUNT_LIST,
  URL,
  PAY_NOW,
  UPDATE_MESSAGE,
  UPDATE_TOTAL_DONATE
} from './const';

//get list of all the charities
export function requestCharitiesList() {
  const request = fetch(`${URL}/charities`, {
      method: 'GET'
  }).then(response =&gt; response.json())
  return {
      type: REQUEST_CHARITIES,
      payload: request
  }
}

//get list of all payment amount
export function requestDonationAmount() {
  return {
      type: REQUEST_PAYMENT,
      payload: [{
              ""id"": 0,
              ""price"": 10
          },
          {
              ""id"": 1,
              ""price"": 20
          },
          {
              ""id"": 2,
              ""price"": 50
          },
          {
              ""id"": 3,
              ""price"": 100
          },
          {
              ""id"": 4,
              ""price"": 500
          },
      ]
  }
}

//get the total count of charities and update the payment options list visibility
export function showDonationList() {
  const paymentOptionsShow = []
  const request = fetch(`${URL}/charities`, {
      method: 'GET'
  }).then( response =&gt;  response.json())
  request.then(function(result) {
    if(result.length &gt;= 1){
      let arrayLength = result.length

      for( var i = 0 ; i &lt; arrayLength ; i++ ) {
        paymentOptionsShow.push({active: false });
      }  
    }
 })

  return {
      type: SHOW_DONATION_AMOUNT_LIST,
      payload: paymentOptionsShow
  }
}

//to show and hide the payment options for each card
export function updateDonationList(list,id){
  return {
    type: UPDATE_DONATION_AMOUNT_LIST,
    payload: {
        ""list"": list,
        ""id"": id
        }
  }
}


//post the current paid amount
export function payNow(id, amount, currency) {
  const request = fetch(`${URL}/payments`, {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: `{ ""charitiesId"": ${id}, ""amount"": ${amount}, ""currency"": ""${currency}"" }`
  })
  .then(response =&gt; response.json())
  return {
    type: PAY_NOW,
    payload: request
  }
}

//show thank you message
export function updateMessage(message) {
  return {
    type: UPDATE_MESSAGE,
    message: message
  }
}

//get the total number of payments made
export function summaryTotal() {
  const request = fetch(`${URL}/payments`,
    { method: 'GET' }).then(response =&gt; response.json())
  return {
    type: UPDATE_TOTAL_DONATE,
    payload: request
  }
}
</code></pre>

<p>One of my Reducers </p>

<pre><code>import {
  REQUEST_CHARITIES
} from '../actions/const'

export default function (state = null, action) {
  switch (action.type) {
    case REQUEST_CHARITIES:
      return action.payload
    default:
      return state;
  }
}
</code></pre>
",https://stackoverflow.com/questions/52866051/jest-react-redux-testing,"['reactjs', 'redux', 'react-redux', 'jestjs', 'jest-fetch-mock']",580,FALSE,0,1
C# Msbuild code coverage hard halt if not met threshold,"<p>We have a c# solution with more than one projects. Project uses msbuild for packaging, run Nunit for unit testing. What we don't have at the moment is to define code coverage threshold for each project and to fail msbuild if code coverage is below threshold limit. This comes out of box in java project using maven and cobertura as plug-in. 
 Any such tool in dot net world. </p>

<p>We are using 
- Visual Studio 2017 Professional 
- Msbuild 15.3.409.57025
- Resharper ultimate 2017.2
- DotNet Framework 4.6.2
- Nunit 2.5.7</p>
",https://stackoverflow.com/questions/50580397/c-msbuild-code-coverage-hard-halt-if-not-met-threshold,"['.net', 'c#-4.0', 'msbuild', 'nunit']",337,TRUE,0,1
Angular 2+ - How to mockup constant class used for environment variables,"<p>I was wondering if someone could help me on this topic, I'm typing down some unit tests regarding to some functionalities that are done depending on the environment that's running at the moment. </p>

<p>This is my source code of the component I want to create the unit test:</p>

<pre><code>import { Component, OnInit } from '@angular/core';

// DEV environment
import { environment } from '@env/environment';
// PROD environment
// import { environment } from '@env/environment.prod';
import { Logger } from '@app/core/logger/logger.service';
import { I18nService } from '@app/core/language/i18n.service';

let log: Logger;

@Component({
  selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.scss'],
   providers: [I18nService]
 })

export class AppComponent implements OnInit {

  constructor(private i18nService: I18nService) {
     log  = new Logger('X');
  }

  ngOnInit() {
    // Setup logger
    if (environment.isProduction) {
        Logger.enableProductionMode();
    }

    log.debug('init');

    // Setup translations
    this.i18nService.init(environment.defaultLanguage, environment.supportedLanguages);
  }
</code></pre>

<p>And and this is the unit testing:</p>

<pre><code> import * as environmentDEV from '@env/environment';
 import * as environmentPRO from '@env/environment.prod';
 ...

 let component: AppComponent;
 let fixture: ComponentFixture&lt;AppComponent&gt;;

 // Spies declarations
 let spy_initI8nServiceMethod: jasmine.Spy;
 let spy_debugLoggerAttr: jasmine.Spy;
 let spy_enableProductionModeLoggerMethod: jasmine.Spy;

 describe('AppComponent', () =&gt; {
       beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
          imports: [TranslateModule.forRoot()],
          declarations: [AppComponent],
          providers: [I18nService]
        });
        TestBed.compileComponents();
        fixture = TestBed.createComponent(AppComponent);
        component = fixture.debugElement.componentInstance;
       }));

       beforeEach(inject([I18nService],
                        (_i18nService: I18nService) =&gt; {

        i18nService = _i18nService;

        // Create spies
        // Spies
        spy_initI8nServiceMethod = spyOn(I18nService.prototype, 'init');
        spy_debugLoggerAttr = spyOn(Logger.prototype, 'debug');
        spy_enableProductionModeLoggerMethod = spyOn(Logger, 'enableProductionMode');
       }));

       it('should component init on PRO environment',
           async(() =&gt; {

        spyOn(environment, 'isProduction').and.returnValue(environmentPRO.environment.isProduction);
        spyOn(environment, 'defaultLanguage').and.returnValue(environmentPRO.environment.defaultLanguage);
        spyOn(environment, 'supportedLanguages').and.returnValue(environmentPRO.environment.supportedLanguages);

        component.ngOnInit();

        expect(spy_enableProductionModeLoggerMethod).toHaveBeenCalledBefore(spy_debugLoggerAttr);
        expect(spy_debugLoggerAttr).toHaveBeenCalledBefore(spy_initI8nServiceMethod);
        expect(spy_initI8nServiceMethod).toHaveBeenCalledWith(environmentPRO.environment.defaultLanguage,
                                                              environmentPRO.environment.supportedLanguages);
       }));
 });
</code></pre>

<p>My problem is that I'm unable to force constant environment to return certain values, I've both tried both spyOn &amp; spyOnAttribute with same result. What's wrong here? shall I try another approach?</p>
",https://stackoverflow.com/questions/52492864/angular-2-how-to-mockup-constant-class-used-for-environment-variables,"['angular', 'typescript', 'jasmine', 'karma-jasmine', 'constants']",868,TRUE,0,1
Mocking a method with Action&lt;T&gt;,"<p>I am new with Unit Testing, would be happy to know if I am making any mistake or not proceeding the right direction.</p>

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

<p>I am trying to test a method (<code>MethodUnderTest</code>) which calls another method(<code>MethodWithAction</code>) which takes <code>Action&lt;T&gt;</code> as argument.
I want to mock <code>MethodWithAction</code>, but test the logic based on the return value.</p>

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

<pre><code>interface IInterface
{
    void MethodWithAction(Action&lt;string&gt; action);
}

class MyClass : IInterface
{
    public void MethodWithAction(Action&lt;string&gt; action)
    {
        string sampleString = ""Hello there"";
        action(sampleString);
    }
}

class ClassUnderTest
{
    public IInterface Obj = new MyClass();
    public string MethodUnderTest()
    {
        string stringToBeTested = string.Empty;

        Obj.MethodWithAction(str =&gt;
        {
            if (str.Contains("".""))
                stringToBeTested = string.Empty;
            else
                stringToBeTested = str.Replace("" "", string.Empty);
        });
        return stringToBeTested;
    }
}
</code></pre>

<p>My test method goes like this:</p>

<pre><code>[TestMethod]
[DataRow(""Hello, World"", ""Hello,World"")]
[DataRow(""Hello, World."","""")]
[DataRow(""Hello"", ""Hello"")]
public void MethodUnderTestReturnsCorrectString(string sampleString, string expected)
{
    var mockObj = new Mock&lt;IInterface&gt;();
    mockObj.Setup(m=&gt;m.MethodWithAction(It.IsAny&lt;Action&lt;string&gt;&gt;))
    .Callback(???);
    ClassUnderTest sut = new ClassUnderTest();
    sut.Obj=mockObj.Object;
    string actual = sut.MethodUnderTest();
    Assert.Equal(expected, actual);
 }
</code></pre>

<p>I would like to know what goes at the place of <code>???</code> in the test, or is there entirely different approach for this problem?</p>
",https://stackoverflow.com/questions/50586196/mocking-a-method-with-actiont,"['c#', '.net', 'unit-testing', 'mocking', 'moq']",2691,TRUE,3,2
django 2.1.4 migration fails with &quot;DETAIL: Key columns &quot;xxx&quot; and &quot;yyy&quot; are of incompatible types: integer and character varying&quot;,"<p>I'm trying to upgrade a django 1.11 based service to latest django 2.1.4.
When running migrations ( during unit testing ) I now get the following error in an existing migration of my django application that did not happen before upgrade to latest django version !?</p>

<p><code>DETAIL:  Key columns ""xxx"" and ""yyy"" are of incompatible types: integer and character varying</code>.</p>

<p><strong>How can such an existing django migration be fixed when upgrading to latest django version ?</strong></p>

<p>The models (snippet) changed from</p>

<pre><code>class Aaa(models.model):
    # id based on default primary key =&gt; integer based

class Bbb(models.model):
    # id based on default primary key =&gt; integer based
    aaa = models.ForeignKey(Aaa, on_delete=models.CASCADE)
</code></pre>

<p>to</p>

<pre><code>class Aaa(models.model):
    id = models.CharField(primary_key=True, max_length=36, editable=False)

class Bbb(models.model):
    id = models.CharField(primary_key=True, max_length=36, editable=False)
    aaa = models.ForeignKey(Aaa, on_delete=models.CASCADE)
</code></pre>

<p>The callstack of the exception during the migration (from scratch) when setting up the unit-test environment looks like the following :</p>

<pre><code>foo_aaa__________ ERROR at setup of ViewTests.test_aaa ___________

self = &lt;django.db.backends.utils.CursorWrapper object at 0x7fa7ac64a240&gt;
sql = 'ALTER TABLE ""foo_aaa"" ALTER COLUMN ""id"" TYPE varchar(36) USING ""id""::varchar(36)'
params = []
ignored_wrapper_args = (False, {'connection': &lt;django.db.backends.postgresql.base.DatabaseWrapper object at 0x7fa7b5235780&gt;, 'cursor': &lt;django.db.backends.utils.CursorWrapper object at 0x7fa7ac64a240&gt;})

    def _execute(self, sql, params, *ignored_wrapper_args):
        self.db.validate_no_broken_transaction()
        with self.db.wrap_database_errors:
            if params is None:
                return self.cursor.execute(sql)
            else:
&gt;               return self.cursor.execute(sql, params)
E               psycopg2.ProgrammingError: foreign key constraint ""foo_bbb_aaa_id_1e82a2eb_fk_foo"" cannot be implemented
E               DETAIL:  Key columns ""aaa_id"" and ""id"" are of incompatible types: integer and character varying.

/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py:85: ProgrammingError

The above exception was the direct cause of the following exception:

request = &lt;SubRequest '_django_setup_unittest' for &lt;TestCaseFunction 'test_aaa'&gt;&gt;
django_db_blocker = &lt;pytest_django.plugin._DatabaseBlocker object at 0x7fa7b83b9ba8&gt;

    @pytest.fixture(autouse=True, scope=""class"")
    def _django_setup_unittest(request, django_db_blocker):
        """"""Setup a django unittest, internal to pytest-django.""""""
        if django_settings_is_configured() and is_django_unittest(request):
            request.getfixturevalue(""django_test_environment"")
&gt;           request.getfixturevalue(""django_db_setup"")

/usr/local/lib/python3.6/site-packages/pytest_django/plugin.py:486: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
/usr/local/lib/python3.6/site-packages/six.py:692: in reraise
    raise value.with_traceback(tb)
/usr/local/lib/python3.6/site-packages/pytest_django/fixtures.py:110: in django_db_setup
    **setup_databases_args
/usr/local/lib/python3.6/site-packages/django/test/utils.py:174: in setup_databases
    serialize=connection.settings_dict.get('TEST', {}).get('SERIALIZE', True),
/usr/local/lib/python3.6/site-packages/django/db/backends/base/creation.py:68: in create_test_db
    run_syncdb=True,
/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py:148: in call_command
    return command.execute(*args, **defaults)
/usr/local/lib/python3.6/site-packages/django/core/management/base.py:353: in execute
    output = self.handle(*args, **options)
/usr/local/lib/python3.6/site-packages/django/core/management/base.py:83: in wrapped
    res = handle_func(*args, **kwargs)
/usr/local/lib/python3.6/site-packages/django/core/management/commands/migrate.py:203: in handle
    fake_initial=fake_initial,
/usr/local/lib/python3.6/site-packages/django/db/migrations/executor.py:117: in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
/usr/local/lib/python3.6/site-packages/django/db/migrations/executor.py:147: in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
/usr/local/lib/python3.6/site-packages/django/db/migrations/executor.py:244: in apply_migration
    state = migration.apply(state, schema_editor)
/usr/local/lib/python3.6/site-packages/django/db/migrations/migration.py:124: in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
/usr/local/lib/python3.6/site-packages/django/db/migrations/operations/fields.py:216: in database_forwards
    schema_editor.alter_field(from_model, from_field, to_field)
/usr/local/lib/python3.6/site-packages/django/db/backends/base/schema.py:523: in alter_field
    old_db_params, new_db_params, strict)
/usr/local/lib/python3.6/site-packages/django/db/backends/postgresql/schema.py:122: in _alter_field
    new_db_params, strict,
/usr/local/lib/python3.6/site-packages/django/db/backends/base/schema.py:663: in _alter_field
    params,
/usr/local/lib/python3.6/site-packages/django/db/backends/base/schema.py:133: in execute
    cursor.execute(sql, params)
/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py:68: in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py:77: in _execute_with_wrappers
    return executor(sql, params, many, context)
/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py:85: in _execute
    return self.cursor.execute(sql, params)
/usr/local/lib/python3.6/site-packages/django/db/utils.py:89: in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = &lt;django.db.backends.utils.CursorWrapper object at 0x7fa7ac64a240&gt;
sql = 'ALTER TABLE ""foo_aaa"" ALTER COLUMN ""id"" TYPE varchar(36) USING ""id""::varchar(36)'
params = []
ignored_wrapper_args = (False, {'connection': &lt;django.db.backends.postgresql.base.DatabaseWrapper object at 0x7fa7b5235780&gt;, 'cursor': &lt;django.db.backends.utils.CursorWrapper object at 0x7fa7ac64a240&gt;})

    def _execute(self, sql, params, *ignored_wrapper_args):
        self.db.validate_no_broken_transaction()
        with self.db.wrap_database_errors:
            if params is None:
                return self.cursor.execute(sql)
            else:
&gt;               return self.cursor.execute(sql, params)
E               django.db.utils.ProgrammingError: foreign key constraint ""foo_bbb_aaa_id_1e82a2eb_fk_foo"" cannot be implemented
E               DETAIL:  Key columns ""aaa_id"" and ""id"" are of incompatible types: integer and character varying.

/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py:85: ProgrammingError
_____ ERROR at setup of ViewTests.test_bar ______

self = &lt;django.db.backends.utils.CursorWrapper object at 0x7fa7ac64a240&gt;
sql = 'ALTER TABLE ""foo_aaa"" ALTER COLUMN ""id"" TYPE varchar(36) USING ""id""::varchar(36)'
params = []
ignored_wrapper_args = (False, {'connection': &lt;django.db.backends.postgresql.base.DatabaseWrapper object at 0x7fa7b5235780&gt;, 'cursor': &lt;django.db.backends.utils.CursorWrapper object at 0x7fa7ac64a240&gt;})

    def _execute(self, sql, params, *ignored_wrapper_args):
        self.db.validate_no_broken_transaction()
        with self.db.wrap_database_errors:
            if params is None:
                return self.cursor.execute(sql)
            else:
&gt;               return self.cursor.execute(sql, params)
E               psycopg2.ProgrammingError: foreign key constraint ""foo_bbb_aaa_id_1e82a2eb_fk_foo"" cannot be implemented
E               DETAIL:  Key columns ""aaa_id"" and ""id"" are of incompatible types: integer and character varying.

/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py:85: ProgrammingError

The above exception was the direct cause of the following exception:

tp = &lt;class 'django.db.utils.ProgrammingError'&gt;, value = None, tb = None

    def reraise(tp, value, tb=None):
        try:
            if value is None:
                value = tp()
            if value.__traceback__ is not tb:
&gt;               raise value.with_traceback(tb)

/usr/local/lib/python3.6/site-packages/six.py:692: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
/usr/local/lib/python3.6/site-packages/pytest_django/plugin.py:486: in _django_setup_unittest
    request.getfixturevalue(""django_db_setup"")
/usr/local/lib/python3.6/site-packages/six.py:692: in reraise
    raise value.with_traceback(tb)
/usr/local/lib/python3.6/site-packages/pytest_django/fixtures.py:110: in django_db_setup
    **setup_databases_args
/usr/local/lib/python3.6/site-packages/django/test/utils.py:174: in setup_databases
    serialize=connection.settings_dict.get('TEST', {}).get('SERIALIZE', True),
/usr/local/lib/python3.6/site-packages/django/db/backends/base/creation.py:68: in create_test_db
    run_syncdb=True,
/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py:148: in call_command
    return command.execute(*args, **defaults)
/usr/local/lib/python3.6/site-packages/django/core/management/base.py:353: in execute
    output = self.handle(*args, **options)
/usr/local/lib/python3.6/site-packages/django/core/management/base.py:83: in wrapped
    res = handle_func(*args, **kwargs)
/usr/local/lib/python3.6/site-packages/django/core/management/commands/migrate.py:203: in handle
    fake_initial=fake_initial,
/usr/local/lib/python3.6/site-packages/django/db/migrations/executor.py:117: in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
/usr/local/lib/python3.6/site-packages/django/db/migrations/executor.py:147: in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
/usr/local/lib/python3.6/site-packages/django/db/migrations/executor.py:244: in apply_migration
    state = migration.apply(state, schema_editor)
/usr/local/lib/python3.6/site-packages/django/db/migrations/migration.py:124: in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
/usr/local/lib/python3.6/site-packages/django/db/migrations/operations/fields.py:216: in database_forwards
    schema_editor.alter_field(from_model, from_field, to_field)
/usr/local/lib/python3.6/site-packages/django/db/backends/base/schema.py:523: in alter_field
    old_db_params, new_db_params, strict)
/usr/local/lib/python3.6/site-packages/django/db/backends/postgresql/schema.py:122: in _alter_field
    new_db_params, strict,
/usr/local/lib/python3.6/site-packages/django/db/backends/base/schema.py:663: in _alter_field
    params,
/usr/local/lib/python3.6/site-packages/django/db/backends/base/schema.py:133: in execute
    cursor.execute(sql, params)
/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py:68: in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py:77: in _execute_with_wrappers
    return executor(sql, params, many, context)
/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py:85: in _execute
    return self.cursor.execute(sql, params)
/usr/local/lib/python3.6/site-packages/django/db/utils.py:89: in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = &lt;django.db.backends.utils.CursorWrapper object at 0x7fa7ac64a240&gt;
sql = 'ALTER TABLE ""foo_aaa"" ALTER COLUMN ""id"" TYPE varchar(36) USING ""id""::varchar(36)'
params = []
ignored_wrapper_args = (False, {'connection': &lt;django.db.backends.postgresql.base.DatabaseWrapper object at 0x7fa7b5235780&gt;, 'cursor': &lt;django.db.backends.utils.CursorWrapper object at 0x7fa7ac64a240&gt;})

    def _execute(self, sql, params, *ignored_wrapper_args):
        self.db.validate_no_broken_transaction()
        with self.db.wrap_database_errors:
            if params is None:
                return self.cursor.execute(sql)
            else:
&gt;               return self.cursor.execute(sql, params)
E               django.db.utils.ProgrammingError: foreign key constraint ""foo_bbb_aaa_id_1e82a2eb_fk_foo"" cannot be implemented
E               DETAIL:  Key columns ""aaa_id"" and ""id"" are of incompatible types: integer and character varying.

/usr/local/lib/python3.6/site-packages/django/db/backends/utils.py:85: ProgrammingError
</code></pre>
",https://stackoverflow.com/questions/53629057/django-2-1-4-migration-fails-with-detail-key-columns-xxx-and-yyy-are-of-in,['django'],876,FALSE,0,1
Should i mock List for stream operations?,"<p>I have a line of code in function which applies stream operations on an <code>ArrayList</code> as:</p>

<pre><code>List&lt;Entity&gt; list = xyz(); 

long result = list.stream().map(n -&gt; n.getData()).filter(n -&gt; n == 1).count();
</code></pre>

<p>Now when i write a test for this method should i do like:</p>

<pre><code>@Mock
private List&lt;Entity&gt; list;

//inside the test method
when(list.stream().map(any()).filter(any()).count()).thenReturn(someValue);
</code></pre>

<p>What is coming to my mind is that when we are calling stream operations in our code, we are basically going out of our class to call these functions. Since it is unit testing we should remain inside our module. Please clarify if i have some misconceptions. If we do not need to mock <code>List</code>, then why?</p>
",https://stackoverflow.com/questions/53045470/should-i-mock-list-for-stream-operations,"['java', 'unit-testing', 'mockito', 'junit4']",7138,TRUE,0,2
Is it possible to unit test a structural directive the way we test an attribute directive in angular 2,"<p>I have both attribute and structural directives in my project. I am able to test the attribute directive by creating a test component and using the attribute directive in it's template.</p>

<pre><code>@Component({
    template: `&lt;input [myAttrDir]=""{prop1: val1, prop2: val2}""/&gt;`
})
export class TestComponent {
}

@Directive({
    selector: '[myAttrDir]'
})
export class MyAttrDirective {
    @Input('myAttrDir') testProp;
}
</code></pre>

<p>The testing module looks like:</p>

<pre><code>TestBed.configureTestingModule({
    declarations: [MyAttrDirective, TestComponent]
})
</code></pre>

<p>I get hold of directive this way:</p>

<pre><code>fixture = TestBed.createComponent(TestComponent)
directive = fixture.debugElement.query(By.directive(MyAttrDirective))
</code></pre>

<p>I am able to get the instance of attribute directive.
However when I try this same way to test structural directive, I get null value of directive.
I have checked out official documentation as well and only found the unit testing of attribute directive. The structural directive testing methodology is not given anywhere.</p>

<pre><code>@Component({
    template: `&lt;input *myStrucDir=""{prop1: val1, prop2: val2}""/&gt;`
})
export class TestComponent {
}
@Directive({
    selector: '[myStrucDir]'
})
export class MyStrucDirective {
    @Input set myStrucDir(data);
    constructor(
        private templateRef: TemplateRef&lt;any&gt;,
        private vcr: ViewContainerRef,
        private cfr: ComponentFactoryResolver,
        private el: ElementRef) {

    }
}
TestBed.configureTestingModule({
    declarations: [MyStrucDirective, TestComponent]
})
fixture = TestBed.createComponent(TestComponent)
directive = fixture.debugElement.query(By.directive(MyStrucDirective))
</code></pre>

<p>Is it possible to test structural directive in any way?</p>
",https://stackoverflow.com/questions/51839072/is-it-possible-to-unit-test-a-structural-directive-the-way-we-test-an-attribute,"['angular', 'angular-directive']",3637,TRUE,13,1
How to Mock a trackable repository?,"<p>I am doing unit testing for the first time.I want to mock a Trackable Repository. Is it different from mocking normal repository? I am in doubt because I was creating a simple repository and my method to be tested which uses trackable repository  was not accepting it. Can u provide a simple example to mock a trackable repository.
I am passing the repository like this using DI:</p>

<pre><code>   public CountryService(ITrackableRepository&lt;Country&gt; repository) : base(repository)
    {
    }
</code></pre>

<p>and I want to test if the country is inserted by the Upsert Method:</p>

<pre><code>public void UpsertCountries(Country[] countries)
        {
            countries.ToList().ForEach(country =&gt;
            {
                if (Repository.Queryable().Any(c =&gt; c.ForeignId == country.ForeignId))
                {
                    UpdateCountry(country);
                }
                else
                {
                    Repository.Insert(country);
                }
            });
        }
</code></pre>

<p>Thanks in advance....</p>
",https://stackoverflow.com/questions/51362597/how-to-mock-a-trackable-repository,"['c#', 'unit-testing', 'mocking']",69,TRUE,0,1
Xamarin DependencyService Get() method NULL when using wrapper,"<p>I have created a DependencyServiceWrapper so I can replace it in unit tests following the guide here: <a href=""https://robgibbens.com/unit-testing-with-xamarin-forms-dependencyservice/"" rel=""nofollow noreferrer"">https://robgibbens.com/unit-testing-with-xamarin-forms-dependencyservice/</a> </p>

<p>My wrapper is located in my Portable project and looks like this</p>

<pre><code>public class DependencyServiceWrapper : IDependencyService
    {
        public T Get&lt;T&gt;() where T : class
        {
            // The wrapper will simply pass everything through to the real Xamarin.Forms DependencyService class when not unit testing
            return DependencyService.Get&lt;T&gt;();
        }
    }
</code></pre>

<p>Then my viewModel simply news this up in the constructor as shown below</p>

<pre><code>public TasksListViewModel(Page page) : this(page, new DependencyServiceWrapper())
        {
        }

        public TasksListViewModel(Page page, IDependencyService dependencyService)
        {
            this.page = page;
            this.connectivityService = dependencyService.Get&lt;IConnectivityService&gt;(); 
            this.taskRepo = dependencyService.Get&lt;ITaskRepository&gt;(); // NULL HERE
            this.RowClicked = new Command&lt;Guid&gt;(OnTaskSelected); // NULL HERE
            this.RefreshList = new Command(RefreshTasks);
        }
</code></pre>

<p>Previously in my ViewModel I had</p>

<pre><code>public IConnectivityService ConnectivityService =&gt; DependencyService.Get&lt;IConnectivityService&gt;(); // Returns correct object (so I know it's registered correctly).
</code></pre>

<p>Can anyone advise why I get NULL. When I call the wrapped service (above) I get NULL, yet doing the wrapped call directly from the ViewModel works fine.</p>

<p>Thanks,
David</p>
",https://stackoverflow.com/questions/50507652/xamarin-dependencyservice-get-method-null-when-using-wrapper,['xamarin.forms'],673,FALSE,0,0
C++ Metaprogramming: Generating a byte sequence based on type/value input?,"<p>So this might be one of those &quot;that's obviously easy&quot; or &quot;obviously impossible&quot; questions..</p>
<p>But imagine a simple buffer protocol where the data is prefixed by a byte indicating the type. So you'd have <code>04 00</code> for a false bool and <code>02 00 00 00 01</code> for a uint32_t with a value of 1.</p>
<p>Would it be possible to serialize data at compiletime so that <code>Serialize(false, true, uint32_t(3));</code> returns a sequence like <code>04 00 04 01 02 00 00 00 03</code>?</p>
<p>If so, could one create prepared statements like that would just have zeroes in the sequence that could be filled at runtime? As well as maybe even doing basic unit-testing like <code>static_assert(Deserialize&lt;bool, bool&gt;(&quot;\x04\x01\x04\x00&quot;)[0] == true, &quot;Error&quot;);</code></p>
<pre><code>// e.g something like this.
template&lt;typename T&gt; constexpr uint8_t Prefix()
{
    if constexpr (std::is_same_v&lt;T, bool&gt;) return 0x04;
    if constexpr (std::is_same_v&lt;T, uint32_t&gt;) return 0x02;
    return 0x00;
};
template &lt;typename T&gt; ctString Write(T Value)
{
    ctString Temp{};
    Temp += Write(Prefix&lt;T&gt;());
    Temp += /* something sizeof(Value) */;
    return Temp;
};
template &lt;typename... Args&gt; ctString Serialize(std::tuple&lt;Args...&gt; Input)
{
    ctString Temp{};
    std::apply([&amp;](auto Argument) { Temp += Write(Argument); }, Input);
    return Temp;
};

constexpr auto Message = Serialize(false, true, uint32_t(3));
</code></pre>
",https://stackoverflow.com/questions/53728566/c-metaprogramming-generating-a-byte-sequence-based-on-type-value-input,"['c++', 'serialization', 'deserialization', 'metaprogramming', 'c++17']",255,TRUE,2,2
NodeJS : How do I unit test an Async function that depends on other Async calls,"<p>I have a service that I inject a mongoose model into and then this service is used by my express routes to do certain functions. I have been stumped by how to unit test the below code, as there are multiple async calls to retrieve DB data to make some calculations and then return the result.</p>

<p>I am new to async unit testing and am using Jest runner with sinon.</p>

<pre><code>// Service.ts
export default class Service {
    constructor(private dbModel){}

    public async problemFunc(arg1, arg2, arg3) {
        // validate args
        let data1;
        let data2;
        let data3;
        try {
            data1 = await SomeOtherService1.getData();
        }
        catch(e) {
            return e;
        }
        try {
            data2 = await SomeOtherService2.getData();
        }
        catch(e) {
            return e;
        }

        try {
            data3 = await this.dbModel
                    .findById(arg1)
                    .where('some_field')
                    .exists(false);
        }
        catch(e) {
            return e;
        }

        const calcResult = CalculationService.calc(arg1, data1, data2, data3);

        if (calcResult) {
            await this.dbModel.findByIdAndUpdate(arg1, calcResult);
            return this.dbModel.findById(arg1);
        } else {
            return new Error('Fail');
        }
    }
}
</code></pre>

<p>It would be most helpful if someone could explain how to unit test such a complex (in my opinion complex) function.</p>
",https://stackoverflow.com/questions/50366274/nodejs-how-do-i-unit-test-an-async-function-that-depends-on-other-async-calls,"['node.js', 'unit-testing', 'mongoose', 'jestjs', 'sinon']",5204,TRUE,2,1
Import Angular unit test report into Sonarqube,"<p><strong>Context</strong></p>

<p>In an Angular5 project using karma and jasmine for unit testing, I am generating this report file for my unit tests using karma-sonarqube-unit-reporter.</p>

<pre><code>&lt;testExecutions version=""1""&gt;
  &lt;file path=""src/app/app.component.spec.ts""&gt;
    &lt;testCase name=""app/app.component.spec.ts should create the app"" duration=""314""/&gt;
    &lt;testCase name=""app/app.component.spec.ts should have as title 'Projet de test Angular5'"" duration=""104""/&gt;
    &lt;testCase name=""src/app/app.component.spec.ts should render title in a h1 tag"" duration=""114""/&gt;
  &lt;/file&gt;
  &lt;file path=""src/app/client-add/client-add.component.spec.ts""&gt;
    &lt;testCase name=""client-add/client-add.component.spec.ts should create"" duration=""107""/&gt;
  &lt;/file&gt;
  &lt;file path=""app/client.service.spec""&gt;
    &lt;testCase name=""app/client.service.spec #getClients should return an Observable&amp;lt;Client[]&gt;"" duration=""38""/&gt;
  &lt;/file&gt;
  &lt;file path=""src/app/message.service""&gt;
    &lt;testCase name=""app/message.service should be created"" duration=""35""/&gt;
  &lt;/file&gt;
&lt;/testExecutions&gt;
</code></pre>

<p>But when I import it into Sonarqube (v6.7) (via Jenkins), I get the following</p>

<pre><code>INFO: Sensor Generic Test Executions Report
WARN: Property 'sonar.genericcoverage.unitTestReportPaths' is deprecated. Please use 'sonar.testExecutionReportPaths' instead.
INFO: Parsing C:\Users\adminpp\.jenkins\workspace\ELIS JustElis Beta WEB\reports\ut_report.xml
INFO: Imported test execution data for 0 files
INFO: Test execution data ignored for 4 unknown files, including:
src/app/app.component.spec.ts
src/app/client-add/client-add.component.spec.ts
src/app/client.service.spec
src/app/message.service
INFO: Sensor Generic Test Executions Report (done) | time=110ms
</code></pre>

<p>Here are my sonar properties for excluding and including sources and test codes.</p>

<pre><code>sonar.sourceEncoding=UTF-8
sonar.sources=.
sonar.exclusions=**/node_modules/** 
sonar.test.inclusions = **/*.spec.ts
sonar.import_unkown_files=true
sonar.typescript.lcov.reportPaths=coverage/lcov.info
sonar.testExecutionReportPaths=reports/ut_report.xml
</code></pre>

<p>I checked and I have my *.spec.ts files where they are supposed to be.</p>

<p><strong>Questions</strong></p>

<p>Why Sonarqube doesn't find my files?</p>

<p>Have I missed a property or an important step?</p>

<p>(Is this property <code>sonar.test.inclusions = **/*.spec.ts</code> important?)</p>
",https://stackoverflow.com/questions/49539155/import-angular-unit-test-report-into-sonarqube,"['javascript', 'angular', 'unit-testing', 'sonarqube', 'karma-jasmine']",6018,TRUE,2,1
Testing with java owner aeonbits,"<p>I've been using java OWNER for property based configuration.</p>

<p>I've create a static method </p>

<pre><code>public static final ApplicationConfiguration config = ConfigFactory.create(ApplicationConfiguration.class,
        System.getProperties(), System.getenv());
</code></pre>

<p>and I import the class everywhere I need conf. </p>

<p>Needless to say, unit testing is a PITA. I couldn't find a good way of override the values in the configuration.</p>

<p>I would like to avoid passing the config as a dependency in every class.
It adds a lot of verbosity and it doesn't make sense from a design point of view.
Same applies for calling the config factory in every class</p>

<pre><code>ApplicationConfiguration config = ConfigFactory.create(ApplicationConfiguration.class,
        System.getProperties(), System.getenv());
</code></pre>

<p>Have you got any suggestion? is there a best practice?</p>
",https://stackoverflow.com/questions/52188820/testing-with-java-owner-aeonbits,"['java', 'unit-testing', 'testing', 'owner']",2247,TRUE,2,2
How to stub/mock submodules of a require of nodejs using sinon,"<p>I am using sinon as for unit testing a nodejs(Hapijs) functionality. This function is in index.js. I am include the index.js in my test file as </p>

<pre><code>    var index=require('./index.js');
</code></pre>

<p>But again inside the index.js there is require</p>

<pre><code>    var library= require('./library.js')
</code></pre>

<p>Again the library.js has the require of a third part functionality</p>

<pre><code>     var googlelib=require('googlelib')
</code></pre>

<p>Now when I run my testfile testfunc.js below</p>

<pre><code>    var index= require('./index.js');
    var assert = require('assert');
    var sinon = require('sinon');
    var proxyquire= require('proxyquire');
</code></pre>

<p>I get the below error </p>

<pre><code>    Error: Cannot find module './library'
    at Function.Module._resolveFilename (module.js:555:15)
    at Function.Module._load (module.js:482:25)
    at Module.require (module.js:604:17)
    at require (internal/module.js:11:18)
</code></pre>

<p>I would like to know if there is any way I can stub the inner require library.js of index.js (as there are many requires inside index.js and many requires of requires)</p>
",https://stackoverflow.com/questions/48115128/how-to-stub-mock-submodules-of-a-require-of-nodejs-using-sinon,"['javascript', 'node.js', 'unit-testing', 'mocha.js', 'sinon']",2346,TRUE,2,1
Cannot pass Testify Mock object error,"<p>Hi I'm trying to mock a struct in GO. I'm using testify to do this. But I can't seem to get it to work and don't now what I'm doing wrong. Below is the sample main.go and main_test.go file I have</p>

<pre><code>// Arithmetic ...
type Arithmetic interface {
    Add(int, int) int
    Subtract(int, int) int
}

// MathOperation ...
type MathOperation struct {}

// GetNewArithmetic ...
func GetNewArithmetic(obj Arithmetic) Arithmetic {
    if obj != nil {
        return obj
    }

    return MathOperation{}
}

// Add ...
func (a MathOperation) Add(num1 int, num2 int) int {
    return num1 + num2
}

// Subtract ...
func (a MathOperation) Subtract(num1 int, num2 int) int {
    return num1 - num2
}
</code></pre>

<p>And here is my test file</p>

<pre><code>import (
    ""testing""

    ""github.com/stretchr/testify/assert""
    ""github.com/stretchr/testify/mock""
)

type MyMock struct {
    mock.Mock
}

func (m *MyMock) Add(num1 int, num2 int) int {
    args := m.Called(num1, num2)
    return args.Int(0) + args.Int(1)
}

func (m *MyMock) Subtract(num1 int, num2 int) int {
    args := m.Called(num1, num2)
    return args.Int(0) + args.Int(1)
}

func TestDoComputation(t *testing.T) {
    testobj := new(MyMock)

    testobj.On(""Add"", 1, 2).Return(5)

    // a := GetNewArithmetic(testobj)

    result := GetNewArithmetic(testobj)

    assert.Equal(t, 5, result.Add(5, 6))
    testobj.AssertExpectations(t)
}
</code></pre>

<p>I receive this error</p>

<pre><code>--- FAIL: TestDoComputation (0.00s)
panic:

mock: Unexpected Method Call
-----------------------------

Add(int,int)
            0: 5
            1: 6

The closest call I have is:

Add(int,int)
            0: 1
            1: 2


 [recovered]
        panic:

mock: Unexpected Method Call
-----------------------------

Add(int,int)
            0: 5
            1: 6

The closest call I have is:

Add(int,int)
            0: 1
            1: 2

goroutine 13 [running]:
testing.tRunner.func1(0xc420106870)
        /usr/lib/golang/src/testing/testing.go:711 +0x2d2
panic(0x701160, 0xc420011070)
</code></pre>

<p>I have no idea on how to fix since this is my first time using Go and using Testify to do unit testing. Would appreciate if someone can take a look and have a working version of this. Thanks</p>
",https://stackoverflow.com/questions/50772163/cannot-pass-testify-mock-object-error,"['go', 'testify']",12340,TRUE,2,2
Can I use a Code::Blocks as a MinGW GDB GUI?,"<p>We are unit testing with Vectorcast, which lets us use the MinGw GDB, but only the command line version. Some of the younger developers would like something more visual.</p>

<p>We do not use Code::Blocksto build our code, and it would be a major effort to do so.</p>

<p>Can we use a Code::Blocksas a GDB GUI? That is to say, can I point it at a .EXE file (which contains MinGW debug information) and use Code::Blocks (or any other MinGW based IDE) as a GDB GUI?</p>
",https://stackoverflow.com/questions/51416832/can-i-use-a-codeblocks-as-a-mingw-gdb-gui,"['gdb', 'mingw', 'codeblocks']",419,TRUE,2,3
Getting error - Failed: Cannot read property &#39;click&#39; of null,"<p>Hi I am working on angular2. I am writing unit test case for delete operation. In real time I am making API call to delete user. To unit test i have created json objecr array and I am making required operations. Below is my code for delete operation.</p>

<pre><code> it('should', async(() =&gt; {
        spyOn(component, 'deleteUser');
        let button = fixture.debugElement.nativeElement.querySelector('deleteUser');
        button.click();
        fixture.whenStable().then(() =&gt; {
            expect(component.deleteUser).toHaveBeenCalled();
        })
        alert(1);
    }));
</code></pre>

<p>Below is my service.</p>

<pre><code>  deleteUserEndpoint(userid: string) {
        var deleteUserUserOnboard = { result: true };
        return Observable.of(deleteUserUserOnboard);
    }
</code></pre>

<p>Below is my html code.</p>

<pre><code> &lt;a class=""btn btn-link btn-xs"" href=""javascript:;"" id=""deleteUser"" (click)=""deleteUser(row)""&gt;&lt;i class=""fa fa-trash-o"" aria-hidden=""true""&gt;&lt;/i&gt; {{'users.management.Delete' | translate}}&lt;/a&gt;
</code></pre>

<p>I have below error.</p>

<pre><code>Failed: Cannot read property 'click' of null 
</code></pre>

<p>I am newbie to unit testing. Can someone tell me what would be the expected behavior? Also may I know am I doing something wrong here? Any help would be appreciated. Thank you. </p>
",https://stackoverflow.com/questions/49526701/getting-error-failed-cannot-read-property-click-of-null,"['angular', 'unit-testing', 'jasmine']",8633,TRUE,2,1
Running dotnet test on webapi app with xunit,"<p>I am trying to setup a dotnet core webapi project with xunit, using latest versions, based on this guide :</p>

<p><a href=""https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-with-dotnet-test"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-with-dotnet-test</a>
(by the way, I have downloaded the github sample project and have the same error)</p>

<p>My project structure is realy basic :</p>

<p>the solution contains</p>

<ul>
<li>""PrimeService"" project (the api)</li>
<li>""PrimeService.Test"" project (xunit tests)</li>
</ul>

<p>I'am getting the following error when running ""dotnet test"" :</p>

<pre><code>Build started, please wait...
Build started, please wait...
Build completed.

Test run for /media/sf_D_DRIVE/TestDotNetCoreMultiProjectSolution/PrimeService/bin/Debug/netstandard2.0PrimeService.dll(.NETStandard,Version=v2.0)
Microsoft (R) Test Execution Command Line Tool Version 15.7.0
Copyright (c) Microsoft Corporation.  All rights reserved.

Starting test execution, please wait...
System.IO.FileNotFoundException: Unable to find tests for /media/sf_D_DRIVE/TestDotNetCoreMultiProjectSolution/PrimeService/bin/Debug/netstandard2.0/PrimeService.dll. Make sure test project has a nuget reference of package ""Microsoft.NET.Test.Sdk"" and framework version settings are appropriate. Rerun with /diag option to diagnose further.
   at     Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Hosting.DotnetTestHostManager.GetTestHostProcessStartInfo(IEnumerable`1 sources, IDictionary`2 environmentVariables, TestRunnerConnectionInfo connectionInfo)
   at     Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Client.ProxyOperationManager.SetupChannel(IEnumerable`1 sources, CancellationToken cancellationToken)
   at     Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Client.ProxyExecutionManager.StartTestRun(TestRunCriteria testRunCriteria, ITestRunEventsHandler eventHandler)

Test Run Aborted.
Build completed.

Test run for /media/sf_D_DRIVE/TestDotNetCoreMultiProjectSolution/PrimeService.Tests/bin/Debug/netcoreapp2.1/PrimeService.Tests.dll(.NETCoreApp,Version=v2.1)
Microsoft (R) Test Execution Command Line Tool Version 15.7.0
Copyright (c) Microsoft Corporation.  All rights reserved.

Starting test execution, please wait...

Total tests: 11. Passed: 11. Failed: 0. Skipped: 0.
Test Run Successful.
Test execution time: 1.5172 Seconds
</code></pre>

<p>Here is the top of the sln :</p>

<pre><code>Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26124.0
MinimumVisualStudioVersion = 15.0.26124.0
Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""PrimeService"", ""PrimeService\PrimeService.csproj"", ""{AE9EB41F-3946-4577-AC13-EF9B7117BCD5}""
EndProject
Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""PrimeService.Tests"", ""PrimeService.Tests\PrimeService.Tests.csproj"", ""{4EC37F9F-B5F3-4820-8476-689CE8BC1D2F}""
EndProject
</code></pre>

<p>Here is the test csproj</p>

<pre><code>&lt;Project Sdk=""Microsoft.NET.Sdk""&gt;

  &lt;PropertyGroup&gt;
    &lt;TargetFramework&gt;netcoreapp2.1&lt;/TargetFramework&gt;

    &lt;IsPackable&gt;false&lt;/IsPackable&gt;
  &lt;/PropertyGroup&gt;

  &lt;ItemGroup&gt;
    &lt;PackageReference Include=""Microsoft.NET.Test.Sdk"" Version=""15.7.0"" /&gt;
    &lt;PackageReference Include=""xunit"" Version=""2.3.1"" /&gt;
  &lt;/ItemGroup&gt;

  &lt;ItemGroup&gt;
    &lt;ProjectReference Include=""..\PrimeService\PrimeService.csproj"" /&gt;
  &lt;/ItemGroup&gt;

&lt;/Project&gt;
</code></pre>

<p>Here is the webapi csproj :</p>

<pre><code>&lt;Project Sdk=""Microsoft.NET.Sdk""&gt;

  &lt;PropertyGroup&gt;
    &lt;TargetFramework&gt;netstandard2.0&lt;/TargetFramework&gt;
  &lt;/PropertyGroup&gt;

&lt;/Project&gt;
</code></pre>

<p>Any clues ?</p>

<p>Thanks :-)</p>
",https://stackoverflow.com/questions/50730508/running-dotnet-test-on-webapi-app-with-xunit,"['visual-studio-code', '.net-core', 'xunit', 'csproj', 'sln-file']",1339,TRUE,2,1
Create JObject with propertyname.subname,"<p>I am trying to create a JObject on the fly for unit testing but it does not seem to like <code>name.subname</code> as a property</p>

<p>The json that I am trying to create JObject for is</p>

<pre><code>   { ""UserDetails"": {
          ""FirstName"": ""Test1"",
          ""Surname"": ""Test2"",
          ""UserID"": ""123456789"",
          ""Children1.Active1"": false,
          ""Children1.Active2"": false
    }
}
</code></pre>

<p>The C# code I have is</p>

<pre><code>dynamic jsonObject = new JObject();
jsonObject.UserDetails = new JObject();
jsonObject.UserDetails.UserID = ""123456789"";
jsonObject.UserDetails.FirstName = ""Test1"";
jsonObject.UserDetails.Surname= ""Test2"";
</code></pre>

<p>However i am not sure how to add <code>Children1.Active</code> to the JObject <code>jsonObject. UserDetails</code> it does not work with <code>jsonObject.UserDetails.Children.Active1 = false</code>.</p>

<p>I have validated the json and it passes validation for being valid json.</p>

<p>How can I add <code>Children1.Active</code> to JObject?</p>

<p>I have tried <code>jsonObject.UserDetails.Children1 = new JObject();</code>
But this creates a new sub object which is not what I need.</p>
",https://stackoverflow.com/questions/52663623/create-jobject-with-propertyname-subname,"['c#', 'json', 'json.net']",88,TRUE,2,1
Django 2.0 unit test not running due to AppRegistryNotReady,"<p>I built a very simple Django application to try unit testing. I can run a test without any problem when not importing any Django model, like:</p>

<pre><code>import os

from django.test import TestCase

class FirstTest(TestCase):

    os.environ.setdefault(""DJANGO_SETTINGS_MODULE"", ""testje.settings"")

    def test_First(self):
        a = 1
        self.assertEqual(1, a)
</code></pre>

<p>I'm running Django 2.0.1. Now when I'm trying to import a model like:</p>

<pre><code>import os

from django.test import TestCase

from polls.models import Question


class FirstTest(TestCase):

    os.environ.setdefault(""DJANGO_SETTINGS_MODULE"", ""testje.settings"")

    def test_First(self):
        a = 1
        self.assertEqual(1, a)
</code></pre>

<p>it will fail with the following stack trace:</p>

<pre><code>
Testing started at 16:46 ...
C:\Users\martijnka\virtualenvs\Test\Scripts\python.exe ""C:\Program Files\JetBrains\PyCharm Community Edition 2018.1.2\helpers\pycharm\_jb_unittest_runner.py"" --path D:/martijnka/Downloads/testDjango/testje/polls/tests.py
Launching unittests with arguments python -m unittest D:/martijnka/Downloads/testDjango/testje/polls/tests.py in D:\martijnka\Downloads\testDjango\testje\polls

Traceback (most recent call last):
  File ""C:\Program Files\JetBrains\PyCharm Community Edition 2018.1.2\helpers\pycharm\_jb_unittest_runner.py"", line 35, in 
    main(argv=args, module=None, testRunner=unittestpy.TeamcityTestRunner, buffer=not JB_DISABLE_BUFFERING)
  File ""c:\program files (x86)\python36-32\Lib\unittest\main.py"", line 94, in __init__
    self.parseArgs(argv)
  File ""c:\program files (x86)\python36-32\Lib\unittest\main.py"", line 141, in parseArgs
    self.createTests()
  File ""c:\program files (x86)\python36-32\Lib\unittest\main.py"", line 148, in createTests
    self.module)
  File ""c:\program files (x86)\python36-32\Lib\unittest\loader.py"", line 219, in loadTestsFromNames
    suites = [self.loadTestsFromName(name, module) for name in names]
  File ""c:\program files (x86)\python36-32\Lib\unittest\loader.py"", line 219, in 
    suites = [self.loadTestsFromName(name, module) for name in names]
  File ""c:\program files (x86)\python36-32\Lib\unittest\loader.py"", line 153, in loadTestsFromName
    module = __import__(module_name)
  File ""D:\martijnka\Downloads\testDjango\testje\polls\tests.py"", line 5, in 
    from polls.models import Question
  File ""D:\martijnka\Downloads\testDjango\testje\polls\models.py"", line 9, in 
    class Question(models.Model):
  File ""C:\Users\martijnka\virtualenvs\Test\lib\site-packages\django\db\models\base.py"", line 100, in __new__
    app_config = apps.get_containing_app_config(module)
  File ""C:\Users\martijnka\virtualenvs\Test\lib\site-packages\django\apps\registry.py"", line 244, in get_containing_app_config
    self.check_apps_ready()
  File ""C:\Users\martijnka\virtualenvs\Test\lib\site-packages\django\apps\registry.py"", line 127, in check_apps_ready
    raise AppRegistryNotReady(""Apps aren't loaded yet."")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

Process finished with exit code 1
Empty test suite.
</code></pre>

<p>My settings looks like this:</p>

<pre><code>

    """"""
    Django settings for testje project.

    Generated by 'django-admin startproject' using Django 2.0.1.

    For more information on this file, see
    https://docs.djangoproject.com/en/2.0/topics/settings/

    For the full list of settings and their values, see
    https://docs.djangoproject.com/en/2.0/ref/settings/
    """"""

    import os

    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


    # Quick-start development settings - unsuitable for production
    # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/

    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = '********************************'

    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = True

    ALLOWED_HOSTS = ['127.0.0.1', 'localhost']


    # Application definition

    INSTALLED_APPS = [
        'polls.apps.PollsConfig',
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
    ]

    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]

    ROOT_URLCONF = 'testje.urls'

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]

    WSGI_APPLICATION = 'testje.wsgi.application'


    # Database
    # https://docs.djangoproject.com/en/2.0/ref/settings/#databases

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        }
    }


    # Password validation
    # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators

    AUTH_PASSWORD_VALIDATORS = [
        {
            'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
        },
    ]


    # Internationalization
    # https://docs.djangoproject.com/en/2.0/topics/i18n/

    LANGUAGE_CODE = 'en-us'

    TIME_ZONE = 'UTC'

    USE_I18N = True

    USE_L10N = True

    USE_TZ = True


    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/2.0/howto/static-files/

    STATIC_URL = '/static/'

</code></pre>

<p>As you can see I'm running from PyCharm CE 9the latest version). I have been looking for answers and trying many things but so far without any luck. Any idea what I'm missing here (probably something very simple)?</p>
",https://stackoverflow.com/questions/50137660/django-2-0-unit-test-not-running-due-to-appregistrynotready,"['django', 'python-3.x', 'unit-testing']",972,FALSE,2,0
How to use Property-based testing using FsCheck.NUnit or XUnit?,"<p>I new to property-based and unit testing, and in my project I want to to use this technique, but unfortunately it is easy to say... I watched a talk about FsCheck.XUnit library, but the guy was testing numeric function (modulus)... And I want to test functions that use strings, lists and arrays.. Maybe you guys could give a hint or a source where I can look through? 
P.S. every where I was looking there were only numerical example, which looked like pretty easy to test. </p>

<p>There are some functions I wish to test:</p>

<pre><code>let wordSplit (text:string) = 
  text.Split([|' ';'\n';'\r';'\t';'!';',';'.';'?';';';':'; '/'
  ;'\\';'-';'+'; '*'; '#';'(';')';'^';'""';'\'';'`'; '@';'~';'|'|]
  ,StringSplitOptions.RemoveEmptyEntries)
  |&gt; Array.toList 

let rec matchTails (tail1 : string list) (tail2 : string list) = 
    match tail1, tail2 with
        | h1::t1 , h2::t2 -&gt; 
            if (h1=h2) then 
                matchTails t1 t2
            else
                false
        | [], _ -&gt; false
        | _, []  -&gt; true

let rec phraseProcessor (textH: string) (textT: string list) (phrases: string list list) (n:int) = 
    match phrases with 
    |[] -&gt; n
    | h :: t -&gt;
        match h with
        |x when x.Head = textH &amp;&amp; (matchTails (textT) (x.Tail)) -&gt;
            phraseProcessor (textH) (textT) (t) (n+1)
        | _ -&gt; 
            phraseProcessor (textH) (textT) (t) (n)


let rec wordChanger (phrases : string list list) (text:string list) (n:int)= 
    match text with
    | [] -&gt; n
    | h :: t -&gt;
        wordChanger phrases t (phraseProcessor (h) (t) (phrases) (n))
</code></pre>
",https://stackoverflow.com/questions/48209787/how-to-use-property-based-testing-using-fscheck-nunit-or-xunit,"['unit-testing', 'f#', 'fscheck', 'property-based-testing']",347,TRUE,1,1
Change environment settings in unit tests (Angular),"<p>I can think of two approaches when dealing with settings in <code>Angular</code>:</p>

<ol>
<li>DI settings using <code>InjectionToken</code> <a href=""https://angular.io/guide/dependency-injection#injection-token"" rel=""noreferrer"">as per the documentation</a>.</li>
<li>Environment files, where I have settings for each environment (dev, qa, prod), I import the generic ""environment"" file, and I compile with a flag that sets the environment.</li>
</ol>

<p>When unit testing, I'm used to #1: I just create settings appropriate for my unit tests and inject them.</p>

<p>But how could I change the settings if I go with #2? Say that I need to mock a setting. Can I add an environment flag when running the unit tests?</p>
",https://stackoverflow.com/questions/48976945/change-environment-settings-in-unit-tests-angular,['angular'],3693,FALSE,7,0
Is it possible to have virtual column in HSQLDB,"<p>I am new to <strong>HSQLDB</strong> and I am not sure whether HSQLDB supports Virtual column and JSON Path. I am trying to make use of this database to run my Unit Testing. </p>

<p>We use Oracle as the actual database and the Oracle Table has one field which accepts JSON as CLOB. Using JSON Path feature in Oracle, we have created Virtual Columns that parse the JSON and create the virtual column. 
The Oracle Table schema is as follows:</p>

<pre><code>CREATE TABLE ""DUMMY_TABLE"" 
   (    ""ID"" VARCHAR2(40 BYTE), 
    ""JSON_CONTENTS"" CLOB, 
    ""VIRTUAL_COLUMN1"" VARCHAR2(40 BYTE) GENERATED ALWAYS AS (JSON_VALUE(""JSON_CONTENTS"" FORMAT JSON , '$.Info1.Value1' RETURNING VARCHAR2(40) NULL ON ERROR)) VIRTUAL , 
    ""VIRTUAL_COLUMN2"" VARCHAR2(40 BYTE) GENERATED ALWAYS AS (JSON_VALUE(""JSON_CONTENTS"" FORMAT JSON , '$.Info2.Value2' RETURNING VARCHAR2(40) DEFAULT 'Value2' ON ERROR)) VIRTUAL
   )
</code></pre>

<p>Is it possible to mimc the same functionality in <strong>HSQLDB</strong> ? </p>
",https://stackoverflow.com/questions/48932602/is-it-possible-to-have-virtual-column-in-hsqldb,"['json', 'hsqldb', 'jsonpath']",423,FALSE,1,1
Call TIBCO BW6 process from Java code,"<p>I'm looking for a way to automate testing for our TIBCO BW6 applications. </p>

<p>There are 2 test methods I would like to use: Unit tests and BDD. </p>

<p>For unit testing I would like to be able to call a subprocess with some in- and output, and assert the processed data. </p>

<p>For BDD I would like to use Cucumber, and test the entire flows from start to end. </p>

<p>To accomplish this, it would be nice if I could call (sub)processes from Java with some in- and output. </p>

<p>Does anyone know if this is possible?</p>
",https://stackoverflow.com/questions/48868653/call-tibco-bw6-process-from-java-code,['tibco-business-works'],698,FALSE,1,2
Test IF in Subscribe using Karma and Jasmine,"<p>I'm doing unit testing in Angular 6, but I'm having trouble testing this <code>IF</code> branch. I use it to observe how big the screen is, and so to decide how many columns I'll display. I'm struggling with how to test inside the subscribe that is in <code>ngOnInit()</code>. </p>

<p>This </p>

<pre><code> this.watcher = this.media.subscribe((change: MediaChange) =&gt;....
</code></pre>

<p>code coverage show that it does not go into the <code>if</code> and <code>else</code> of these services. This was the best I could do. The Media Change service keeps looking at which screen size, to decide how many columns it would display in the table</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>  ngOnInit() {
        this.watcher = this.media.subscribe((change: MediaChange) =&gt; {
          this.activeMediaQuery = change ? `'${change.mqAlias}' = (${change.mediaQuery})` : '';
          this.changeMqAlias = change.mqAlias;

          if (this.changeMqAlias == this.changeSize.XS) {

            this.displayedColumns = ['job', 'name', 'totalValue'];
          } else {
            this.displayedColumns = ['internalId', 'DateOfPublication', 'alias', 'job', 'name', 'totalValue'];
          }
          return change.mqAlias;
        });
      }</code></pre>
</div>
</div>

The File Test
<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('should create', () =&gt; {
                fixture.whenStable().then(() =&gt; {
                  
                  expect(component).toBeTruthy();
                });
              });

              it('should create which 3 columns in mat table', () =&gt; {
                fixture.whenStable().then(() =&gt; {
                  component.changeMqAlias = 'xs';
                  expect(component).toBeTruthy();
                });
              });
             
            });</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/53934411/test-if-in-subscribe-using-karma-and-jasmine,"['javascript', 'angular', 'testing', 'jasmine', 'angular6']",1381,TRUE,1,1
How to set up a Dockerfile so that the container OS will be Ubuntu?,"<p>I'm just getting into Docker, so please excuse my noobiness.</p>

<p>I've set up a Dockerfile for a unit testing project, based on the guidelines in <a href=""https://techblog.dorogin.com/running-and-debugging-net-core-unit-tests-inside-docker-containers-48476eda2d2a"" rel=""nofollow noreferrer"">this article</a>. The container runs fine, and I managed to run the tests. But I got different results in my local container than we got on our build bot. So I thought it might be because the build bot is on Ubuntu, while my local container appears to be Debian.</p>

<p>So, how do I set up the Dockerfile to use Ubuntu rather than Debian?</p>

<p>Dockerfile code:</p>

<pre><code>FROM microsoft/dotnet:2.1-sdk
WORKDIR /src
COPY ./bin/Debug/netcoreapp2.1/linux-x64/publish/ .
ENTRYPOINT [""tail"", ""-f"", ""/dev/null""]
</code></pre>
",https://stackoverflow.com/questions/51520649/how-to-set-up-a-dockerfile-so-that-the-container-os-will-be-ubuntu,"['docker', '.net-core']",73,TRUE,1,1
"Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be","<p>I am using the <strong>spring batch boot example</strong>. In my project, I have two batch jobs developed so far and in future will be having around 10 batch jobs running simultaneously. </p>

<p>I developed the code for the second batch job and when I started to run the 2nd batch job, I started getting the below error.</p>

<p>I have following doubts in my mind - </p>

<ol>
<li>How can I run only 2nd batch for my development and unit testing ?</li>
<li>How can I run all the batch jobs in one go ?</li>
</ol>

<p>Error which is coming - </p>

<pre><code>org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'org.springframework.batch.core.Job' available: expected single matching bean but found 2: exportemployeesJob,exportOrdersJob
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveNotUnique(DependencyDescriptor.java:215) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1116) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1065) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:584) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:373) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1350) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:580) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:503) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:760) ~[spring-beans-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869) ~[spring-context-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.0.7.RELEASE.jar:5.0.7.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:395) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1255) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1243) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
    at com.prateek.SpringBatchClassicDbApplication.main(SpringBatchClassicDbApplication.java:12) [classes/:na]

2018-07-08 21:45:23.396 ERROR 11600 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Field job in com.prateek.scheduler.EmployeesRunScheduler required a single bean, but 2 were found:
    - exportemployeesJob: defined by method 'exportemployeesJob' in class path resource [com/prateek/job/EmployeesJob.class]
    - exportOrdersJob: defined by method 'exportOrdersJob' in class path resource [com/prateek/job/OrdersJob.class]


Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed
</code></pre>

<p><strong>OrdersJob.java</strong></p>

<pre><code>@Configuration
@EnableBatchProcessing
public class OrdersJob {

    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Autowired
    private DataSource dataSource;

    @Bean(destroyMethod="""")
    public JdbcCursorItemReader&lt;Orders&gt; ordersReader(){
        JdbcCursorItemReader&lt;Orders&gt; itemReader = new JdbcCursorItemReader&lt;&gt;();
        itemReader.setDataSource(dataSource);
        itemReader.setSql(""SELECT orderNumber, productName, msrp, priceEach ""
                + ""FROM products p ""
                + ""INNER JOIN orderdetails o ""
                + ""ON p.productcode = o.productcode ""
                + ""AND p.msrp &gt; o.priceEach "");
                //+ ""WHERE p.productcode = ? "");
        itemReader.setRowMapper(new OrdersRowMapper());
        itemReader.setIgnoreWarnings(true);

        return itemReader;
    }


    @Bean(destroyMethod="""")
    public FlatFileItemWriter&lt;Orders&gt; ordersWriter(){
        FlatFileItemWriter&lt;Orders&gt; fileItemWriter = new FlatFileItemWriter&lt;&gt;();
        fileItemWriter.setResource(new FileSystemResource(""csv/Orders.csv""));
        //fileItemWriter.setHeaderCallback(headerCallback());

        DelimitedLineAggregator&lt;Orders&gt; lineAggregator = new DelimitedLineAggregator&lt;&gt;();
        lineAggregator.setDelimiter("","");
        lineAggregator.setFieldExtractor(new PassThroughFieldExtractor&lt;Orders&gt;());

        fileItemWriter.setLineAggregator(lineAggregator);
        fileItemWriter.setShouldDeleteIfEmpty(true);

        return fileItemWriter;
    }


    // Step Execution
    @Bean
    public Step step1() {
        return stepBuilderFactory.get(""step1"")
                .&lt;Orders, Orders&gt;chunk(10)
                .reader(ordersReader())
                .writer(ordersWriter())
                .build();
    }

    // Job Execution
    @Bean
    public Job exportOrdersJob() {
        return jobBuilderFactory
                .get(""exportOrdersJob"")
                .incrementer(new RunIdIncrementer())
                .flow(step1())
                .end()
                .build();
    }
}
</code></pre>

<p><strong>EmployeesJob.java</strong></p>

<pre><code>@Configuration
@EnableBatchProcessing
public class EmployeesJob {
    public static final String DATE_FORMAT = ""dd-MM-yyyy-hh-mm-ssss"";
    public static final DateFormat formatter = new SimpleDateFormat(DATE_FORMAT);

    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Autowired
    private DataSource dataSource;

    @Bean 
    public EmployeesProcessor employeesProcessor() {
        return new EmployeesProcessor();
    }

    @Bean
    public EmployeesRunScheduler scheduler() {
        return new EmployeesRunScheduler();
    }

    // This file helps to create CSV column aliases
    @Bean
    public EmployeesFlatFileWriterCallback headerCallback() {
        return new EmployeesFlatFileWriterCallback();
    }

    @Bean(destroyMethod="""")
    public JdbcCursorItemReader&lt;Employees&gt; employeesReader(){
        JdbcCursorItemReader&lt;Employees&gt; itemReader = new JdbcCursorItemReader&lt;&gt;();
        itemReader.setDataSource(dataSource);
        itemReader.setSql(""SELECT employeeNumber, lastName, firstName, extension, email, officeCode, reportsTo, jobTitle FROM employees "");
        itemReader.setRowMapper(new EmployeeRowMapper());
        // The fetch size can be controlled from the application.properties 
        //itemReader.setFetchSize(200);
        return itemReader;
    }


    @Bean(destroyMethod="""")
    public FlatFileItemWriter&lt;Employees&gt; employeesWriter(){
        FlatFileItemWriter&lt;Employees&gt; fileItemWriter = new FlatFileItemWriter&lt;&gt;();
        //fileItemWriter.setResource(new FileSystemResource(""csv/employees.csv""));
        fileItemWriter.setResource(new FileSystemResource(""csv/employees-#{""+ formatter.format(new Date()) +""}.csv""));
        fileItemWriter.setHeaderCallback(headerCallback());

        BeanWrapperFieldExtractor&lt;Employees&gt; fieldExtractor = new BeanWrapperFieldExtractor&lt;&gt;();
        fieldExtractor.setNames(new String[] {""employeeNumber"", ""lastName"", ""firstName"", ""extension"", ""email"", ""officeCode"", ""reportsTo"", ""jobTitle""});

        DelimitedLineAggregator&lt;Employees&gt; lineAggregator = new DelimitedLineAggregator&lt;&gt;();
        lineAggregator.setDelimiter("","");
        lineAggregator.setFieldExtractor(fieldExtractor);

        fileItemWriter.setLineAggregator(lineAggregator);
        fileItemWriter.setShouldDeleteIfEmpty(true);

        return fileItemWriter;
    } 

    // Step Execution
    @Bean
    public Step step1() {
        return stepBuilderFactory.get(""step1"")
                .&lt;Employees, Employees&gt;chunk(10)
                .reader(employeesReader())
                .processor(employeesProcessor())
                .writer(employeesWriter())
                .build();
    }

    // Job Execution
    @Bean
    public Job exportemployeesJob() {
        return jobBuilderFactory
                .get(""employeesJob"")
                .incrementer(new RunIdIncrementer())
                .flow(step1())
                .end()
                .build();
    }
}
</code></pre>
",https://stackoverflow.com/questions/51234502/consider-marking-one-of-the-beans-as-primary-updating-the-consumer-to-accept-m,"['spring', 'spring-boot', 'spring-batch']",12634,TRUE,1,1
Unit test to check for global authorization filter on action,"<p>I'm writing unit tests using <code>Microsoft.VisualStudio.TestTools.UnitTesting</code> and Moq for an ASP.NET MVC 5 app that has a custom authorization filter added via <code>FilterConfig.cs</code>:</p>

<pre><code>public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new AuthorizeRedirect());
        //...
    }
}
</code></pre>

<p>Here's the custom authorization attribute:</p>

<pre><code>public class AuthorizeRedirect: AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        base.HandleUnauthorizedRequest(filterContext);

        if (filterContext.RequestContext.HttpContext.User.Identity.IsAuthenticated)
        {
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
            {
                action = ""Redirect"",
                controller = ""Error""
            }));
        }
    }
}
</code></pre>

<p>I'm using a slightly modified version of the <code>IsAnonymous</code> method from here: <a href=""https://datatellblog.wordpress.com/2015/05/05/unit-testing-asp-net-mvc-authorization/"" rel=""nofollow noreferrer"">https://datatellblog.wordpress.com/2015/05/05/unit-testing-asp-net-mvc-authorization/</a>. However it only checks the method/controller for explicitly defined <code>[AuthorizeRedirect]</code> attribute; in its absence, it considers the action to be anonymous.</p>

<p>Is it possible to detect that the above attribute has been applied globally in a unit test when checking if an action is allowing anonymous access? </p>
",https://stackoverflow.com/questions/48103002/unit-test-to-check-for-global-authorization-filter-on-action,"['c#', 'asp.net-mvc', 'unit-testing']",776,TRUE,1,1
Jest: Not able to test specific class with parameter in constructor,"<p>I use Jest as unit testing framework. I want to test a class called EDVApi (edv.ts):</p>

<pre><code>import { Http } from '@angular/http';
import { File } from '@ionic-native/file';
import { FilePath } from '@ionic-native/file-path';
import {Headers} from '@angular/http';
import {RequestOptions} from '@angular/http';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/share';
import {Response} from '@angular/http/src/static_response';
import { Inject } from '@angular/core';

export default class EDVApi {
webservice: any = ""https://XXX.XXX.XXX.XXX:YYYYY/"";

public constructor(public http: Http) {
console.log('EDVApi created.');
}

login(loginData) {
let headers = new Headers();
let data = {
  loginData: loginData
};
headers.append('Content-Type', 'application/json');

let options = new RequestOptions({
  headers: headers,
  body: JSON.stringify(data)
});

return this.http.post(this.webservice + ""login"", data, options);
}
public sum(a,b){
return a+b;
}
}
</code></pre>

<p>In my test class I want to test the function sum of EDVApi:</p>

<pre><code>import EDVApi from './edv';
import 'jest';
jest.mock('./edv');

describe('EDV Tests', () =&gt; {
it('Sum 1+2 should be 3', () =&gt; {
const mockEDV = EDVApi.mock.instances[0];
expect(mockEDV.sum(1,2)).toBe(3);
});
});
</code></pre>

<p>when I try to compile my code the cli gives me following error: Property 'mock' does not exist on type 'typeof EDVApi'. when i run <code>npm test</code> Jest tests fail with the message: </p>

<pre><code>   the module which has no default export › Sum 1+2 should be 3

   TypeError: Cannot read property 'mock' of undefined

   5 | describe('the module which has no default export', () =&gt; {
   6 |   it('Sum 1+2 should be 3', () =&gt; {
&gt;  7 |     const mockEDV = EDVApi.mock.instances[0];
   8 |     expect(mockEDV.sum(1,2)).toBe(3);
   9 |   });
  10 | });

  at Object.&lt;anonymous&gt; (src/edv.test.ts:7:28)
</code></pre>

<p>FAIL  src\edv.test.ts
  ● Test suite failed to run</p>

<pre><code>TypeError: Cannot read property 'Symbol' of undefined

&gt; 1 |
  2 | import { Http } from '@angular/http';
  3 | import { File } from '@ionic-native/file';
  4 |

  at Object.&lt;anonymous&gt; (node_modules/rxjs/symbol/rxSubscriber.js:3:26)
  at Object.&lt;anonymous&gt; (node_modules/rxjs/Subscriber.js:10:22)
  at Object.&lt;anonymous&gt; (node_modules/rxjs/util/toSubscriber.js:2:20)
  at Object.&lt;anonymous&gt; (node_modules/rxjs/Observable.js:3:22)
  at Object.&lt;anonymous&gt;.Object.setPrototypeOf.__proto__ (node_modules/@angular/core/bundles/core.umd.js:7:82)
  at Object.&lt;anonymous&gt; (node_modules/@angular/core/bundles/core.umd.js:10:2)
  at Object.&lt;anonymous&gt;.Object.setPrototypeOf.__proto__ (node_modules/@angular/http/bundles/http.umd.js:7:82)
  at Object.&lt;anonymous&gt; (node_modules/@angular/http/bundles/http.umd.js:10:2)
  at Object.&lt;anonymous&gt; (src/edv.ts:1:52054)
  at Object.&lt;anonymous&gt; (src/edv.test.ts:3:31)
</code></pre>

<p>I tried many different solutions as described in the officially Jest Documentation, but could not solve this issue. Any suggestions?</p>
",https://stackoverflow.com/questions/51443936/jest-not-able-to-test-specific-class-with-parameter-in-constructor,"['angular', 'typescript', 'jestjs']",505,FALSE,1,0
Test DelegateCommand async without needing to make handler public,"<p>Using the <strong>DelegateCommand</strong> within <strong>Prism</strong> it is no longer possible to await the command execution since FromAsyncHanlder was removed from version <strong>6.3</strong>. </p>

<p>For unit testing the recommendation is to port as below, so if you have</p>

<pre><code>Task MyHandler() {...}
DelegateCommand myCommand = DelegateCommand.FromAsyncHandler(MyHandler);
/// in test:
await myCommand.Execute();
</code></pre>

<p>change it to</p>

<pre><code>DelegateCommand myCommand = new DelegateCommand(async () =&gt; await MyHandler());
/// in test:
await MyHandler();
</code></pre>

<p>This however requires the command handler (MyHandler) to be made public which negates the encapsulation benefits of using the command pattern. </p>

<p>I know that I can use/create other command implementations but I like DelegateCommand as it is part of Prism and regularly maintained.</p>

<p>Is there a better way of testing async commands using the DelegateCommand?</p>
",https://stackoverflow.com/questions/51288387/test-delegatecommand-async-without-needing-to-make-handler-public,"['c#', 'wpf', 'mvvm', 'prism']",1304,TRUE,1,2
Why unit test coverage data changing when I am using ?? (null coalescing operator)?,"<p>I have created an Employee model with id and name as optional properties and a description method which will return a interpolated string.</p>

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

<pre><code>class Employee: NSObject {
    var id: String?
    var name: String?

    init(id: String, name: String) {
        self.id = id
        self.name = name
    }

    func description() -&gt; String {
        return ""Employee ID: \(id ?? """") and Employee Name: \(name ?? """").""
        //return ""Employee ID: \(id != nil ? id! : """") and Employee Name: \(name ?? """").""
    }
}
</code></pre>

<p>and I have written test case for unit testing this Employee model.</p>

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

<pre><code>class EmployeeTests: 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 testEmployee() {
        let employee = Employee(id: ""1"", name: ""Yash Vyas"")
        XCTAssertEqual(employee.id, ""1"")
        XCTAssertEqual(employee.name, ""Yash Vyas"")
        XCTAssertEqual(employee.description(), ""Employee ID: 1 and Employee Name: Yash Vyas."")
    }
}
</code></pre>

<p>I am not getting why coverage is 100% for Employee class when I use ternary operator instead of ?? (the commented line in the description method) for checking nil for optional properties when returning interpolated string from description() method and why it is reducing when I am using ?? (null coalescing) operator.</p>
",https://stackoverflow.com/questions/49208274/why-unit-test-coverage-data-changing-when-i-am-using-null-coalescing-operato,"['ios', 'swift', 'xcode', 'unit-testing', 'code-coverage']",703,TRUE,1,1
How to unit-test a requirement that can be enforced by the compiler,"<p>Let me explain! I'm trying to implement some DDD in a node app. I have a <code>Post</code> object with a <code>title</code> attribut. The requirement is that we can't create a <code>Post</code> with empty <code>title</code> (title is required).</p>

<p>I have <code>""strict"": true</code> in my <code>tsconfig.json</code> file. (Enable strict null checks)</p>

<p>The <code>Post</code> class look like this : </p>

<pre><code>export class Post {

    private title: string;

    constructor(title: string) {
        this.title = title;

        if (!this.title) {
            throw new Error('Post title should not be empty');
        }
    }
}
</code></pre>

<p>Now the compiler will stop me from doing <code>new Post(null);</code> which is good.</p>

<p>My question is, in my unit testing, how could I test that this requirement is fulfilled. Should I ignore it ? What if someone changed the <code>Post</code> class and make the title optional in the future ?</p>
",https://stackoverflow.com/questions/50286907/how-to-unit-test-a-requirement-that-can-be-enforced-by-the-compiler,"['unit-testing', 'typescript', 'tdd']",37,FALSE,1,0
Firebase Test Lab - Not authorised to use project,"<p>I followed this tutorial to create tests in android studio: <a href=""https://developer.android.com/training/testing/unit-testing/instrumented-unit-tests#run-ctl"" rel=""nofollow noreferrer"">https://developer.android.com/training/testing/unit-testing/instrumented-unit-tests#run-ctl</a>. I successfully ran those tests on my physical device. Then I created the test run configuration for test lab, also followed the same tutorial. When I want to run this configuration I am receiving the following error:</p>

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

<p>What am I doing wrong? Why am I not authorised for my own project? I was able to add my firebase project normally. I am using only free spark billing in Firebase. </p>
",https://stackoverflow.com/questions/52482339/firebase-test-lab-not-authorised-to-use-project,"['android', 'firebase', 'testing', 'firebase-test-lab']",675,TRUE,1,1
How do I test how a mobile app gets foregrounded?,"<p>I've got a <code>create-react-native-app</code> and I need to write a test to prevent a regression of an issue when users bring the app back to the foreground (it seems to have difficulty reconnecting the socket.io connection).</p>

<p>Currently I have to manually test this by following some steps:</p>

<ol>
<li>Open the app</li>
<li>Log in</li>
<li>Wait for login to complete</li>
<li>Switch to another app (background it)</li>
<li>Wait for backgrounded app to lose its server connection (~20 seconds)</li>
<li>Re-open app (foreground it)</li>
<li>Check if issue occurs</li>
</ol>

<p>How do I go about writing automated tests for this? I'm using <code>jest</code> for unit testing within the app.</p>
",https://stackoverflow.com/questions/50673923/how-do-i-test-how-a-mobile-app-gets-foregrounded,"['react-native', 'testing', 'automated-tests']",965,FALSE,6,1
Return Null reference by mocking UserManger and Identity extension functions from Moq framework,"<p>I am implementing Unit testing using Nunit and moq mocking framework. While testing I successfully mocked Usermanager and identity but unable to return correct value and data type.</p>

<blockquote>
  <p>Mock User Manager</p>
</blockquote>

<pre><code>var users = new List&lt;MstUser&gt;
{
new MstUser { Id=new Guid(""b35ec046-423e-4ee4-a057-fcb1fe182086"") , 
            Email=""niteshkmodi@gmail.com"", 
            UserName = ""niteshkmodi@gmail.com"" }
}.AsQueryable();
var userManager = new Mock&lt;ApplicationUserManager&gt;();
userManager.Setup(x =&gt; x.Users).Returns(users);

// Initialize controller constructor
var controller = new HomeController(userManager.Object, adminBl);

// Calling Index Method to test
ViewResult result = await controller.Index(model, RedirectToAction) as ViewResult;
</code></pre>

<p>By using this code i able to mock UserManager but while testing in controller identity reference returns null</p>

<pre><code>var identity = await UserManager.CreateIdentityAsync(adminUser, DefaultAuthenticationTypes.ApplicationCookie);
</code></pre>

<p><strong>and i am unable to add claim and this create reference error.</strong></p>

<pre><code>identity.AddClaim(new Claim(IdentityClaimConst.FullName, adminUser.Name == null ? """" : adminUser.Name));
</code></pre>

<blockquote>
  <p>Mock identity</p>
</blockquote>

<pre><code>var controllerContext = new Mock&lt;ControllerContext&gt;();
var principal = new Moq.Mock&lt;IPrincipal&gt;();
principal.SetupGet(x =&gt; x.Identity.Name).Returns(userName);
controllerContext.SetupGet(x =&gt; x.HttpContext.User).Returns(principal.Object);
var controller = new HomeController(adminBl);
controller.ControllerContext = controllerContext.Object;
JsonResult result = controller.MyProfile(null, null) as JsonResult;
</code></pre>

<p>From this code I successfully mocking Identity but unable to access value of User.Identity.GetUserId() which give casting error </p>

<p><strong>Unable to cast object of type 'Castle.Proxies.ObjectProxy' to type 'System.Security.Claims.ClaimsIdentity'.</strong></p>
",https://stackoverflow.com/questions/48259793/return-null-reference-by-mocking-usermanger-and-identity-extension-functions-fro,"['unit-testing', 'mocking', 'asp.net-identity', 'nunit-3.0', 'moq-3']",306,FALSE,0,0
Why is my JDBC connection only failing when deployed through Jetty?,"<p>To pretense, i'm new to web development. I have a java web application that is deployed through Jetty, and I have an issue that is really confusing me. In order to display data from my database in the web app I must establish a database connection, which I can do when I am unit testing my code, but when I call the same methods from .jsp pages to populate the web app I get a message telling me this:</p>

<pre><code>java.sql.SQLException: No suitable driver found for jdbc:sqlserver://localhost:1433;integratedSecurity=true;database=TicketITBookingSystemDatabase;loginTimeout=30;
</code></pre>

<p>Here is the rest of the relevant code:</p>

<pre><code>public void queryDatabase(String query){

ResultSet resultSet = null;
String connectionUrl = establishDatabaseConnection();

try (Connection connection = DriverManager.getConnection(connectionUrl);
     Statement statement  = connection.createStatement();) {

    //Execute the sql statement passed as the query parameter.
    resultSet = statement.executeQuery(query);
    processResultSet(resultSet);
    statement.close();
}
// Handle any errors that may have occurred.
catch (SQLException e) {
    e.printStackTrace(); //why is this being hit but only on the web build
}
</code></pre>

<p>And the event that is being called:</p>

<pre><code>public List&lt;String[]&gt; getAllEvents(){
    queryDatabase(""EXEC dbo.sp_GetAllEventDetails"");
    return events;
}
</code></pre>

<p>Thanks.</p>
",https://stackoverflow.com/questions/53592597/why-is-my-jdbc-connection-only-failing-when-deployed-through-jetty,"['java', 'jdbc', 'web-applications', 'jetty']",53,FALSE,0,2
Jest expect mongoose timestamps,"<p>I'm unit testing an Express / Mongoose API using Jest.
However, I'm facing issues concerning expect ""_id"" and timestamps fields (""createdAt"" and ""updatedAt"" for instance).</p>

<pre><code>  const validBody = {
    email: faker.internet.email(),
    lastName: faker.name.lastName(),
    firstName: faker.name.firstName(),
    password: faker.internet.password()
  }

 // creation of an user by API call
 // ...

  const user = await User.findById(response.body.data._id)

  // OK
  expect(user._id).toEqual(expect.anything())
  expect(user.createdAt).toEqual(expect.anything())

  // FAIL
  expect(user).toEqual({
    ...validBody,
    _id: expect.anything(),
    createdAt: expect.anything()
  )}
</code></pre>

<p>Both first expects match fine. However, the last one using the full object doesn't match, whatever I put in expect.any(...) (even anything()). For instance for createdAt, I've tried ""Object, Date, mongoose.Schema.Types.Date, String"" ...</p>

<p>Do you have any idea ? I believe mongoose is casting _id and createdAt objects into a plain field during two first expects. But, using expect.anything() in the object should match ... anything ?</p>

<p>Thanks !</p>
",https://stackoverflow.com/questions/53143134/jest-expect-mongoose-timestamps,"['javascript', 'mongoose', 'jestjs']",1837,TRUE,0,1
Shallow Testing in Angular - overwriting the template - is this good practice?,"<p>I have a bit of a hypothetical question regards overwriting the Template in Angular Unit Tests (if this isn't an appropriate question for here please suggest to close rather than mark it down and I will remove / close the question). Members of my team prefer to overwrite the HTML template when unit testing in Angular, so if I had a test it would look something like this:</p>

<pre><code>describe('MyWhateverComponent', () =&gt; {
  let component: MyWhateverComponent;
  let fixture: ComponentFixture&lt;MyWhateverComponent&gt;;
  // lots more things here removed

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [
        MyWhateverComponent
      ],
      schemas: [...],
      imports: [...],
      providers: [...]
    }).overrideTemplate(MyWhateverComponent, '&lt;div&gt;Overridden template&lt;/div&gt;')
      .compileComponents();
  }));
</code></pre>

<p>The reasons my colleagues seem to like doing this as they say it allows them to test the Component code only (as contained in the .ts file), it prevents us having to mock or include directives and we don't want to test Angular bindings like <code>ngIf</code>, <code>ngFor</code>, <code>ngClass</code>, etc, etc... Good arguments but it seems wrong to me as I think you should test what is rendered in the view as it prevents unexpected behaviour or content. This argument doesn't seem to appease my colleagues, can anyone else suggest or think of other reasons why we shouldn't overwrite a template when Unit Testing our Components in Angular. To me it just feels like the nature of our test doesn't really dealwith our true component. I would assume (as I haven't done any checks) that shallow testing would be quicker to execute another reason to support my colleagues. </p>

<p>Any thoughts or opinions are appreciated in advance.</p>
",https://stackoverflow.com/questions/51259317/shallow-testing-in-angular-overwriting-the-template-is-this-good-practice,"['angular', 'unit-testing']",954,TRUE,1,2
How to Mock an Autofac Aggregate Service with Moq?,"<p>I'm on .NET 4.6.2 and using the following versions of the assemblies via Nuget:</p>

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

<p>Autofac    - 4.8.1</p>

<p>Autofac.Extras.AggregateService - 4.1.0</p>

<p>Autofac.Wcf    - 4.1.0</p>

<p>Castle.Core    - 4.3.1</p>

<p><strong>Tests</strong></p>

<p>Autofac.Extras.Moq    - 4.3.0</p>

<p>Moq    - 4.10.1</p>

<p>The setup I'm using for the host container is exactly like the ""Getting Started"" example from the <a href=""https://autofaccn.readthedocs.io/en/latest/advanced/aggregate-services.html"" rel=""nofollow noreferrer"">Docs</a> and you end up with a proxy generated from <code>DynamicProxy</code>, and this works well by eliminating the constructor overloads.</p>

<p>When it comes to unit testing the services that use this type of injection I seem to be stumbling on how to mock it out properly.</p>

<p>I've spent a few hours trying various approaches and none of them have panned out. Here's basically what I have:</p>

<pre><code>public interface IMyAggregateService
{
    IFirstService FirstService { get; }
    ISecondService SecondService { get; }
    IThirdService ThirdService { get; }
    IFourthService FourthService { get; }
}

public class SomeController
{
    private readonly IMyAggregateService _aggregateService;

    public SomeController(IMyAggregateService aggregateService)
    {
        _aggregateService = aggregateService;
    }
}

using (var mock = AutoMock.GetLoose())
{
    //var depends = mock.Mock&lt;IMyAggregateService&gt;().SetupAllProperties(); //Not working 

    //depends.SetupProperty(p =&gt; p.IFirstService, ?? );
    //depends.SetupProperty(p =&gt; p.ISecondService, ?? );
    //depends.SetupProperty(p =&gt; p.IThirdService, ?? );
    //depends.SetupProperty(p =&gt; p.IFourthService, ?? );

    var sut = mock.Create&lt;SomeController&gt;();

    Action action = () =&gt; sut.SomeAction();

    action.Should().xxxx

}
</code></pre>

<p>So the first problem I had was that there are no setters on the <code>IMyAggregateService</code> so the <code>SetupProperty</code> method won't work. When I used <code>SetupAllProperties</code>, everything was null at run-time, so that won't work. I even pulled down the <code>Autofac.Extras.AggregateService</code> code and was checking out the Test project, but there's really nothing I can gleam from it that might help, except the <code>AggregateServiceGenerator</code> might be useful at some point.  </p>

<p>So my questions is,</p>

<blockquote>
  <p>""How do I properly mock an aggregate service, and provide behaviors for it during unit testing?"" </p>
</blockquote>

<p>For extra credit I'd like to know also how to provide a specific implementation of any of the dependencies that are properties, like this:</p>

<pre><code>using (var mock = AutoMock.GetLoose())
{
    mock.Provide&lt;IFirstService&gt;(this.MyImplProperty);
</code></pre>
",https://stackoverflow.com/questions/53982197/how-to-mock-an-autofac-aggregate-service-with-moq,"['c#', 'unit-testing', 'moq', 'autofac']",750,TRUE,1,1
Angular 5 Jasmine issue in VS code,"<p>I am totally new to Angular 5 Unit testing. I have installed all @types/jasmine but still i am getting errors in spec.ts file like describle is not a name and jasmine.createSpyObj does not exists on the typeof Jasmine. Please be informed i have imported jasmine in my spec file. import {} from 'jasmine'(no use though)</p>

<p><strong>package.json</strong></p>

<pre><code>""devDependencies"": {
    ""@angular/cli"": ""1.6.5"",
    ""@angular/compiler-cli"": ""^5.0.0"",
    ""@angular/language-service"": ""^5.0.0"",
    ""@types/jasmine"": ""^2.8.8"",
    ""@types/jasminewd2"": ""~2.0.2"",
    ""@types/node"": ""~6.0.60"",
    ""codelyzer"": ""^4.0.1"",
    ""jasmine-core"": ""^2.99.1"",
    ""jasmine-spec-reporter"": ""~4.1.0"",
    ""karma"": ""~1.7.0"",
    ""karma-chrome-launcher"": ""~2.1.1"",
    ""karma-cli"": ""~1.0.1"",
    ""karma-coverage-istanbul-reporter"": ""^1.2.1"",
    ""karma-jasmine"": ""~1.1.0"",
    ""karma-jasmine-html-reporter"": ""^0.2.2"",
    ""protractor"": ""~5.1.2"",
    ""ts-node"": ""~3.2.0"",
    ""tslint"": ""~5.7.0"",
    ""typescript"": ""~2.4.2""
}
</code></pre>

<p><strong>tsconfig.json</strong></p>

<pre><code>""compileOnSave"": false,
""compilerOptions"": {
    ""outDir"": ""./dist/out-tsc"",
    ""sourceMap"": true,
    ""declaration"": false,
    ""moduleResolution"": ""node"",
    ""emitDecoratorMetadata"": true,
    ""experimentalDecorators"": true,
    ""target"": ""es5"",
    ""typeRoots"": [
        ""node_modules/@types""
    ],
    ""lib"": [
        ""es2017"",
        ""dom""
    ]
}
</code></pre>

<p>please be informed i tried all possibilities but still not clear my i am getting issue in <code>Spec.ts</code> file. Even the intellisense in VS code is not working, to be precise i am seeing all erroneous semnatics error. </p>
",https://stackoverflow.com/questions/51451363/angular-5-jasmine-issue-in-vs-code,"['angular', 'typescript', 'karma-jasmine']",751,TRUE,0,2
Angular Unit Test returns &#39;cannot read property of undefined&#39; for Http Post,"<p>I have a service where where my restpoints are being defined in the constructor so I've set up as variables. When I run my unit tests, these properties are returning as undefined. I'm relatively new to unit testing so I'm not sure if I missed an obvious step... </p>

<p>Here's my 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-js lang-js prettyprint-override""><code>import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class PulldownService {

  public pulldownData: any = [];
  public restURL;

  constructor(public http: HttpClient, public router: Router) {
    this.getEnvConf().subscribe(
        res =&gt; {
          this.restURL = res[window.location.hostname];
        }
    );
  }

  getEnvConf(): Observable&lt;any&gt; {
    return this.http.get('./assets/data/environment-config.json');
  }
  postClaim() {
    let headerTarget;
    if (this.restURL['target_env']) {
      headerTarget = {'Accept': 'application/json', 'Content-Type': 'application/json', 'target_env': this.restURL['targetEnv']};
    } else {
      headerTarget = {'Accept': 'application/json', 'Content-Type': 'application/json'};
    }
    const httpHeaders = new HttpHeaders(headerTarget);
    const options = { headers: httpHeaders };
    return this.http.post( this.restURL['restEndPoint'],
      { 'names' : [
        'PersonRelationType',
        'State',
        ...
        ...

      ]}, options ).subscribe(
      data =&gt; {
        // Success!
        this.pulldownData.push(data);
      }
      ,
      (err: HttpErrorResponse) =&gt; {
        if (err.error instanceof Error) {
          // A client-side or network error occurred.
          this.router.navigateByUrl('/error');
          console.log('An error occurred:', err.error.message);
        } else {
          // The backend returned an unsuccessful response code.
          this.router.navigateByUrl('/error');
          console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
        }
      },
      () =&gt; {
        this.router.navigateByUrl('/getstart');
      }
    );
  }
}</code></pre>
</div>
</div>
</p>

<p>Here's my service.spec.ts</p>

<pre><code>import { PulldownService } from './pulldown.service';
import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { HttpRequest } from '@angular/common/http';

describe('PulldownService', () =&gt; {
  let service: PulldownService;
  let httpTestingController: HttpTestingController;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [ HttpClientTestingModule, RouterTestingModule ],
      providers: [ PulldownService ]
    });
    httpTestingController = TestBed.get(HttpTestingController);
    service = TestBed.get(PulldownService);
  });
  describe('getEnvConfig', () =&gt; {
    it('should call get with the correct url', () =&gt; {
      // no subscribe method called in getEnvConfig
      // service.getEnvConf().subscribe();
      const req = httpTestingController.expectOne('./assets/data/environment-config.json');
      req.flush({ 'restEndPoint': 'http://localhost:8080/typelist?version=1', 'target_env': null});
      httpTestingController.verify();
      // expect(req.request.url.endsWith('environment-config.json')).toEqual(true);
    });
  });
  describe('postClaim', () =&gt; {

    it('should be called with proper arguments', () =&gt; {
      const responseForm = '&lt;form /&gt;';
      const pulldownService = TestBed.get(PulldownService);
      const http = TestBed.get(HttpTestingController);
      let postResponse;

      pulldownService.postClaim().subscribe((response) =&gt; {
        postResponse = response;
      });
      http.expectOne((request: HttpRequest&lt;any&gt;) =&gt; {
        return request.method === 'POST'
          &amp;&amp; request.url === 'http://localhost:8080/typelist?version=1'
          &amp;&amp; JSON.stringify(request.body) === JSON.stringify({
            names: ['State']
          })
          &amp;&amp; request.headers.get('Accept') === 'application/json'
          &amp;&amp; request.headers.get('Content-Type') === 'application/json'
          &amp;&amp; request.headers.get('target_env') === null;
      }).flush(responseForm);
      expect(postResponse).toEqual(responseForm);
    });
  });
})
</code></pre>

<p>The error I keep getting is : TypeError: Cannot read property 'target_env' of undefined. Upon removing 'target_env' from my function, I see a new, different error for 'restEndPoint'. </p>

<p>Any help on this would be greatly appreciated. Thanks</p>
",https://stackoverflow.com/questions/53578044/angular-unit-test-returns-cannot-read-property-of-undefined-for-http-post,"['angular', 'unit-testing', 'karma-jasmine']",7238,TRUE,0,2
How do I start my Spring container once for multiple selenium tests,"<p>I followed tutorial <a href=""https://www.codenotfound.com/jsf-primefaces-automated-unit-testing-selenium.html"" rel=""nofollow noreferrer"">JSF - Primefaces Automated Unit Testing using Selenium</a> without issues (it continues from <a href=""https://www.codenotfound.com/jsf-primefaces-example-spring-boot-maven.html"" rel=""nofollow noreferrer"">JSF - PrimeFaces Example using Spring Boot and Maven</a>).</p>

<p>My question is, how to have multiple such tests?</p>

<p>The reason for asking is, when I created additional such test, my Spring Boot PF application is starting before second test, but fails on ""port already in use"" error.</p>

<p>Preferably I want my Spring Boot appplication to start once and not restart in between tests as it starts in 30 seconds with is too long for a developer to do modify-test round...</p>
",https://stackoverflow.com/questions/53098224/how-do-i-start-my-spring-container-once-for-multiple-selenium-tests,"['selenium', 'spring-boot', 'junit']",48,FALSE,0,0
Maven doesn&#39;t find tests,"<p>I have a Maven project setup. In the project, am using JUnit in for unit testing. When I run tests with <code>mvn test</code> or <code>mvn clean test</code>, no tests are run. Tests are in <code>src/test/java</code> and they all end in <code>Test</code> (they match <code>*Test.java</code>).</p>

<p>This is my pom.xml:</p>

<pre><code>&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;build&gt;
        &lt;plugins&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
                &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt;
                &lt;version&gt;3.7.0&lt;/version&gt;
                &lt;configuration&gt;
                    &lt;source&gt;1.9&lt;/source&gt;
                    &lt;target&gt;1.9&lt;/target&gt;
                &lt;/configuration&gt;
            &lt;/plugin&gt;
        &lt;/plugins&gt;
    &lt;/build&gt;
    &lt;dependencies&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.junit.jupiter&lt;/groupId&gt;
            &lt;artifactId&gt;junit-jupiter-api&lt;/artifactId&gt;
            &lt;version&gt;5.0.3&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.junit.jupiter&lt;/groupId&gt;
            &lt;artifactId&gt;junit-jupiter-params&lt;/artifactId&gt;
            &lt;version&gt;5.1.0&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.commons&lt;/groupId&gt;
            &lt;artifactId&gt;commons-lang3&lt;/artifactId&gt;
            &lt;version&gt;3.1&lt;/version&gt;
        &lt;/dependency&gt;
    &lt;/dependencies&gt;

    &lt;groupId&gt;org.astropeci.ppp4e&lt;/groupId&gt;
    &lt;artifactId&gt;ppp4e&lt;/artifactId&gt;
    &lt;version&gt;1.0&lt;/version&gt;
&lt;/project&gt;
</code></pre>

<p>My entire project structure can be seen here: <a href=""https://bitbucket.org/equator-lang/ppp4e/src/master/"" rel=""nofollow noreferrer"">https://bitbucket.org/equator-lang/ppp4e/src/master/</a> </p>

<p>Any help would be greatly appreciated as I have been trying for many hours to get this to work and have no idea what to do.</p>

<p>EDIT:</p>

<p>After making a test class public, the Maven response changed from:</p>

<pre><code>-------------------------------------------------------
 T E S T S
-------------------------------------------------------

Results :

Tests run: 0, Failures: 0, Errors: 0, Skipped: 0
</code></pre>

<p>To:</p>

<pre><code>-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running org.astropeci.ppp4e.defaultimpl.internal.lexing.MultiplexedTokenBuilderTest
Tests run: 0, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.002 sec

Results :

Tests run: 0, Failures: 0, Errors: 0, Skipped: 0
</code></pre>
",https://stackoverflow.com/questions/50944095/maven-doesnt-find-tests,"['java', 'maven']",3378,TRUE,0,1
Tests passed but code coverage is 0%,"<p>I am still learning to use MSTest and Moq for automated unit testing in my application. I have successfully mocked the code and run it. It is showing that the tests are passed , but the code coverage is 0%. This is my code below.What needs to be changed so that code coverage becomes 100%.</p>

<p>I know this question has been asked a couple of times before, but nothing seems to help me.So can anyone suggest me what am I doing wrong.</p>

<p>Any help is highly appreciated.Thanks.</p>

<p>PS: I'm using Sonarcube for knowing the code coverage.</p>

<pre><code>using Moq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading.Tasks;
using System.Diagnostics.CodeAnalysis;

namespace MyNameSpace
{
    [TestClass]
    public class ApplicationTest
    {
        readonly Helper moqHelper = new Helper();
        [TestMethod()]
        public void GetDataFromDataBaseMoq()
        {
            Task&lt;bool&gt; returnValue;
            Mock&lt;Application&gt; mockType = new Mock&lt;Application&gt;();
            mockType.CallBase = true;
            mockType.Setup(x =&gt; x.GetDataFromDataBase()).Returns(returnValue = moqHelper.GetDataFromDataBaseMoq());
            if (returnValue.Result)
            {
                Assert.IsTrue(true);
            }
            else
            {
                Assert.Fail();
            }
        }
    }

    [ExcludeFromCodeCoverage]
    class Helper
    {
        internal async Task&lt;bool&gt; GetDataFromDataBaseMoq()
        {
            bool returnValue = true;
            return returnValue;
        }
    }
    public class Application : IApplication
    {
        public virtual async Task&lt;bool&gt; GetDataFromDataBase()
        {
            //if data retrive successfull, return true, else false
            return true;
        }
    }
    public interface IApplication
    {
        Task&lt;bool&gt; GetDataFromDataBase();
    }
}
</code></pre>
",https://stackoverflow.com/questions/50851761/tests-passed-but-code-coverage-is-0,"['c#', 'unit-testing', 'moq', 'code-coverage', 'mstest']",2070,TRUE,0,1
Empty test suite with karma in Intellij,"<p>I'm running angularjs unit testing using karma.
I have 2 ways to do that:</p>

<ol>
<li>using grunt</li>
<li>using intellij (with the play icons on the left of the editor)</li>
</ol>

<p>Until now everything worked fine, but now only grunt is really running the tests. Intellij gives me this output:</p>

<blockquote>
  <p>Empty test suite.</p>
  
  <p>Process finished with exit code 0</p>
</blockquote>

<p>I don't know if it's because I updated Intellij recently, or because I removed node_modules and reinstalled it..</p>

<p>this is my karma.conf.js file:</p>

<pre><code>// Karma configuration
// http://karma-runner.github.io/0.12/config/configuration-file.html
// Generated on 2016-01-01 using
// generator-karma 1.0.1

module.exports = function (config) {
    'use strict';

    config.set({
        // enable / disable watching file and executing tests whenever any file changes
        autoWatch: true,

        // base path, that will be used to resolve files and exclude
        basePath: '../',

        // testing framework to use (jasmine/mocha/qunit/...)
        // as well as any additional frameworks (requirejs/chai/sinon/...)
        frameworks: [
            'jasmine-jquery',
            'jasmine'
        ],

        reporters: ['progress', 'coverage'],


        preprocessors: {
            'app/**/*.html': ['ng-html2js'],
            'test/**/*.es6': ['babel'],
            'app/**/*.js': ['coverage']
        },

        // list of files / patterns to load in the browser
        files: [
            // bower:js
            'bower_components/jquery/dist/jquery.js',
            'bower_components/ipaddr.js/lib/ipaddr.js',
            'bower_components/angular/angular.js',
            'bower_components/angular-animate/angular-animate.js',
            'bower_components/angular-cookies/angular-cookies.js',
            'bower_components/angular-resource/angular-resource.js',
            'bower_components/angular-route/angular-route.js',
            'bower_components/angular-sanitize/angular-sanitize.js',
            'bower_components/d3/d3.js',
            'bower_components/d3-cloud/build/d3.layout.cloud.js',
            'bower_components/d3-more-plugins/build/d3-plugins.js',
            'bower_components/nvd3/build/nv.d3.js',
            'bower_components/angular-nvd3/dist/angular-nvd3.js',
            'bower_components/velocity/velocity.js',
            'bower_components/velocity/velocity.ui.js',
            'bower_components/angular-ui-router/release/angular-ui-router.js',
            'bower_components/javascript-detect-element-resize/detect-element-resize.js',
            'bower_components/angular-gridster/src/angular-gridster.js',
            'bower_components/perfect-scrollbar/js/perfect-scrollbar.jquery.js',
            'bower_components/iso-3166-country-codes-angular/dist/iso-3166-country-codes-angular.min.js',
            'bower_components/angular-messages/angular-messages.js',
            'bower_components/lodash/lodash.js',
            'bower_components/angular-vs-repeat/src/angular-vs-repeat.js',
            'bower_components/moment/moment.js',
            'bower_components/lumx/dist/lumx.js',
            'bower_components/v-accordion/dist/v-accordion.js',
            'bower_components/ua-parser-js/src/ua-parser.js',
            'bower_components/smooth-scrollbar/dist/smooth-scrollbar.js',
            'bower_components/angular-smooth-scrollbar/dist/angular-smooth-scrollbar.js',
            'bower_components/codemirror/lib/codemirror.js',
            'bower_components/codemirror/addon/fold/foldcode.js',
            'bower_components/codemirror/addon/fold/foldgutter.js',
            'bower_components/codemirror/addon/fold/xml-fold.js',
            'bower_components/codemirror/addon/fold/brace-fold.js',
            'bower_components/codemirror/addon/search/searchcursor.js',
            'bower_components/codemirror/addon/scroll/simplescrollbars.js',
            'bower_components/codemirror/addon/selection/active-line.js',
            'bower_components/codemirror/addon/edit/matchbrackets.js',
            'bower_components/codemirror/addon/mode/multiplex.js',
            'bower_components/codemirror/mode/javascript/javascript.js',
            'bower_components/codemirror/mode/htmlmixed/htmlmixed.js',
            'bower_components/codemirror/mode/css/css.js',
            'bower_components/codemirror/mode/http/http.js',
            'bower_components/codemirror/mode/xml/xml.js',
            'bower_components/angular-ui-codemirror/ui-codemirror.js',
            'bower_components/angular-resizable/src/angular-resizable.js',
            'bower_components/ngstorage/ngStorage.js',
            'bower_components/ng-csv/build/ng-csv.js',
            'bower_components/jquery-mousewheel/jquery.mousewheel.js',
            'bower_components/js-beautify/js/lib/beautify.js',
            'bower_components/js-beautify/js/lib/beautify-css.js',
            'bower_components/js-beautify/js/lib/beautify-html.js',
            'bower_components/jquery-ui/jquery-ui.js',
            'bower_components/angular-ui-sortable/sortable.js',
            'bower_components/jqueryui-touch-punch/jquery.ui.touch-punch.min.js',
            'bower_components/lz-string/libs/lz-string.min.js',
            'bower_components/tippy.js/dist/tippy.js',
            'bower_components/crypto-js/core.js',
            'bower_components/crypto-js/enc-base64.js',
            'bower_components/crypto-js/md5.js',
            'bower_components/crypto-js/evpkdf.js',
            'bower_components/crypto-js/cipher-core.js',
            'bower_components/crypto-js/aes.js',
            'bower_components/angular-mocks/angular-mocks.js',
            'bower_components/jasmine/lib/jasmine-core/jasmine.js',
            'bower_components/jasmine-jquery/lib/jasmine-jquery.js',
            // endbower
            ""app/scripts/**/*.js"",
            ""app/modules/some-folder/scripts/module.es6"",
            ""app/modules/mobile-replay/scripts/module.es6"",
            ""app/modules/web-replay/scripts/module.es6"",
            ""app/modules/period-picker/scripts/period-picker.es6"",
            //""test/mock/**/*.es6"",
            ""app/modules/**/*.es6"",
            ""test/spec/**/*.es6"",
            'app/views/**/*.html',
            'app/modules/*/views/**/*.html'
        ],

        proxies: {
            '/data/': '/data/'
        },

        // list of files / patterns to exclude
        exclude: [
            'app/modules/web-replay/scripts/replay-libs.js',
            'app/detector-beacon.min.js'
        ],

        // web server port
        port: 8082,

        // Start these browsers, currently available:
        // - Chrome
        // - ChromeCanary
        // - Firefox
        // - Opera
        // - Safari (only Mac)
        // - PhantomJS
        // - IE (only Windows)
        browsers: [
            'ChromeHeadless'
        ],

        // Which plugins to enable
        plugins: [
            '@metahub/karma-jasmine-jquery',
            'karma-*'
        ],

        ngHtml2JsPreprocessor: {
            stripPrefix: 'app/',
            moduleName: 'html-templates'
        },

        babelPreprocessor: {
            options: {
                presets: [['env',{
                    ""targets"": {
                        ""browsers"": [""last 10 Chrome major versions"", ""last 10 Firefox major versions"", ""ie &gt;= 11"", ""safari &gt;= 9""]
                    }
                }]],
                sourceMap: 'inline'
            }
        },

        // Continuous Integration mode
        // if true, it capture browsers, run tests and exit
        singleRun: false,

        colors: true,

        // level of logging
        // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
        logLevel: config.LOG_INFO,

        browserDisconnectTolerance: 8,
        browserNoActivityTimeout: 10000,

        // Uncomment the following lines if you are using grunt's server to run the tests
        // proxies: {
        //   '/': 'http://localhost:9000/'
        // },
        // URL root prevent conflicts with the site root
        // urlRoot: '_karma_'
    });
};
</code></pre>

<p>Example Project (I Can't upload my project): </p>

<p>Tested file</p>

<pre><code>angular.module('app', [])
.controller('PasswordController', function PasswordController($scope) {
  $scope.password = '';
  $scope.grade = function() {
    var size = $scope.password.length;
    if (size &gt; 8) {
      $scope.strength = 'strong';
    } else if (size &gt; 3) {
      $scope.strength = 'medium';
    } else {
      $scope.strength = 'weak';
    }
  };
});
</code></pre>

<p>testing file:</p>

<pre><code>describe('PasswordController', function() {
  beforeEach(module('app'));

  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('$scope.grade', function() {
    it('sets the strength to ""strong"" if the password length is &gt;8 chars', function() {
      var $scope = $rootScope.$new();
      var controller = $controller('PasswordController', { $scope: $scope });
      $scope.password = 'longerthaneightchars';
      $scope.grade();
      expect($scope.strength).toEqual('strong');
    });
  });
});
</code></pre>
",https://stackoverflow.com/questions/51635216/empty-test-suite-with-karma-in-intellij,"['angularjs', 'unit-testing', 'intellij-idea', 'jasmine', 'karma-runner']",910,FALSE,0,0
how do I mock Identity.UserManager&lt;TUser&gt;.GetUserName?,"<p>I am trying to do Unit Testing for methods which checks if the user is logged in. I am using xunit and moq and I am able to create a mock user object with the correct claims and everything but it(_userManager.GetUserName(User);) returns null in the controller.</p>

<p>I am not able to pass the mock user as a valid user in the controller method ""GetUserName"". </p>

<pre><code>public virtual string GetUserName(System.Security.Claims.ClaimsPrincipal principal);
/// &lt;summary&gt;
/// Returns the User ID claim value if present otherwise returns null.
/// &lt;/summary&gt;
/// &lt;param name=""principal""&gt;The &lt;see cref=""T:System.Security.Claims.ClaimsPrincipal"" /&gt; instance.&lt;/param&gt;
/// &lt;returns&gt;The User ID claim value, or null if the claim is not present.&lt;/returns&gt;
/// &lt;remarks&gt;The User ID claim is identified by &lt;see cref=""F:System.Security.Claims.ClaimTypes.NameIdentifier"" /&gt;.&lt;/remarks&gt;
</code></pre>

<p>Any help would be greatly appreciated! Thank you!</p>

<p>Controller:
When I debug the test, the line var user returns null..</p>

<pre><code>[HttpPost]
public async Task&lt;IActionResult&gt; Post([FromForm] Product productModel)
{
    var user = _userManager.GetUserName(User);
    if (user == null)
    {
        return Json(new { success = false, value = ""Please Log in to Continue."" });
    }
    if (productModel.Id == Guid.Empty)
    {               
        try
        {
            productModel.CreatedBy = user;
            productModel.CreatedDate = DateTime.Now;

            await _unitOfWork.ProductRepo.AddProductAsync(productModel);
            await _unitOfWork.Complete();

            return Json(new {id=productModel.Id, success = true, value = ""Successfully Added."" });
         }
         catch (Exception ex)
         {
             _logging.Invoke(ex, ""Failed."");
             return Json(new {success = false, value = ""Failed.""});
         }                
    }
}
</code></pre>

<p>Unit Test:</p>

<pre><code>[Fact]
public async Task Post_ValidUser_EmptyId_Add_ReturnSuccess()
{
    var user = GetUser();

    var userManager = _context.UserManager(user.Id, out _httpContext);

    var controller = new ProductsController(_mockUnitOfWork.Object, userManager, null, null);
    controller.ControllerContext.HttpContext = _httpContext;

    var productModel = new Product()
    {
        Id = Guid.NewGuid(),
        Title = ""Test"",
        CreatedDate = DateTime.Now
    };
    var result = await controller.Post(productModel);
    Assert.IsType&lt;JsonResult&gt;(result);

    var responseString = result as JsonResult;
    Assert.NotNull(responseString);
    var success = responseString.Value.GetType().GetProperty(""success"")?.GetValue(responseString.Value);
    Assert.Equal(true, success);
}
</code></pre>

<p>InitHttpContext:</p>

<pre><code>public UserManager&lt;ApplicationUser&gt; UserManager(string userId, out HttpContext httpcontext)
{
    var claims = new List&lt;Claim&gt; { new Claim(ClaimTypes.NameIdentifier, userId) };

    var userManager = _serviceProvider.GetRequiredService&lt;UserManager&lt;ApplicationUser&gt;&gt;();
    var signInManager = _serviceProvider.GetRequiredService&lt;SignInManager&lt;ApplicationUser&gt;&gt;();

    var httpContext = _serviceProvider.GetRequiredService&lt;IHttpContextAccessor&gt;().HttpContext;
    httpContext.User = new ClaimsPrincipal(new ClaimsIdentity(claims));
    httpcontext = httpContext;
    //controller.ControllerContext.HttpContext = httpContext;

    return userManager;
}
</code></pre>
",https://stackoverflow.com/questions/52428703/how-do-i-mock-identity-usermanagertuser-getusername,"['c#', 'asp.net', 'moq', 'xunit']",207,FALSE,0,0
Are they really using redux-saga in real projects? Is it safe to migrate from thunk to saga?,"<p>I am using redux-thunk in my current project. I recently found redux-saga one of our peers suggested to my teammates to migrate from thunk to saga.</p>

<p><strong>Benefits of using Saga</strong></p>

<ol>
<li>Sagas uses generator functions the call to the fetch api with the
yield keyword will block until the promise is resolved.</li>
<li>Unit testing is easy in saga as compared to thunk.</li>
</ol>

<p>By simply looking those above two benefits I dont want to migrate to saga.
Is there any advantage of using saga? If so please advice me.</p>
",https://stackoverflow.com/questions/50097526/are-they-really-using-redux-saga-in-real-projects-is-it-safe-to-migrate-from-th,['redux-saga'],408,TRUE,0,2
How to jumpstart on html5 JavaScript migration for struts based UI?,"<p>I am not a specialist in UI/UX design and hence pardon my knowledge in this space. My team is however tasked to move away from Struts. And the platform of choice is JavaScript with html5. Now the questions that I have are around the tools and best practices people use towards the following:</p>

<ol>
<li>What IDE do you use?</li>
<li>What is the equivalent of JUNIT for unit testing both?</li>
<li>Any well known test automation platform (selenium?)</li>
<li>Web server technologies </li>
<li>Build and deployment tools</li>
<li>Sites where I can refer to for all of the above</li>
</ol>
",https://stackoverflow.com/questions/52788936/how-to-jumpstart-on-html5-javascript-migration-for-struts-based-ui,"['javascript', 'html']",43,FALSE,0,0
Why does the view methods does not get called inside an Observable which is inside the presenter on a unit test?,"<p>I am new to Android Unit Testing and we are currently using MVP+RxJava+Dagger 2. I wrote this test which fails in unit test, but works in production code:</p>

<pre><code>@Override
public void retrieveListOfBillers() {
    getMvpView().showLoading();
    getCompositeDisposable().add(
        getDataManager()
            .doServerGetBillersList()
            .observeOn(getSchedulerProvider().ui())
            .subscribeOn(getSchedulerProvider().io())
            .subscribe( response -&gt;{
                for (Datum data : response.getData()) {
                    getMvpView().setUpRecyclerView(enrollmentBillers);
                    getMvpView().showDefaultViews();
                    getMvpView().hideLoading();
                }, throwable -&gt; {
                    ...
</code></pre>

<p>And this is how I do it in the test:</p>

<pre><code>@Test
public void testGetListOfBillersCallsSetupRecyclerView(){
    mPresenter.retrieveListOfBillers();
    verify(mView).showLoading();
    verify(mView).setUpRecyclerView(anyList());
}
</code></pre>

<p>This is how I instanciated the setup for the test:</p>

<pre><code>@Before
public void setUp() {
    // Mockito has a very convenient way to inject mocks by using the @Mock annotation. To
    // inject the mocks in the test the initMocks method needs to be called.
    MockitoAnnotations.initMocks(this);
    CompositeDisposable compositeDisposable = new CompositeDisposable();
    mTestScheduler = new TestScheduler();
    testSchedulerProvider = new TestSchedulerProvider(mTestScheduler);
    mPresenter = new CreateBillerContactPresenter&lt;&gt;(
            dataManager,
            testSchedulerProvider,
            compositeDisposable
    );
    mPresenter.onAttach(mView);


when(dataManager.doServerGetBillersList()).thenReturn(Observable.just(getBillerListResponse));
</code></pre>

<p>I believe it has something to do with the TestScheduler but I need someone who actually knows what is the problem here, which is why my test code fails to call setupRecyclerView, and other expected view method calls from the presenter?</p>
",https://stackoverflow.com/questions/52640118/why-does-the-view-methods-does-not-get-called-inside-an-observable-which-is-insi,"['android', 'mockito', 'rx-java2', 'android-mvp']",88,TRUE,0,1
"Code to make complete graph fails unit test, yet produces correct answer","<p>The following code produces this error during unit testing at the line marked with a comment:
<code>(Exception: TypeError) ""'int' object is not iterable""</code></p>

<p>The visual debugger detects no errors and produces the desired output. That is, make_complete_graph(2) yields the graph {0: set([1]), 1: set([0])}.</p>

<p>The graph representation is non-negotiable.</p>

<p>The error occurs on the highlighted line. The permutations routine is included in the original file, as the unit tester has issues importing itertools. However, I have substituted itertools for brevity here. Any thoughts on why this is happening would be appreciated. </p>

<pre><code>from itertools import permutations

def make_complete_graph(num_nodes):
    '''
    Input: Number of nodes (an int) in graph.
    Output: Complete directed graph containing all possible edges subject to restriction
    that self-loops are disallowed &amp; number of nodes must be positive. If number of nodes is
    not positive, empty graph is returned. 
    '''
    if num_nodes &gt; 0:
        new_dict = {}
        nodes = [i for i in range(0, num_nodes)]
        edges = list(permutations(nodes, r=2))
        for n in nodes:
            new_dict[n] = set()
            for e in edges:
                if n == e[0]:
                    # the error occurs at this line
                    new_dict[n].add(set(e[1]))
        return new_dict
    else:
        return {num_nodes: set([])}
</code></pre>
",https://stackoverflow.com/questions/49718082/code-to-make-complete-graph-fails-unit-test-yet-produces-correct-answer,"['python', 'python-2.7', 'graph']",26,TRUE,0,1
API unit test using chai giving wrong result,"<p>I am writing unit test for my API which uses nodejs and mongoose. I am using mocha, chai, and chai-http to do unit testing.</p>

<p>I am testing a POST request that creates a customer. The first test creates a customer, and it passes. The last test will try to create a customer but should fail since the email already exist, but that fails since the request creates a new customer.</p>

<p>I tried doing the requests manually using postman and it gives the right behaviour.</p>

<p>Here are the tests:</p>

<pre><code>describe('Customer', () =&gt; {

//Before each test we empty the database
beforeEach((done) =&gt; {
    Customer.remove({}, (err) =&gt; {
        done();
    });
});

// Creating Customer test
describe('POST Account - Creating customer account', () =&gt; {

    it('creating a user with correct arguments', (done) =&gt; {

        // defining the body
        var body = {
            first_name : ""Abdulrahman"",
            last_name : ""Alfayad"",
            email: ""test@test.com"",
            password: ""123""
        };

        chai.request(server)
        .post('/api/customer/account')
        .send(body).end((err, res) =&gt; {
            res.body.should.have.property('status').and.is.equal('success');
            res.body.should.have.property('message').and.is.equal('customer was created');
            done();
        });
    });

    it('creating a user with incorrect arguments', (done) =&gt; {

        // defining the body
        var body = {
            first_name: ""Abdulrahman"",
            email: ""test@test.com"",
        };

        chai.request(server)
            .post('/api/customer/account')
            .send(body).end((err, res) =&gt; {
                res.body.should.have.property('status').and.is.equal('failure');
                res.body.should.have.property('message').and.is.equal('no arguments were passed');
                done();
            });
    });

    it('creating a user with an already existing email in the DB', (done) =&gt; {

        // defining the body
        var body = {
            first_name: ""Abdulrahman"",
            last_name: ""Alfayad"",
            email: ""test@test.com"",
            password: ""123""
        };

        chai.request(server)
            .post('/api/customer/account')
            .send(body).end((err, res) =&gt; {
                res.body.should.have.property('status').and.is.equal('failure');
                res.body.should.have.property('message').and.is.equal('email already exist');
                done();
            });
    });

});
</code></pre>

<p>});</p>
",https://stackoverflow.com/questions/52451125/api-unit-test-using-chai-giving-wrong-result,"['node.js', 'mongoose', 'mocha.js', 'chai', 'chai-http']",201,TRUE,0,1
ant task to run JUnit tests from a jar (but only files that have tests!),"<p>We're using JUnit inside a custom framework to test an applications behaviour. We're not actually doing unit testing, just leveraging JUnit.</p>

<p>I've created an ant task to run all the tests in the jar file, but unfortunately it's trying to run <em>everything</em> as a JUnit test. Since the jar file contains things besides just the tests (it contains the supporting framework) this is a problem.</p>

<p>Is there a way to make the junit task only run things marked as tests (we use @Test)?</p>

<p>Currently my ant task looks like this:</p>

<pre><code>&lt;target name=""test""&gt;
    &lt;junit printsummary=""yes"" haltonfailure=""no""&gt;
        &lt;classpath refid=""library.third-party.classpath"" /&gt;
        &lt;classpath&gt;
            &lt;pathelement location=""${basedir}/build/jar/fidTester.jar"" /&gt;
        &lt;/classpath&gt;

        &lt;formatter type=""plain"" /&gt;
        &lt;formatter type=""xml"" /&gt;

        &lt;batchtest fork=""no"" todir=""${basedir}/reports""&gt;
            &lt;zipfileset src=""${basedir}/build/jar/fidTester.jar"" includes=""**/tests/**/*.class"" /&gt;
        &lt;/batchtest&gt;

    &lt;/junit&gt;
&lt;/target&gt;
</code></pre>
",https://stackoverflow.com/questions/50714591/ant-task-to-run-junit-tests-from-a-jar-but-only-files-that-have-tests,"['junit', 'ant']",351,FALSE,0,1
Why is main not found when building a project that includes gtest with cmake?,"<p>I have a very small project to which I created some unit testing with GTest. 
To build it, I'm using CMake. It compiles just fine, but it's giving me the error shown below. I include all make output just in case.</p>

<pre><code>Scanning dependencies of target trace
[ 33%] Building C object CMakeFiles/trace.dir/trace/system_trace.c.o
[ 33%] Built target trace
Scanning dependencies of target data-test
[ 66%] Building CXX object CMakeFiles/data-    test.dir/data_testsuite.cpp.o
[100%] Linking CXX executable data-test
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status
CMakeFiles/data-test.dir/build.make:86: recipe for target 'data-test'     failed
make[2]: *** [data-test] Error 1
CMakeFiles/Makefile2:72: recipe for target 'CMakeFiles/data-test.dir/all' failed
make[1]: *** [CMakeFiles/data-test.dir/all] Error 2
Makefile:83: recipe for target 'all' failed
make: *** [all] Error 2
</code></pre>

<p>And I have no idea why is not finding main. Main is part of GTest which I'm including as it can be seen on the <strong>CMakeLists.txt</strong>:</p>

<pre><code>cmake_minimum_required(VERSION 2.8)

set (CMAKE_CXX_STANDARD 11)

project(data-test C CXX)

set(CMAKE_C_FLAGS_DEBUG   ""-g3 -Og -Wall"")
set(CMAKE_CXX_FLAGS_DEBUG ""-g3 -Og -Wall"")

set(CMAKE_C_FLAGS_RELEASE   ""-g0 -O3 -Wall"")
set(CMAKE_CXX_FLAGS_RELEASE ""-g0 -O3 -Wall"")

include(GoogleTest)

set(CMAKE_THREAD_PREFER_PTHREAD TRUE)
set(THREADS_PREFER_PTHREAD_FLAG TRUE)
find_package(Threads REQUIRED)

find_package(GTest REQUIRED)

include_directories(cfg)
include_directories(system)
include_directories(system/include)

include(trace/CMakeLists.txt)

add_executable(data-test
    $&lt;TARGET_OBJECTS:trace&gt;
    data_testsuite.cpp
)

target_link_libraries(data-test Threads::Threads GTest::GTest)

gtest_discover_tests(data-test)
</code></pre>

<p>And as you can see from the <strong>make</strong> command output, it is compiling just fine.</p>

<p>Do you know what is going on?</p>
",https://stackoverflow.com/questions/53565189/why-is-main-not-found-when-building-a-project-that-includes-gtest-with-cmake,"['build', 'cmake']",904,TRUE,0,1
Assigning JSON data to a variable or constant and doing string comparison - AngularJS,"<p>I am new to AngularJS and started working on web unit testing using test cafe. My problem is in inspect element I have set of JSON data, which is generated when I pass few text in text field and click on search. I need to get this JSON data to a variable or constants for string comparison. JSON data is like:</p>

<pre><code>value = {
    ""CVLocation"": """",
    ""PostalCode"": """",
    ""DistanceInKms"": """",
    ""CVJobTitles"": ""java"",
    ""CVSkills"": """",
    ""CVIndustries"": """",
    ""CVLicenses"": """",
    ""CVWhiteBoard"": """",
    ""CVCustomQuery"": """",
    ""CVFilterDataList"": [],
    ""JobTitlesSearchedWithIn"": 2,
    ""SkillsSearchedWithIn"": .......
}
</code></pre>

<p>Could anyone help me how can do string comparison with these JSON data?</p>

<p><a href=""https://i.stack.imgur.com/OLXwE.png"" rel=""nofollow noreferrer"">screenshot of my web page</a></p>

<p>how can i get this JSON data which is generated in Element blog to my code?</p>
",https://stackoverflow.com/questions/49158706/assigning-json-data-to-a-variable-or-constant-and-doing-string-comparison-angu,"['angularjs', 'json']",859,FALSE,0,2
Spring jdbctemplate h2 dynamically switch schema,"<p>I'm trying to have h2's in memory database switch schema's during unit testing. Almost all my data is in the default schema <code>PUBLIC</code> but to mimic how production works I need to switch to another schema <code>SETTINGS</code> for 1 query.</p>

<p>I have tried to switch schema's with <code>jdbcTemplate.getDataSource().getConnection().setSchema(""SETTINGS"");</code>
but when I log the value of <code>jdbcTemplate.getDataSource().getConnection().getSchema();</code> I get the default public one.<br />
So my query fails because I get a BadSqlGrammarException because the table I try to query isn't found, which makes sense since it's in another schema.</p>

<p>Can anyone help me out with this one?</p>

<p>Thx!</p>
",https://stackoverflow.com/questions/51820735/spring-jdbctemplate-h2-dynamically-switch-schema,"['spring-boot', 'h2', 'jdbctemplate']",511,TRUE,0,1
DataTable/DataSet to IFormFile(Excel) to Unit Test,"<p>I am unit testing a new API. I need to write a test method to call a method that converts excel to datatable using ExcelDataReader.DataSet.</p>

<p>The ExcelDataReader library documentation doesn't indicate that there is any method to go form a dataset to an excel file with it. The REST method in the controller for the API takes in the file as an IFormFile. So I need to go from DataTable/DataSet to an IFormFile that can be identified as an xlsx.</p>

<p>How do you go from DataTable to IFormfile(Excel) in .net core?</p>
",https://stackoverflow.com/questions/52007757/datatable-dataset-to-iformfileexcel-to-unit-test,"['unit-testing', '.net-core', 'dataset', 'exceldatareader', 'iformfile']",407,FALSE,0,0
How to test view controller with XIB file using Quick?,"<p>I'm using Quick library for unit testing.</p>

<p>I'm trying to test <code>ViewController</code>, view of which is made as <code>XIB</code>.</p>

<p>I connected view with file owner, and view component with view controller.</p>

<p>And for <code>viewDidLoad</code> test, I accessed view to trigger <code>viewDidLoad()</code>.</p>

<p>Here's my code.</p>

<pre><code>override func spec() {
    super.spec()

    var sut: QuestionViewController!

    describe(""viewDidLoad"") {
        afterEach {
            sut = nil
        }
        beforeEach {
            sut = QuestionViewController(question: ""Q1"")
            _ = sut.view
        }

        it(""renders question header text"") {
            expect(sut.headerLabel.text).toEventually(equal(""Q1""))
        }
    }

}
</code></pre>

<p>But when run the test, nothing happens with just 'test fail'.
I setup break point inside spec(), but it just pass through.(nothing happens)</p>

<p>After removing xib file and make UI components programmatically, the test finally succeeded.</p>

<p>How to test <code>ViewController</code>(viewDidLoad etc.) that contains xib file when using <code>Quick</code>?</p>
",https://stackoverflow.com/questions/53721425/how-to-test-view-controller-with-xib-file-using-quick,"['swift', 'unit-testing', 'xib', 'nimble']",735,TRUE,0,1
Implementing Codeception with Yii1,"<p>I am trying to do unit testing for my project done in Yii1. These are the steps I took</p>

<p>Added composer.json and added the following</p>

<pre><code>{
    ""require-dev"": {
        ""codeception/codeception"": ""2.3.*"",
        ""codeception/yii-bridge"":""dev-master""
    }
}
</code></pre>

<p>and created the complete suit by bootstrapping</p>

<p>In my unit.suit.yml I added </p>

<pre><code>- Yii1:
        appPath: '../index-test.php'
        url: 'http://localhost/pricingdb/index-test.php/'       
</code></pre>

<p>In my index-test.php I have</p>

<pre><code>&lt;?php

defined('DS') or define('DS', DIRECTORY_SEPARATOR);

$yii=dirname(__FILE__).'/../../yii-1.1.12.b600af/framework/yii.php';
$config=dirname(__FILE__).'/protected/config/test.php';

defined('YII_DEBUG') or define('YII_DEBUG',true);

require_once($yii);
require_once __DIR__.DS.'vendor'.DS.'autoload.php';

return array(
       'class' =&gt; 'CWebApplication',
       'config' =&gt; $config,
);
</code></pre>

<p>In my config/test.php I have</p>

<pre><code>&lt;?php

return CMap::mergeArray(
                require(dirname(__FILE__) . '/main.php'), array(
            'components' =&gt; array(
                'request' =&gt; array(
                    'class' =&gt; 'CodeceptionHttpRequest'
                ),
            ),
                )
);
</code></pre>

<p>When I try to run unit tests from my protected folder with the following command</p>

<pre><code>..\vendor\bin\codecept run unit
</code></pre>

<p>I get the following message</p>

<pre><code>In Yii1.php line 173:

  Yii1 module is not configured!

  Codeception-Yii Bridge is not launched. In order to run tests you need to install https://github.com/Codeception/Yi
  iBridge Implement function 'launch_codeception_yii_bridge' to load all Codeception overrides
</code></pre>

<p>What am I missing here? What does it mean to ""Implement function 'launch_codeception_yii_bridge' to load all Codeception overrides"" ?
How do I do that?</p>
",https://stackoverflow.com/questions/49315676/implementing-codeception-with-yii1,"['php', 'unit-testing', 'yii', 'codeception']",706,TRUE,0,1
Doing a Spy in a Mocha (Ruby) test?,"<p>My team uses <a href=""https://github.com/freerange/mocha"" rel=""nofollow noreferrer"">Mocha</a> for unit testing in Ruby. I'd like to use Mocha to add a ""spy"" on a method.  That is, I'd like to write a unit test using Mocha that verifies that the code under test calls a particular method on another class, without overriding the implementation of that method.</p>

<p>Is that possible? If so, how can it be done? </p>

<p>I've tried using Mocha's <a href=""http://gofreerange.com/mocha/docs/Mocha/Mock.html#expects-instance_method"" rel=""nofollow noreferrer""><code>expects</code></a>, like:</p>

<pre><code>MyModule::MyClass.expects(:my_method)
</code></pre>

<p>However, that overrides the implementation of <code>my_method</code>. In my particular situation, I need to both verify that <code>my_method</code> was called, and to have the actual implementation of the method execute during the test.</p>
",https://stackoverflow.com/questions/48951353/doing-a-spy-in-a-mocha-ruby-test,"['ruby-on-rails', 'unit-testing', 'ruby-mocha']",260,FALSE,4,0
Angular: Is there a way to mock the value of PLATFORM_ID in a unit test?,"<p>I am using Angular Universal. I have a guard for a route that behaves differently depending on if I am running on the server or the browser platform. Here is the guard:</p>

<pre><code>export class UniversalShellGuard implements CanActivate {
  private isBrowser: boolean;

  constructor(@Inject(PLATFORM_ID) private platformId: Object) {
    console.log('PLATFORM_ID = ' + platformId);
    this.isBrowser = isPlatformBrowser(this.platformId);
  }

  canActivate(): Observable&lt;boolean&gt; | Promise&lt;boolean&gt; | boolean {
    return !this.isBrowser;
  }
}
</code></pre>

<p>As you can see, the guard is injecting <code>PLATFORM_ID</code> and uses it to determine if he <code>canActivate()</code> or not.</p>

<p>Now, I wanted to write a simple unit test for the guard and did the following:</p>

<pre><code>describe('UniversalShellGuard', () =&gt; {
  let guard: UniversalShellGuard;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      providers: [
        UniversalShellGuard,
        // Idea: for now I just want to test the behaviour if I would be on the browser, so I would just use a fixed value for PLATFORM_ID
        { provide: PLATFORM_ID, useValue: PLATFORM_BROWSER_ID },
      ],
    });

    guard = TestBed.get(UniversalShellGuard);
  });

  it('should deny', () =&gt; {
    expect(guard.canActivate()).toBe(false);
  });
});
</code></pre>

<p>But it gives the following error:</p>

<pre><code>ERROR in ./src/app/universal-shell.guard.spec.ts
Module not found: Error: Can't resolve '@angular/common/src/platform_id' in '/my-app-path/src/app'
 @ ./src/app/universal-shell.guard.spec.ts 4:0-70 11:50-69
 @ ./src sync \.spec\.ts$
 @ ./src/test.ts
</code></pre>

<p>I even tried a simple and straight forward construction of the guard, without using the angular <code>TestBed</code>:</p>

<pre><code>it('should deny', () =&gt; {
  const guard = new UniversalShellGuard(PLATFORM_BROWSER_ID);
  expect(guard.canActivate()).toBe(false);
});   
</code></pre>

<p>Same error.</p>

<p>Is there any way to provide a fixed value for <code>PLATFORM_ID</code> for properly unit-testing such a guard?</p>
",https://stackoverflow.com/questions/52185873/angular-is-there-a-way-to-mock-the-value-of-platform-id-in-a-unit-test,"['angular', 'unit-testing', 'guard', 'angular-universal']",4398,TRUE,9,2
Mock componentDidMount lifecycle method for testing,"<p>I have a component which uses <code>axios</code> within <code>componentDidMount</code> to retrieve data from the server. When using Jest / Enzyme for unit testing the component, the tests fail with a network error.</p>

<p>How do I mock <code>componentDidMount</code> so that the <code>axios</code> call to the server does not happen?</p>

<p>The component in question uses <a href=""http://react-dnd.github.io/react-dnd/docs-overview.html"" rel=""nofollow noreferrer"">React DnD</a> and is a <code>DragDropContext</code>.</p>

<pre><code>class Board extends Component {
    componentDidMount() {
        this.load_data();
    }

    load_data = () =&gt; {
        // axios server calls here
    }
}
export default DragDropContext(HTML5Backend)(Board);
</code></pre>

<p>Example test:</p>

<pre><code>it('should do something', () =&gt; {
    const board = shallow(&lt;Board /&gt;);
    // get the boardInstance because board is wrapped in Reactdnd DragDropContext
    const boardInstance = board.dive().instance();
    boardInstance.callSomeMethodToTestIt();
    expect(testSomething);
}
</code></pre>

<p>So I just need to mock <code>componentDidMount</code> or <code>load_data</code> so that it doesn't try to call the server. If the <code>load_data</code> method was being passed in as a prop, I could simply set that prop to <code>jest.fn()</code>. However this is my top level component which does not receive any props.</p>
",https://stackoverflow.com/questions/50344545/mock-componentdidmount-lifecycle-method-for-testing,"['javascript', 'reactjs', 'jestjs', 'enzyme']",8565,TRUE,3,2
How to mock a method from a class that it is from jar (JAVA),"<p>I can't resolve an issue that it has been bugging me out last week.</p>

<p>It is possible to mock a class that it is inside a jar so I don't call the real method.</p>

<p><strong>Example:</strong> </p>

<blockquote>
  <p>3 Classes (Class Person, Class PersonTest, Class PersonExternalJar)</p>

<pre><code>public class Person{

     private PersonalExternalJar pej;

     public void methodA(){
          *do some stuff*
           pej = new PersonalExternalJar();
           ArrayList people = pej.doSomething(AnyString,AnyString,AnyObject);
           *do some stuff*
           People2 p = new People2(); //  This class it is somewhere in my project lets say
           String SomePeople = p.doSomeStuff();

     }
}


@RunWith(MockitoJUnitRunner.class)
public class PersonTest{
     @Mock private People2 p;
     @Mock private PersonExtenarlJar pej; // I get an error like I can't find this class or some internal thing of this class.

     @InjectMocks private Person  pr;

     @Test
     public void personTest(){
          *do some stuff*
           pr = new Personal();
           //try both declare the class and not declaring the class
           //when I do the next 
           Mockito.doReturn(""anything"").when(p).doSomeStuff(); // WORKS
           Mockito.doReturn(AnyArray).when(pej).doSomething(AnyString,AnyString,AnyObject) // CAN'T DO THIS 
           //Doesn't work
           //Alternatively I tried to take off the annotation mock and do the following.   
            PersonalExternalJar pej = Mockito.mock(PersonalExternalJar.class) 
            //Still doesn't work.
     }
}
</code></pre>
  
  <p>As I understood about unit testing it is to isolate the class and try its behaviour without calling external methods (that's why I use mockito).</p>
</blockquote>

<p>Mockito core version 1.10.19 
Junit     4.12.</p>

<p>I hope someone can give me a solution or make me see another perspective or make me understand that I might be confused about concepts.</p>
",https://stackoverflow.com/questions/48510471/how-to-mock-a-method-from-a-class-that-it-is-from-jar-java,"['java', 'unit-testing', 'mockito', 'junit4']",4715,TRUE,3,1
Organization of unit tests with C++ Boost.Test?,"<p>I've been reading about unit testing and I'm a little confused as to how the tests of different program components are organized. I'm assuming that each class usually has its own set of unit tests. If so:</p>
<ol>
<li>Should every class to be tested get its own unit test .cpp file?</li>
<li>How to combine all the unit test .cpp files together?</li>
<li>Do the unit test files go into their own separate VS project? If so, is it run manually when desired, or can it somehow be connected to your actual project?</li>
<li>What is the purpose of test suits?</li>
</ol>
",https://stackoverflow.com/questions/50946354/organization-of-unit-tests-with-c-boost-test,"['c++', 'unit-testing', 'boost']",169,TRUE,3,1
Confirm that middleware is in use,"<p>I am trying to confirm via a unit test that middleware is actually being added to the pipeline. I have the following static method that adds the middleware. This is what I am testing.</p>

<pre><code>public static class HandleDbUpdateExceptionExtensions
{
    public static IApplicationBuilder UseDbUpdateExceptionHandler(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware&lt;DbUpdateExceptionHandler&gt;();
    }
}
</code></pre>

<p>I know it's actually working because the middleware runs on my site. However, I'd like to write a unit test to ensure it's always included in future builds. My unit test, however, fails:</p>

<pre><code>[Fact(DisplayName = ""Exception handler is added to IApplicationBuilder"")]
public void DbUpdateExceptionHandler_Added_To_IApplicationBuilder()
{
    var builder = new Mock&lt;IApplicationBuilder&gt;().Object;

    builder.UseDbUpdateExceptionHandler();

    Assert.NotNull(builder.ApplicationServices);

    //var test = builder.ApplicationServices.GetService(typeof(DbUpdateExceptionHandler));
}
</code></pre>

<p><code>builder.ApplicationServices</code> is null so the test currently fails. I assume that it is failing because I am just mocking <code>IApplicationBuilder</code> but there is very little relevant material online about unit testing the <em>existance</em> of .Net Core middleware.</p>

<p>Any help is greatly appreciated!</p>
",https://stackoverflow.com/questions/50116882/confirm-that-middleware-is-in-use,"['c#', 'unit-testing', 'asp.net-core', 'moq', 'asp.net-core-middleware']",5311,TRUE,8,3
How to mock data repository in Visual Studio Test?,"<p>I am new to unit testing. I have these classes <strong>AccountBl</strong> that calls <strong>DataStore</strong> that uses SqlConnection to grab data from the database.</p>

<p>I need to test <strong>AccountBl.GetInvestmentAccounts</strong> method by mocking the data source, the test needs to run even without Database connection.</p>

<p>Here are the given classes <strong>AccountBl</strong>:</p>

<pre><code>public class AccountBl
{
    private readonly DataStore dataStore = new DataStore();

    public List&lt;Account&gt; GetInvestmentAccounts(int clientId, AccountType accountType)
    {
        if (accountType == AccountType.Investment)
        {
            var accounts = dataStore.LoadAccounts(clientId);
            return accounts.Where(a =&gt; a.AccountType == AccountType.Investment).ToList();
        }
        throw new Exception(""Invalid account type provided"");
    }
}
</code></pre>

<p>and the <strong>DataStore</strong>:</p>

<pre><code>public class DataStore
{
    public static string GetAccountsSql = ""irrelevant query"";

    public virtual List&lt;Account&gt; LoadAccounts(int clientId)
    {
        using (var connection = CreateConnection())
        {
            var sqlCommand = connection.CreateCommand();
            sqlCommand.CommandText = GetAccountsSql;
            sqlCommand.CommandType = CommandType.Text;
            sqlCommand.Parameters.Add(""@clientId"", clientId);

            var reader = sqlCommand.ExecuteReader();
            var accounts = new List&lt;Account&gt;();
            while (reader.Read())
            {
                var account = new Account();
                account.AccountNumber = (string)reader[""number""];
                account.AccountOwner = clientId;
                if (reader[""accountType""] == null || reader[""accountType""] == DBNull.Value)
                {
                    account.AccountType = AccountType.Checking;
                }
                else
                {
                    account.AccountType =
                        (AccountType)Enum.Parse(typeof(AccountType), reader[""accountType""].ToString());
                }
                accounts.Add(account);
            }
            return accounts;
        }

    }

    private static SqlConnection CreateConnection()
    {
        var sqlConnection = new SqlConnection(ConfigurationManager.AppSettings[""ConnectionString""]);
        sqlConnection.Open();
        return sqlConnection;
    }
}
</code></pre>

<p>Here is my <strong>TestClass</strong></p>

<pre><code>[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void GetInvestmentAccountsTest()
    {
        var clientId = 25;

        var mockAccounts = new List&lt;Account&gt;
        {
            new Account{AccountNumber = ""aaa"", AccountOwner = clientId, AccountType = AccountType.Investment},
            new Account{AccountNumber = ""bbb"", AccountOwner = clientId, AccountType = AccountType.Savings},
            new Account{AccountNumber = ""ccc"", AccountOwner = clientId, AccountType = AccountType.Checking},
        };

        var mockDatastore = new Mock&lt;DataStore&gt;();
        mockDatastore.Setup(x =&gt; x.LoadAccounts(clientId)).Returns(mockAccounts);

        var accountBl = new AccountBl();

        var accounts = accountBl.GetInvestmentAccounts(clientId, AccountType.Investment);


    }
}
</code></pre>

<p><strong>When I run, I get error message</strong></p>

<blockquote>
  <p>Message: Test method
  ScreeningSample.Tests.UnitTest1.GetInvestmentAccountsTest threw
  exception:  System.InvalidOperationException: The ConnectionString
  property has not been initialized.</p>
</blockquote>

<p>Obviously its trying to create a connection, but I need to run the test without a connection.</p>

<p><strong>Am I mocking incorrectly?</strong></p>
",https://stackoverflow.com/questions/48939420/how-to-mock-data-repository-in-visual-studio-test,"['c#', 'unit-testing', 'moq', 'mstest']",1926,TRUE,3,2
How to exclude mock files from Code Coverage Istanbul Reporter,"<p>I have a question regarding Istanbul Reporter used for reporting my unit testing coverage in my angular 6 application.</p>

<p>My problem is: when the coverage is rendered, I see the mocks in the tested files list and obviously the mocks aren't tested, which gives me wrong coverage stats.</p>

<p>This is my karma.conf file setup by a colleague and I'd like to know if you have any idea on how to exclude those mock files.</p>

<pre><code>module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma')
    ],
    client:{
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    coverageIstanbulReporter: {
      dir: require('path').join(__dirname, 'coverage'), reports: [ 'html', 'lcovonly' ],
      fixWebpackSourcePaths: true
    },
    angularCli: {
      environment: 'local'
    },
    reporters: ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
  });
};
</code></pre>

<p>I saw on StackOverflow that it might be done by adding an exclude in the tsconfig.spec.json but even by re-running the code coverage, it still includes them.</p>

<pre><code>{
  ""extends"": ""../../tsconfig.json"",
  ""compilerOptions"": {
    ""outDir"": ""../../out-tsc/spec"",
    ""module"": ""commonjs"",
    ""types"": [
      ""jasmine"",
      ""node""
    ],
    ""typeRoots"": [ ""../node_modules/@types"" ]
  },
  ""files"": [
    ""src/test.ts"",
    ""src/polyfills.ts""
  ],
  ""include"": [
    ""**/*.spec.ts"",
    ""**/*.d.ts""
  ],
  ""exclude"": [
    ""/**/*mock*.ts""
  ]
}
</code></pre>

<p>My mock files are inside <strong>tests</strong>/mocks folder in every module/feature and are called ""mock-whatevertheymock.ts"" </p>

<p>The command to run it is</p>

<pre><code>test:wc-dogs"": ""ng test --project=wc-dogs--code-coverage
</code></pre>

<p>Thank you for the help</p>
",https://stackoverflow.com/questions/52538596/how-to-exclude-mock-files-from-code-coverage-istanbul-reporter,"['javascript', 'angular', 'unit-testing', 'jasmine', 'karma-runner']",10952,TRUE,23,2
Phantomjs not running for complex methods used in Qunit testing,"<p>I m using qunit for headless unit testing. After testing is done i convert the qunit results into junit-styled output .xml file to be used in Jenkins. The problem here when i m using the decode and encode functions and include this in the test process the phantom js is unable to generate any xml.
The encode decode functions i used are as follows : </p>

<pre><code>     var encodeString = function(stringToEncode){
     return btoa(stringToEncode);
     var decodeString = function(stringToDecode){
     return atob(stringToDecode);
</code></pre>

<p>Is there any alternative to using these decode encode functions so that the phantomjs limitations can be encountered.Or any lead on any alternative for phantomjs which does the same job will be beneficial.</p>
",https://stackoverflow.com/questions/50696426/phantomjs-not-running-for-complex-methods-used-in-qunit-testing,"['javascript', 'unit-testing', 'phantomjs', 'automated-tests', 'qunit']",32,FALSE,2,0
ASP.Net Web API Controller Unit Test Fails,"<p>I have created a relatively simple Controller as follows:</p>

<pre><code>[Route(""api/areas"")]
    public class AreasController : Controller
    {
        private IAreaRepository _areaRepository;
        private ILogger&lt;AreasController&gt; _logger;

        // Constructor.
        public AreasController(
            IAreaRepository areaRepository,
            ILogger&lt;AreasController&gt; logger
        )
        {
            _areaRepository = areaRepository;
            _logger = logger;
        }

        [HttpGet()]
        public IActionResult GetAreas()
        {
            try
            {
                _logger.LogTrace(""AreasController.GetAreas called."");

                // Create an IEnumerable of Area objects by calling the repository.
                var areasFromRepo = _areaRepository.GetAreas();

                var areas = Mapper.Map&lt;IEnumerable&lt;AreaDto&gt;&gt;(areasFromRepo);

                // Return a code 200 'OK' along with an IEnumerable of AreaDto objects mapped from the Area entities.
                return Ok(areas);

            }
            catch (Exception ex)
            {
                _logger.LogError($""Failed to get all Areas: {ex}"");

                return BadRequest(""Error Occurred"");
            }

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

<p>I am new to Unit Testing and am struggling to get the most basic of tests working. I am using XUnit and Moq in Visual Studio 2017.</p>

<p>To dip my toe in the water I wanted to test that the GetAreas method on the controller, if there were some Areas, would return an okObjectResult, but it doesn't!</p>

<p>Here's my test:</p>

<pre><code>[Fact]
        public void ReturnAreasForGetAreas()
        {
            //Arrange
            var area = new Area
            {
                Id = new Guid(""761317f6-f9d7-4fa4-a8fe-c6179daee3da""),
                Description = ""Test Area"",
                SortIndex = 1
            };

            var _mockAreaRepository = new Mock&lt;IAreaRepository&gt;();
            _mockAreaRepository
                .Setup(x =&gt; x.GetAreas())
                .Returns(new List&lt;Area&gt; { area });

            var _mockLogger = new Mock&lt;ILogger&lt;AreasController&gt;&gt;();
            var _sut = new AreasController(_mockAreaRepository.Object, _mockLogger.Object);

            // Act
            var result = _sut.GetAreas();
            Assert.NotNull(result);

            // Assert
            var okResult = result.Should().BeOfType&lt;OkObjectResult&gt;().Subject;
        }
</code></pre>

<p>Let me know if you want any Repository or Entity details. I am expecting the problem to be in my misunderstanding of setting up the mocked objects, either way I can't see it.</p>
",https://stackoverflow.com/questions/48344653/asp-net-web-api-controller-unit-test-fails,"['c#', 'unit-testing', 'moq', 'xunit', 'asp.net-core-webapi']",1214,TRUE,2,1
Unable to mock Configuration.Formatters using Moq,"<p>I am developing an ASP.NET web API application. I am unit testing to every component in my application. I am using Moq Unit Test framework to mock the data. Now I am trying to mock the <code>Configuration.Formatters.JsonFormatter</code> in my Unit test because my action under unit test is using it as follows:</p>
<pre><code>public HttpResponseMessage Register(model)
{
    return new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.BadRequest,
                Content = new ObjectContent&lt;List&lt;string&gt;&gt;(errors, Configuration.Formatters.JsonFormatter)
            };
}
</code></pre>
<p>I am trying to mock the <code>Configuration.Formatters.JsonFormatter</code> in the Unit Test as follow.</p>
<pre><code>[TestMethod]
public void Register_ReturnErrorsWithBadRequest_IfValidationFails()
{
    PostUserRegistration model = new PostUserRegistration {
        Name = &quot;Wai Yan Hein&quot;,
        Email = &quot;waiyanhein@gmail.com&quot;,
        Password = &quot;&quot;
    };

    Mock&lt;JsonMediaTypeFormatter&gt; formatterMock = new Mock&lt;JsonMediaTypeFormatter&gt;();
    Mock&lt;MediaTypeFormatterCollection&gt; formatterCollection = new Mock&lt;MediaTypeFormatterCollection&gt;();
    formatterCollection.Setup(x =&gt; x.JsonFormatter).Returns(formatterMock.Object);
    Mock&lt;HttpConfiguration&gt; httpConfigMock = new Mock&lt;HttpConfiguration&gt;();
    httpConfigMock.Setup(x =&gt; x.Formatters).Returns(formatterCollection.Object);
    Mock&lt;IAccountRepo&gt; accRepoMock = new Mock&lt;IAccountRepo&gt;();

    AccountsController controller = new AccountsController(accRepoMock.Object);

    controller.Configuration = httpConfigMock.Object;
    controller.ModelState.AddModelError(&quot;&quot;, &quot;Faking some model error&quot;);
    HttpResponseMessage response = controller.Register(model);
    Assert.AreEqual(response.StatusCode, System.Net.HttpStatusCode.BadRequest);
}
</code></pre>
<p>When I run my unit tests, it is giving me this error.
<a href=""https://i.stack.imgur.com/mGyql.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/mGyql.png"" alt=""enter image description here"" /></a></p>
<blockquote>
<p>System.NotSupportedException: Invalid setup on a non-virtual
(overridable in VB) member: x =&gt; x.JsonFormatter</p>
</blockquote>
<p>So, how can I fix that error and how can I mock <code>Configuration.Formatters.JsonFormatter</code>?</p>
",https://stackoverflow.com/questions/49350575/unable-to-mock-configuration-formatters-using-moq,"['unit-testing', 'asp.net-web-api', 'mocking', 'moq', 'mediatypeformatter']",369,TRUE,1,1
"Phantom: Detected both log4j-over-slf4j.jar AND bound slf4j-log4j12.jar on the class path,","<p>I have just plugged my spark application into Cassandra. I am using the Phantom Cassandra driver.</p>

<p>Now I get the following error during unit testing</p>

<blockquote>
  <p>Detected both log4j-over-slf4j.jar AND bound slf4j-log4j12.jar on the
  class path</p>
</blockquote>

<p>The Exception is thrown during SparkCintext Initialization,
This is caused because I now have Phantom dependencies in my pom.xml. (Seems crazy that Phantom would have a direct conflict with Spark, but there it is)</p>

<pre><code>    &lt;dependency&gt;
        &lt;groupId&gt;com.outworkers&lt;/groupId&gt;
        &lt;artifactId&gt;phantom-dsl_2.11&lt;/artifactId&gt;
        &lt;version&gt;2.24.1&lt;/version&gt;
    &lt;/dependency&gt;
</code></pre>

<p>I can add an exclusion to Phantom to prevent <code>log4j-over-slf4j.jar</code>.</p>

<p>QUESTION:
Is it safe to exclude <code>log4j-over-slf4j.jar</code> from Phantom or will it cause problems further down the line?</p>
",https://stackoverflow.com/questions/49837902/phantom-detected-both-log4j-over-slf4j-jar-and-bound-slf4j-log4j12-jar-on-the-c,"['scala', 'apache-spark', 'log4j', 'slf4j', 'phantom-dsl']",1750,TRUE,1,1
How to unit test MVC controller with argument validation in action filter?,"<p>We have an MVC.NET Core Web API app which uses an action filter to validate the controller's methods' arguments.</p>

<p>For validation we use FluentValidation framework. In the action filter, we find the <code>IValidator&lt;TModel&gt;</code> where <code>TModel</code> is the argument of the controller action, eg:</p>

<pre><code>public async Task&lt;IActionResult&gt; Post([FromBody] TModel model)
{
}
</code></pre>

<p>In the filter's <code>OnActionExecuting(ActionExecutingContext context)</code> we find the proper validator (<code>IValidator&lt;TModel&gt;</code>), validate the arguments (<code>context.ActionArguments</code>) and if validation fails, we short-circuit by assigning the validation result into the <code>context.Result</code> - which means the execution never reaches the controller.</p>

<p>Basic principle is similar to hooking up FluentValidation into the MVC's ModelState validation pipeline but we need some extra things so we're doing it manually.</p>

<p>We would like to unit test both the controller and the validator. The problem is with unit testing the controller. In the test setup we instantiate the controller and call one of its methods. Now in production environment, the arguments will always get validated and actually make it to the controller method only if the arguments are valid. But when unit testing the controller, we can easily pass invalid arguments and get unexpected behaviour.</p>

<p>In principal, is there a way around this? Or do I actually need to make sure that in the test method I pass valid arguments to the controller?</p>

<p>EDIT:</p>

<p>We are also planning on integration testing (most likely using .NET Core's TestServer) to make sure the pipeline is working. In this post, I would like to discuss only the issue around invalid arguments passed from unit test methods to the controller.</p>
",https://stackoverflow.com/questions/49942904/how-to-unit-test-mvc-controller-with-argument-validation-in-action-filter,"['c#', 'unit-testing', 'fluentvalidation', 'asp.net-mvc-filters']",1916,TRUE,2,3
How to test react component that has relative path nested sub component with Jest and enzyme?,"<p>Recently I want to do some unit testing for a react website. I want to import a component, say A. The code looks like:</p>

<pre><code>import ComponentA from '../src/containers/ComponentA';
</code></pre>

<p>And ComponentA is a very complex component with a lot of import inside, like:</p>

<pre><code>import React from 'react';
import { browserHistory } from 'react-router';
import request from 'utils/request';
import { ACTIONS } from 'constants/actions';
import { Table, Link } from 'components';  
import ComponentB from './ComponentB';
</code></pre>

<p>In which utils, constants, and components are local folders and ComponentB is another component used by ComponentA.
So when I tried to import ComponentA, it gives me wired error:</p>

<pre><code>  ● Test suite failed to run

    TypeError: Cannot read property 'prototype' of undefined

      1 | import React from 'react';
    &gt; 2 | import c3 from 'c3';
      3 | import { isEqual } from 'lodash';
      4 |
      5 | import './C3Chart.scss';
</code></pre>

<p>The c3 appears in a component in a very base level, it works during the website, how could I fix this? Or should I mock some sub components? Any suggestions?</p>
",https://stackoverflow.com/questions/48091610/how-to-test-react-component-that-has-relative-path-nested-sub-component-with-jes,"['reactjs', 'enzyme', 'jestjs']",457,FALSE,1,0
Testing unit with skip_before_action does not unset after using TDD,"<p>I am using Rails 5.2 and doing some testing. I am trying my unit testing with <code>ActionController::TestCase</code> and found that <code>@controller.class.skip_before_action :verify_user</code> does not reset the controller automatically before going to the next test unit method.</p>

<p>Now because rails tests are randomized at every run, certain unit fails sometimes and not other times. I figured it was expecting HTTP 401 but I got 200. Cause the controller ignored to <code>before_action :verify_user</code>.</p>

<p>I could set <code>@controller.class.before_action :verify_user</code> at end of every unit (and it works!) but should it not be the rep of testing sys to reset context before every run?</p>

<p>Giving a snip of my code:</p>

<pre><code>class ApiSiteMetricsTest &lt; ActionController::TestCase
  tests Api::SiteMetricsController

  def test_1_index
    @controller.class.skip_before_action :verify_user,raise: false

    get ""index"",  params:{ 
        ""format""=&gt;""json"",
        ""site_metric_value""=&gt;{
            ""site_metric_id""=&gt;2403, 
            ""date_acquired""=&gt;""2018-03-14T01:44:00+05:30"", 
            ""site_id""=&gt;3840, 
            ""lab_device_details""=&gt;"""", 
            ""comment""=&gt;"""", 
            ""sender_affiliation""=&gt;"""", 
            ""float_value""=&gt;""""
        }
    }
    assert_response :success
    File.open(""#{Rails.root}/del.html"", ""wb"") { |f| f.write(@response.body) }        
    #Do I have to do this o every test?
    #@controller.class.before_action :verify_user
  end
  ...
</code></pre>
",https://stackoverflow.com/questions/50738619/testing-unit-with-skip-before-action-does-not-unset-after-using-tdd,"['ruby-on-rails', 'ruby', 'unit-testing', 'tdd', 'ruby-on-rails-5.2']",959,TRUE,1,1
MATLAB changing variable inside a for loop,"<p>I created the Matlab code below to implement the value of an European Put following the implementation inside <a href=""https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=1&amp;ved=0ahUKEwjI2u7_6MvaAhWsxYMKHRjsAw0QFggnMAA&amp;url=http%3A%2F%2Fpersonal.strath.ac.uk%2Fd.j.higham%2FPlist%2FP46.pdf&amp;usg=AOvVaw2zBaQvmpsd5pAW7__fQZYC"" rel=""nofollow noreferrer"">this paper</a>. I am trying to graph the value of M against the value of the European Put as M increases from 20 to 250 in time steps of 5.</p>

<p>In order to do this, I created a for loop to change the value of M,</p>

<pre><code>for M = 20:5:250
</code></pre>

<p>I think that I need to create this for loop in order to change the value of M. Unit testing shows that I did something wrong. The for loop isn't working as intended. The graph produced by the code is referencing the original value of M (defined to be 200) instead of the changing values of M inside the for loop. I don't know why the code returns the original value of M instead of the values inside the for loop. </p>

<pre><code>clear all;
close all;
% EURO9  Binomial method for a European put.
%
% Uses explicit solution based on binomial expansion.
% Vectorized, based on logs to avoid overflow,
% and avoids computing with zeros.
%%%%%%%%%% Problem and method parameters %%%%%%%%%%%%%
S = 9 ;E = 10 ;T = 3 ;r = 0.06 ;sigma = 0.3 ; M = 200;
dt = T/M ; A = 0.5*(exp(-r*dt)+exp((r+sigma^2)*dt)) ;
u= A + sqrt(A^2-1) ; d = 1/u ; p = (exp(r*dt)-d)/(u-d) ;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% cut-off index

for M = 20:5:250
    z = max(1,min(M+1,floor( log((E*u)/(S*d^(M+1)))/(log(u/d)) )));
    % Option values at time T
    W=E-S*d.^([M:-1:M-z+1]').*u.^([0:z-1]');
    % log/cumsum version using cut-off index z
    tmp1 = cumsum(log([1;[M:-1:M-z+2]'])) - cumsum(log([1;[1:z-1]']));
    tmp2 = tmp1 + log(p)*([0:z-1]') + log(1-p)*([M:-1:M-z+1]');
    value = exp(-r*T)*sum(exp(tmp2).*W);
    disp('M is'), disp(M)
    disp('Option value is'), disp(value)
    hold on;
    xlabel('M') % x-axis label
    ylabel('European Put') % y-axis label
    plot(M,value,'r*')
end
</code></pre>

<p>Unit testing shows that my code is wrong. Testing against M=20 returns a value less than one when the true value is 1.5076. </p>

<p>Did I write the for loop completely wrong? Why is it referencing the value of M=200 at every iteration instead of the increment specified in the for loop for M = 20:5:250?</p>

<p>As an example, running</p>

<pre><code>clear all;
close all;
% EURO9  Binomial method for a European put.
%
% Uses explicit solution based on binomial expansion.
% Vectorized, based on logs to avoid overflow,
% and avoids computing with zeros.
%%%%%%%%%% Problem and method parameters %%%%%%%%%%%%%
S = 9 ;E = 10 ;T = 3 ;r = 0.06 ;sigma = 0.3 ; M = 20;
dt = T/M ; A = 0.5*(exp(-r*dt)+exp((r+sigma^2)*dt)) ;
u= A + sqrt(A^2-1) ; d = 1/u ; p = (exp(r*dt)-d)/(u-d) ;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% cut-off index


z = max(1,min(M+1,floor( log((E*u)/(S*d^(M+1)))/(log(u/d)) )));
% Option values at time T
W=E-S*d.^([M:-1:M-z+1]').*u.^([0:z-1]');
% log/cumsum version using cut-off index z
tmp1 = cumsum(log([1;[M:-1:M-z+2]'])) - cumsum(log([1;[1:z-1]']));
tmp2 = tmp1 + log(p)*([0:z-1]') + log(1-p)*([M:-1:M-z+1]');
value = exp(-r*T)*sum(exp(tmp2).*W);
disp('M is'), disp(M)
disp('Option value is'), disp(value)
</code></pre>

<p>returns</p>

<pre><code>Option value is
    1.5076
</code></pre>

<p>and running </p>

<pre><code>clear all;
close all;
% EURO9  Binomial method for a European put.
%
% Uses explicit solution based on binomial expansion.
% Vectorized, based on logs to avoid overflow,
% and avoids computing with zeros.
%%%%%%%%%% Problem and method parameters %%%%%%%%%%%%%
S = 9 ;E = 10 ;T = 3 ;r = 0.06 ;sigma = 0.3 ; M = 25;
dt = T/M ; A = 0.5*(exp(-r*dt)+exp((r+sigma^2)*dt)) ;
u= A + sqrt(A^2-1) ; d = 1/u ; p = (exp(r*dt)-d)/(u-d) ;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% cut-off index


z = max(1,min(M+1,floor( log((E*u)/(S*d^(M+1)))/(log(u/d)) )));
% Option values at time T
W=E-S*d.^([M:-1:M-z+1]').*u.^([0:z-1]');
% log/cumsum version using cut-off index z
tmp1 = cumsum(log([1;[M:-1:M-z+2]'])) - cumsum(log([1;[1:z-1]']));
tmp2 = tmp1 + log(p)*([0:z-1]') + log(1-p)*([M:-1:M-z+1]');
value = exp(-r*T)*sum(exp(tmp2).*W);
disp('M is'), disp(M)
disp('Option value is'), disp(value)
</code></pre>

<p>returns </p>

<pre><code>Option value is
    1.4666
</code></pre>

<p>Although, I don't get these values in the graph of the for loop for M = 20:5:250. I must have made a mistake inside the for loop.</p>
",https://stackoverflow.com/questions/49957810/matlab-changing-variable-inside-a-for-loop,"['matlab', 'loops']",126,TRUE,2,1
roboletric keeps throwing java.lang.NullPointerException before running any test,"<p>I am a newbee on roboletric and using this tutorial to get started</p>

<p><a href=""https://android.jlelse.eu/robolectric-unit-testing-framework-for-android-b78ebac0b411"" rel=""nofollow noreferrer"">https://android.jlelse.eu/robolectric-unit-testing-framework-for-android-b78ebac0b411</a>.</p>

<p>I am using this JDK</p>

<p>JAVA_HOME=C:\Program Files\Java\jdk-11.0.1</p>

<p>Yet, the unit tests keep crashing before they even start no matter what :(</p>

<p>Any idea how can I resolve this?</p>

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

<pre><code>android {
    compileSdkVersion 28
    defaultConfig {
        applicationId ""com.guitarv.robotest""
        minSdkVersion 24
        targetSdkVersion 28
        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(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    testImplementation ""org.robolectric:robolectric:3.3.2""
}
</code></pre>

<p>here is the part of the unittest from the sample doing nothing:</p>

<pre><code>@Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.LOLLIPOP_MR1)
@RunWith(RobolectricTestRunner.class)

public class MainActivityTest {

    private Activity activity;

    // 3
    @Before
    public void setup() {
        //activity = Robolectric.buildActivity(MainActivity.class).create().get();
    }

    @Test // 4
    public void validateTextViewContent() {
        //TextView textView = (TextView) activity.findViewById(R.id.text_view);

        // 5
        //assertNotNull(""TextView is null"", textView);
        // 6
        //assertTrue(""TextView's text does not match."", ""Hello Robolectric!"".equals(textView.getText().toString()));
    }
}
</code></pre>

<p>I commented out all the code on purpose but still I keep getting:</p>

<pre><code>""C:\Program Files\Android\Android Studio\jre\bin\java.exe"" -ea -Didea.test.cyclic.buffer.size=1048576 -Didea.launcher.port=61050 ""-Didea.launcher.bin.path=C:\Program Files\Android\Android Studio\bin"" -Dfile.encoding=UTF-8 -classpath ""C:\Program Files\Android\Android Studio\lib\idea_rt.jar;C:\Program Files\Android\Android Studio\plugins\junit\lib\junit-rt.jar;C:\Program Files\Android\Android Studio\plugins\junit\lib\junit5-rt.jar;C:\Users\goliveira\AppData\Local\Android\Sdk\platforms\android-28\data\res;D:\gmmo\accriva\dev\misc\droid\RoboEletricTest\app\build\intermediates\javac\debugUnitTest\compileDebugUnitTestJavaWithJavac\classes;D:\gmmo\accriva\dev\misc\droid\RoboEletricTest\app\build\intermediates\javac\debug\compileDebugJavaWithJavac\classes;D:\gmmo\accriva\dev\misc\droid\RoboEletricTest\app\build\generated\res\rs\debug;D:\gmmo\accriva\dev\misc\droid\RoboEletricTest\app\build\generated\res\resValues\debug;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\backport-util-concurrent\backport-util-concurrent\3.1\682f7ac17fed79e92f8e87d8455192b63376347b\backport-util-concurrent-3.1.jar;C:\Users\goliveira\.gradle\caches\transforms-1\files-1.1\localbroadcastmanager-28.0.0.aar\b3c58c4eb60e9210b5d76238a783884e\jars\classes.jar;C:\Users\goliveira\.gradle\caches\transforms-1\files-1.1\support-vector-drawable-28.0.0.aar\371b6522d664fc5b787ee41c99f0347c\jars\classes.jar;C:\Users\goliveira\.gradle\caches\transforms-1\files-1.1\interpolator-28.0.0.aar\a18477ce77c1bc73879414a4c1189ef5\jars\classes.jar;C:\Users\goliveira\.gradle\caches\transforms-1\files-1.1\support-core-utils-28.0.0.aar\d48404db6dbf03f1f6d60821baa8627b\jars\classes.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\org.apache.maven\maven-error-diagnostics\2.2.1\e81bb342d7d172f23d108dc8fa979a1facdcde8e\maven-error-diagnostics-2.2.1.jar;C:\Users\goliveira\.gradle\caches\transforms-1\files-1.1\drawerlayout-28.0.0.aar\e637c84c580b131b2350f433bda154ae\jars\classes.jar;C:\Users\goliveira\.gradle\caches\transforms-1\files-1.1\coordinatorlayout-28.0.0.aar\7c08ed52390afce91866a0f172731525\jars\classes.jar;C:\Users\goliveira\.gradle\caches\transforms-1\files-1.1\coordinatorlayout-28.0.0.aar\7c08ed52390afce91866a0f172731525\res;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\org.apache.maven.wagon\wagon-http-lightweight\1.0-beta-6\b3815078570c3b1f0667e123d59717c6b726c6c2\wagon-http-lightweight-1.0-beta-6.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\org.apache.maven\maven-project\2.2.1\8239e98c16f641d55a4ad0e0bab0aee3aff8933f\maven-project-2.2.1.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\org.apache.maven.wagon\wagon-file\1.0-beta-6\6c53633505460caf49d2660de1e24744d915afb9\wagon-file-1.0-beta-6.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\org.apache.maven.wagon\wagon-provider-api\1.0-beta-6\3f952e0282ae77ae59851d96bb18015e520b6208\wagon-provider-api-1.0-beta-6.jar;C:\Users\goliveira\.gradle\caches\transforms-1\files-1.1\constraint-layout-1.1.3.aar\1bcfd614af80c4832f67420ed3c169cb\res;C:\Users\goliveira\.gradle\caches\transforms-1\files-1.1\constraint-layout-1.1.3.aar\1bcfd614af80c4832f67420ed3c169cb\jars\classes.jar;C:\Users\goliveira\.gradle\caches\transforms-1\files-1.1\swiperefreshlayout-28.0.0.aar\5f33f72b473c63a42f22a2684c667af0\jars\classes.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\org.apache.ant\ant\1.8.0\7b456ca6b93900f96e58cc8371f03d90a9c1c8d1\ant-1.8.0.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\xpp3\xpp3_min\1.1.4c\19d4e90b43059058f6e056f794f0ea4030d60b86\xpp3_min-1.1.4c.jar;C:\Users\goliveira\.gradle\caches\transforms-1\files-1.1\livedata-1.1.1.aar\955c5f3ce9a18760008044450d2bd7ac\jars\classes.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\org.bouncycastle\bcprov-jdk16\1.46\ce091790943599535cbb4de8ede84535b0c1260c\bcprov-jdk16-1.46.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\org.robolectric\robolectric\3.3.2\90022fc9ad52c44d0c2a13b8371e9a3624357ba8\robolectric-3.3.2.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\org.robolectric\shadow-api\3.3.2\b27c499e077a842330aca3f76615af8bff0fab29\shadow-api-3.3.2.jar;C:\Users\goliveira\.gradle\caches\transforms-1\files-1.1\versionedparcelable-28.0.0.aar\c720aed29e0f6ad3ffce1a8fdf53b870\jars\classes.jar;C:\Users\goliveira\.gradle\caches\transforms-1\files-1.1\runtime-1.1.1.aar\31cdc70d8f0bdb1d27d07983a12ad3e2\jars\classes.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\com.google.guava\guava\20.0\89507701249388e1ed5ddcf8c41f4ce1be7831ef\guava-20.0.jar;C:\Users\goliveira\.gradle\caches\transforms-1\files-1.1\loader-28.0.0.aar\a2c1dc655b8a52ced6a718a8e802779b\jars\classes.jar;C:\Users\goliveira\.gradle\caches\transforms-1\files-1.1\viewpager-28.0.0.aar\06c54ff569e312ccfa71e4fcdc7985ca\jars\classes.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\org.robolectric\robolectric-sandbox\3.3.2\4d968978679b572e5993b3eea35cae88268f44ee\robolectric-sandbox-3.3.2.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\com.android.support\support-annotations\28.0.0\ed73f5337a002d1fd24339d5fb08c2c9d9ca60d8\support-annotations-28.0.0.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\org.robolectric\shadows-core\3.3.2\3d20e0784abd5d6ccf58eeb82da908ecbf7bffd9\shadows-core-3.3.2.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\com.almworks.sqlite4java\sqlite4java\0.282\745a7e2f35fdbe6336922e0d492c979dbbfa74fb\sqlite4java-0.282.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\org.apache.maven\maven-artifact-manager\2.2.1\ec355b913c34d37080810f98e3f51abecbe1572b\maven-artifact-manager-2.2.1.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\org.apache.maven\maven-settings\2.2.1\2236ffe71fa5f78ce42b0f5fc22c54ed45f14294\maven-settings-2.2.1.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\com.android.support.constraint\constraint-layout-solver\1.1.3\bde0667d7414c16ed62d3cfe993cff7f9d732373\constraint-layout-solver-1.1.3.jar;C:\Users\goliveira\.gradle\caches\transforms-1\files-1.1\runtime-1.1.1.aar\592b1351298476a94ec1712db1b91201\jars\classes.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\org.codehaus.plexus\plexus-container-default\1.0-alpha-9-stable-1\94aea3010e250a334d9dab7f591114cd6c767458\plexus-container-default-1.0-alpha-9-stable-1.jar;C:\Users\goliveira\.gradle\caches\transforms-1\files-1.1\customview-28.0.0.aar\7955ec8523e8028326883f2e231f469a\jars\classes.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\com.thoughtworks.xstream\xstream\1.4.8\520d90f30f36a0d6ba2dc929d980831631ad6a92\xstream-1.4.8.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\org.ow2.asm\asm\5.0.1\2fd56467a018aafe6ec6a73ccba520be4a7e1565\asm-5.0.1.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\org.apache.maven\maven-plugin-registry\2.2.1\72a24b7775649af78f3986b5aa7eb354b9674cfd\maven-plugin-registry-2.2.1.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\org.ow2.asm\asm-tree\5.0.1\1b1e6e9d869acd704056d0a4223071a511c619e6\asm-tree-5.0.1.jar;C:\Users\goliveira\.gradle\caches\transforms-1\files-1.1\support-core-ui-28.0.0.aar\642f5b61e8611ac9fd4b75bfb9725126\jars\classes.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\org.apache.maven\maven-ant-tasks\2.1.3\b09be554228d66d208e5fef5266844aacf443abc\maven-ant-tasks-2.1.3.jar;C:\Users\goliveira\.gradle\caches\transforms-1\files-1.1\slidingpanelayout-28.0.0.aar\f90b7075c9c10d61058f4dbaeac8f2f6\jars\classes.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\com.ibm.icu\icu4j\53.1\786d9055d4ca8c1aab4a7d4ac8283f973fd7e41f\icu4j-53.1.jar;C:\Users\goliveira\.gradle\caches\transforms-1\files-1.1\viewmodel-1.1.1.aar\3f70ea745461b173c85d6688df0a45d5\jars\classes.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\com.google.protobuf\protobuf-java\2.6.1\d9521f2aecb909835746b7a5facf612af5e890e8\protobuf-java-2.6.1.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\org.robolectric\robolectric-junit\3.3.2\fd1cb1d27d125c0826feddfcd00653f2f16e458d\robolectric-junit-3.3.2.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\com.android.support\collections\28.0.0\c1bcdade4d3cc2836130424a3f3e4182c666a745\collections-28.0.0.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\org.apache.maven.wagon\wagon-http-shared\1.0-beta-6\ccd70d7e0d8c085e648a83f072da06ca9a53be94\wagon-http-shared-1.0-beta-6.jar;C:\Users\goliveira\.gradle\caches\transforms-1\files-1.1\documentfile-28.0.0.aar\ecb51ab8a338322fd5ee210413d745be\jars\classes.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\org.apache.ant\ant-launcher\1.8.0\8b53ba16fa62fb1034da8f1de200ddc407c8381\ant-launcher-1.8.0.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\org.ow2.asm\asm-commons\5.0.1\7b7147a390a93a14d2edfdcf3f7b0e87a0939c3e\asm-commons-5.0.1.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\org.apache.maven\maven-profile\2.2.1\3950071587027e5086e9c395574a60650c432738\maven-profile-2.2.1.jar;C:\Users\goliveira\.gradle\caches\transforms-1\files-1.1\cursoradapter-28.0.0.aar\3bd07da01bf98a85596dec6dc27cc586\jars\classes.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\nekohtml\nekohtml\1.9.6.2\2d960be7b62ae6622dbbbe49ab4ffdc609f85c80\nekohtml-1.9.6.2.jar;C:\Users\goliveira\.gradle\caches\transforms-1\files-1.1\asynclayoutinflater-28.0.0.aar\7e74ec87a85890a1f51ca394d667bf88\jars\classes.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\nekohtml\xercesMinimal\1.9.6.2\d1c5e063683a0e6f77cd5f051a9d4af48346fa6\xercesMinimal-1.9.6.2.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\org.apache.maven\maven-model\2.2.1\c0a1c17436ec3ff5a56207c031d82277b4250a29\maven-model-2.2.1.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\org.robolectric\robolectric-utils\3.3.2\c94200e8e1176caa63ff46ff6f2870990f5642cc\robolectric-utils-3.3.2.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\android.arch.core\common\1.1.1\e55b70d1f5620db124b3e85a7f4bdc7bd48d9f95\common-1.1.1.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\org.assertj\assertj-core\2.6.0\b532c3fc4f66bcfee4989a3514f1cd56203a33ad\assertj-core-2.6.0.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\org.apache.maven\maven-repository-metadata\2.2.1\98f0c07fcf1eeb213bef8d9316a9935184084b06\maven-repository-metadata-2.2.1.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\junit\junit\4.12\2973d150c0dc1fefe998f834810d68f278ea58ec\junit-4.12.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\org.hamcrest\hamcrest-core\1.3\42a25dc3219429f0e5d060061f71acb49bf010a0\hamcrest-core-1.3.jar;C:\Users\goliveira\.gradle\caches\transforms-1\files-1.1\print-28.0.0.aar\17c6a6e80e92037579f91880318e5f28\jars\classes.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\org.robolectric\robolectric-resources\3.3.2\b1a0ccac05e19a5fa2b21d462375c7603e2203b\robolectric-resources-3.3.2.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\com.google.android.apps.common.testing.accessibility.framework\accessibility-test-framework\2.1\c2d6267c3ad0435ddf9e27a94a0e0af4ca3fdfbb\accessibility-test-framework-2.1.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\org.hamcrest\hamcrest-library\1.3\4785a3c21320980282f9f33d0d1264a69040538f\hamcrest-library-1.3.jar;C:\Users\goliveira\.gradle\caches\transforms-1\files-1.1\support-fragment-28.0.0.aar\b0e409047e22879ce4f39cadf04c923f\jars\classes.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\android.arch.lifecycle\common\1.1.1\207a6efae6a3555e326de41f76bdadd9a239cbce\common-1.1.1.jar;C:\Users\goliveira\.gradle\caches\transforms-1\files-1.1\livedata-core-1.1.1.aar\d56bc7861e06858b588fafb8395f6375\jars\classes.jar;C:\Users\goliveira\.gradle\caches\transforms-1\files-1.1\support-compat-28.0.0.aar\3aa2d1093d375e1c9c74fa3858a94797\jars\classes.jar;C:\Users\goliveira\.gradle\caches\transforms-1\files-1.1\support-compat-28.0.0.aar\3aa2d1093d375e1c9c74fa3858a94797\res;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\org.codehaus.plexus\plexus-interpolation\1.11\ad9dddff6043194904ad1d2c00ff1d003c3915f7\plexus-interpolation-1.11.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\org.codehaus.plexus\plexus-utils\1.5.15\c689598ce1eb94c304817877ed15911099972526\plexus-utils-1.5.15.jar;C:\Users\goliveira\.gradle\caches\transforms-1\files-1.1\animated-vector-drawable-28.0.0.aar\9f7504f5407395a5f670b89c9c4ab36b\jars\classes.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\org.apache.maven\maven-artifact\2.2.1\23600f790d4dab2cb965419eaa982e3e84c428f8\maven-artifact-2.2.1.jar;C:\Users\goliveira\.gradle\caches\transforms-1\files-1.1\appcompat-v7-28.0.0.aar\339a1fc7f52a5d15a2ebd061be344fc7\jars\classes.jar;C:\Users\goliveira\.gradle\caches\transforms-1\files-1.1\appcompat-v7-28.0.0.aar\339a1fc7f52a5d15a2ebd061be344fc7\res;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\xmlpull\xmlpull\1.1.3.1\2b8e230d2ab644e4ecaa94db7cdedbc40c805dfa\xmlpull-1.1.3.1.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\org.robolectric\robolectric-annotations\3.3.2\9aabda1b5c03c0077e0224058a444c23bc1162ac\robolectric-annotations-3.3.2.jar;C:\Users\goliveira\.gradle\caches\modules-2\files-2.1\classworlds\classworlds\1.1-alpha-2\5adf2e681c57d7f48038b602f3ca2254ee82d47\classworlds-1.1-alpha-2.jar;D:\gmmo\accriva\dev\misc\droid\RoboEletricTest\app\build\intermediates\sourceFolderJavaResources\test\debug;D:\gmmo\accriva\dev\misc\droid\RoboEletricTest\app\build\intermediates\sourceFolderJavaResources\debug;C:\Users\goliveira\.gradle\caches\transforms-1\files-1.1\android.jar\50278f1e57ccc2849b9cf0e83a034629\android.jar"" com.intellij.rt.execution.application.AppMainV2 com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 com.guitarv.robotest.MainActivityTest
No such manifest file: build\intermediates\bundles\debug\AndroidManifest.xml

java.lang.RuntimeException: java.lang.NullPointerException

    at org.robolectric.res.ResourceTableFactory.parseResourceFiles(ResourceTableFactory.java:155)
    at org.robolectric.res.ResourceTableFactory.newResourceTable(ResourceTableFactory.java:43)
    at org.robolectric.res.ResourceMerger.buildResourceTable(ResourceMerger.java:22)
    at org.robolectric.RobolectricTestRunner.getAppResourceTable(RobolectricTestRunner.java:450)
    at org.robolectric.RobolectricTestRunner.beforeTest(RobolectricTestRunner.java:288)
    at org.robolectric.internal.SandboxTestRunner$2.evaluate(SandboxTestRunner.java:203)
    at org.robolectric.internal.SandboxTestRunner.runChild(SandboxTestRunner.java:109)
    at org.robolectric.internal.SandboxTestRunner.runChild(SandboxTestRunner.java:36)
    ... a bunch of stuff here that I removed
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMainV2.main(AppMainV2.java:131)
Caused by: java.lang.NullPointerException
    at org.robolectric.res.DocumentLoader.loadFile(DocumentLoader.java:35)
    at org.robolectric.res.DocumentLoader.load(DocumentLoader.java:26)
    at org.robolectric.res.ResourceTableFactory.parseResourceFiles(ResourceTableFactory.java:140)
    ... 24 more
</code></pre>

<p>and here how I am running (right-click on the MainActivityTest):</p>

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

<p>finally the location of the files:</p>

<p><a href=""https://i.stack.imgur.com/mnj69.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/mnj69.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/53218075/roboletric-keeps-throwing-java-lang-nullpointerexception-before-running-any-test,"['android', 'unit-testing', 'robolectric']",1033,FALSE,1,1
Moq - Cannot convert from IGenericRepository To Generic Repository,"<p>Please forgive me in advance, I'm trying to learn unit testing and Moq.</p>

<p>I think i've almost managed to set things up properly (but i could be wrong). When i execute the test below i get the following error:</p>

<blockquote>
  <p>Cannot convert from
  'TestMoq.DAL.IGenericRepository' to
  'TestMoq.DAL.GenericRepository'    TestMoq.UnitTests</p>
</blockquote>

<p>On this line:</p>

<pre><code>    _mockUnitWork.Setup(m =&gt; m.CreditRepository).Returns(_mockRepository.Object);
</code></pre>

<p>Here's my code:</p>

<p>MoqTest</p>

<pre><code>using System;
using NUnit.Framework;
using TestMoq.Controllers;
using TestMoq.Models;
using TestMoq.DAL;
using Moq;
using System.Web.Mvc;
using System.Runtime;
using System.Data.Entity;
using System.Collections.Generic;
using System.Linq;

namespace TestMoq.UnitTests.Controllers
{
    [TestFixture]
    public class BaseControllerTests
    {

        private Mock&lt;IGenericRepository&lt;Credit&gt;&gt; _mockRepository;
        Mock&lt;IUnitOfWork&gt; _mockUnitWork;



        [Test]
        public void MoqTest() {

            _mockRepository = new Mock&lt;IGenericRepository&lt;Credit&gt;&gt;();
            _mockUnitWork = new Mock&lt;IUnitOfWork&gt;();
            var _service = new CreditsController(_mockUnitWork.Object);

            List&lt;Credit&gt; listCredit= new List&lt;Credit&gt;() {
           new Credit() { CreditId = 1},
           new Credit() { CreditId = 2},
           new Credit() { CreditId = 3 }
          };

            _mockRepository.Setup(x =&gt; x.Get(null, null, ""*"")).Returns(listCredit);
            _mockUnitWork.Setup(m =&gt; m.CreditRepository).Returns(_mockRepository.Object);

            List&lt;Credit&gt; results = _service.GetAll() as List&lt;Credit&gt;;


            Assert.IsNotNull(results);
            Assert.AreEqual(3, results.Count);
        }
    }
}
</code></pre>

<p>CreditController.cs</p>

<pre><code>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using TestMoq.CustomFilters;
using TestMoq.DAL;
using TestMoq.Models;

namespace TestMoq.Controllers
{
    public class CreditsController : Controller
    {
        private UnitOfWork unitOfWork = new UnitOfWork();
        private IUnitOfWork _unitOfWork;

        public CreditsController()
        {
            this._unitOfWork = new UnitOfWork();
        }
        public CreditsController(IUnitOfWork _NewUnitOfWork)
        {
            this._unitOfWork = _NewUnitOfWork;
        }       

        public List&lt;Credit&gt; GetAll()
        {
            return _unitOfWork.CreditRepository.Get().ToList();
        }

    }
}
</code></pre>

<p>GenericRepository</p>

<pre><code>using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using TestMoq.Models;

namespace TestMoq.DAL
{

    public class GenericRepository&lt;TEntity&gt; : IGenericRepository&lt;TEntity&gt; where TEntity : class
    {
        internal TcpContext context;
        internal DbSet&lt;TEntity&gt; dbSet;

        public GenericRepository(TcpContext context)
        {
            this.context = context;
            this.dbSet = context.Set&lt;TEntity&gt;();
        }

        public virtual IEnumerable&lt;TEntity&gt; Get(
            Expression&lt;Func&lt;TEntity, bool&gt;&gt; filter = null,
            Func&lt;IQueryable&lt;TEntity&gt;, IOrderedQueryable&lt;TEntity&gt;&gt; orderBy = null,
            string includeProperties = """")
        {
            IQueryable&lt;TEntity&gt; query = dbSet;

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

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

            if (orderBy != null)
            {
                return orderBy(query).ToList();
            }
            else
            {
                return query.ToList();
            }
        }

        public virtual TEntity GetByID(object id)
        {
            return dbSet.Find(id);
        }

        public virtual void Insert(TEntity entity)
        {
            dbSet.Add(entity);
        }

        public virtual void Delete(object id)
        {
            TEntity entityToDelete = dbSet.Find(id);
            Delete(entityToDelete);
        }

        public virtual void Delete(TEntity entityToDelete)
        {
            if (context.Entry(entityToDelete).State == EntityState.Detached)
            {
                dbSet.Attach(entityToDelete);
            }
            dbSet.Remove(entityToDelete);
        }

        public virtual void Update(TEntity entityToUpdate)
        {
            dbSet.Attach(entityToUpdate);
            context.Entry(entityToUpdate).State = EntityState.Modified;
        }
    }
}
</code></pre>

<p>IGenericRepository.cs</p>

<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace TestMoq.DAL
{
    public interface IGenericRepository&lt;TEntity&gt; where TEntity : class
    {
        void Delete(object id);
        void Delete(TEntity entityToDelete);
        IEnumerable&lt;TEntity&gt; Get(Expression&lt;Func&lt;TEntity, bool&gt;&gt; filter = null, Func&lt;IQueryable&lt;TEntity&gt;, IOrderedQueryable&lt;TEntity&gt;&gt; orderBy = null, string includeProperties = """");
        TEntity GetByID(object id);
        void Insert(TEntity entity);
        void Update(TEntity entityToUpdate);
    }
}
</code></pre>

<p>UnitOfWork</p>

<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using TestMoq.Models;

namespace TestMoq.DAL
{

    public class UnitOfWork : IDisposable, IUnitOfWork
    {
        private TcpContext context = new TcpContext();
        public GenericRepository&lt;Credit&gt; creditRepository;

        //Other models &amp; methods removed for clarity


        public GenericRepository&lt;Credit&gt; CreditRepository
        {
            get
            {
                if (this.creditRepository == null)
                {
                    this.creditRepository = new GenericRepository&lt;Credit&gt;(context);
                }

                return creditRepository;
            }

        }

        public void Save()
        {
            context.SaveChanges();
        }

    }
}
</code></pre>

<p>IUnitOfWork.cs</p>

<pre><code>using TestMoq.Models;

namespace TestMoq.DAL
{
    public interface IUnitOfWork
    {
        GenericRepository&lt;Amendment&gt; AmendmentRepository { get; }
        GenericRepository&lt;Credit&gt; CreditRepository { get; }
        GenericRepository&lt;FileUpload&gt; FileUploadRepository { get; }
        GenericRepository&lt;Job&gt; JobRepository { get; }
        GenericRepository&lt;Subscription&gt; SubscriptionRepository { get; }
        GenericRepository&lt;Topic&gt; TopicRepository { get; }
        GenericRepository&lt;Writer&gt; WriterRepository { get; }

        void Dispose();
        void Save();
    }
}
</code></pre>

<p>Apologies in advance if i'm totally messing this up, if you've noticed any other massive errors in my way of thinking (im still getting my head around all this) please do point them out to me.</p>

<p>Thank you!</p>
",https://stackoverflow.com/questions/52433483/moq-cannot-convert-from-igenericrepository-to-generic-repository,"['c#', 'unit-testing', 'moq']",256,FALSE,1,1
Mock Verify() Invocation,"<p>I'm unit testing to see if a method is called.</p>

<pre><code>[Fact]
        public void Can_Save_Project_Changes()
        {
            //Arrange
            var user = new AppUser() { UserName = ""JohnDoe"", Id = ""1"" };
            Mock&lt;IRepository&gt; mockRepo = new Mock&lt;IRepository&gt;();
            Mock&lt;UserManager&lt;AppUser&gt;&gt; userMgr = GetMockUserManager();
            userMgr.Setup(x =&gt; x.FindByNameAsync(It.IsAny&lt;string&gt;())).ReturnsAsync(new AppUser() { UserName = ""JohnDoe"", Id = ""1"" });
            var contextUser = new ClaimsPrincipal(new ClaimsIdentity(new Claim[]
            {
                new Claim(ClaimTypes.Name, user.UserName),
                new Claim(ClaimTypes.NameIdentifier, user.Id),
            }));
            Mock&lt;ITempDataDictionary&gt; tempData = new Mock&lt;ITempDataDictionary&gt;();
            ProjectController controller = new ProjectController(mockRepo.Object, userMgr.Object)
            {
                TempData = tempData.Object,
                ControllerContext = new ControllerContext
                {
                    HttpContext = new DefaultHttpContext() { User = contextUser }
                }
            };

            Project project = new Project()
            {
                Name = ""Test"",
                UserID = ""1"",
            };

            //Act
            Task&lt;IActionResult&gt; result = controller.EditProject(project);

            //Assert

            mockRepo.Setup(m =&gt; m.SaveProject(It.IsAny&lt;Project&gt;(), user));
            //This line still throws an error
            mockRepo.Verify(m =&gt; m.SaveProject(It.IsAny&lt;Project&gt;(), user));
            Assert.IsType&lt;Task&lt;IActionResult&gt;&gt;(result);
            var view = result.Result as ViewResult;
            Assert.Equal(""ProjectCharts"", view.ViewName);
            Assert.Equal(""Project"", view.Model.ToString());
        }
</code></pre>

<p>While debugging, I can verify that the method is actually called in the controller,</p>

<pre><code>//This controller line is touched walking through the code
repository.SaveProject(project, user);

//but this repo line is not touched
public void SaveProject(Project project, AppUser user)      
</code></pre>

<p>Debugging doesn't actually show entrance into the repository method. The exact error is below</p>

<blockquote>
  <p>Expected invocation on the mock at least once, but was never performed: m => m.SaveProject(, JohnDoe)</p>
  
  <p>No setups configured.
  Performed invocations:
  IRepository.ProjectClass
  IRepository.SaveProjects(ProjectClass, JohnDoe)'</p>
</blockquote>

<p>When I do an actual integration test, the <code>SaveProject</code> method is touched in the repository and seems to work properly. I've also tried assigning every <code>Project</code> property within the unit test but got the same error result</p>
",https://stackoverflow.com/questions/49332471/mock-verify-invocation,"['c#', 'mocking', 'xunit']",3608,TRUE,1,2
C++ Unit Test Framework with Allure Report,"<p>I'm starting using Allure with Python Behave for high-level BDD testing of a medium size C++ ecosystem of services. </p>

<p>What I get is a web page inside Jenkins with pretty and clear reports, thanks to the Allure-Jenkins plugin.</p>

<p>I have also some unit tests made with TAP, shown in Jenkins with another plugin. </p>

<p><em>What I would like to get is the integration of the unit test reports inside the same Allure page</em></p>

<p>Unfortunately, I was not able to find a C++ Unit Testing Framework directly supporting Allure reports: <em>does any exist?</em>
<em>Otherwise, I could I get this integration?</em></p>

<p>Thank you!</p>
",https://stackoverflow.com/questions/49051248/c-unit-test-framework-with-allure-report,"['c++', 'jenkins', 'tap', 'allure', 'python-behave']",631,TRUE,1,1
Can I use MOQ to mock future instances?,"<p>I am new to unit testing and trying to figure out a bit more about MOQ.</p>

<p>Is there an API that allows me to mock future instances of some type?
I mean,<br>
Let's say I am mocking a class. Inside that class I use the new operator to create a new instance of an object.<br>
I want to mock all future instances of the same type of that object that will be created within that class in the future, is there such API?</p>

<p>I tried to look into MOQ documentation but there is no such example. Help anyone?</p>
",https://stackoverflow.com/questions/53693273/can-i-use-moq-to-mock-future-instances,"['c#', 'unit-testing', 'moq']",263,TRUE,1,1
QUnit global object states being polluted in the unit tests,"<p>The issue <a href=""https://stackoverflow.com/questions/52561975/qunit-stubbing-out-methods-on-a-dependency-breaks-tests-against-that-dependency"">in this question</a> keeps coming up: somehow, states being set by some test methods are somehow carrying over to other tests. </p>

<p>I am coding in Google Apps Script, and unit-testing using QUnit for Google Apps Script.</p>

<p><strong>The functions under test</strong></p>

<pre><code>/**
 *  Creates menu with driver items
 **/
function createDriverMenu() { 
  SpreadsheetApp.getUi()
     .createMenu(""New Project Analysis"")
     .addItem(""From File"", ""openFilePrompt"")
     .addToUi()
}

/**
 *  Sets formatting on the Sheet
 *  @param { Sheet } sheet
 *  @returns { Sheet } sheet
 **/
function setFormattingFor(sheet) { 
  if (!sheet) throw Error(""sheet required to setFormattingFor !"")
  // set conditional formatting on the range C2:C
  var range = sheet.getRange(""C2:C"")
  var rules = sheet.getConditionalFormatRules()
  // if a cell's text equals FALSE, set that cell to white text, and the background to red
  Logger.log(SpreadsheetApp)
  ruleForFalseText = SpreadsheetApp.newConditionalFormatRule()
                       .setRanges([range])
                       .whenTextEqualTo(""FALSE"")
                       .setBackground(""red"")
                       .setFontColor(""white"")
                       .build()
  rules.push(ruleForFalseText)
  ruleForTrueText = SpreadsheetApp.newConditionalFormatRule()
                       .setRanges([range])
                       .whenTextEqualTo(""TRUE"")
                       .setBackground(""green"")
                       .setFontColor(""white"")
                       .build()
  rules.push(ruleForTrueText)
  ruleForInProgressText = SpreadsheetApp.newConditionalFormatRule()
                       .setRanges([range])
                       .whenTextEqualTo(""IN PROGRESS"")
                       .setBackground(""orange"")
                       .setFontColor(""white"")
                       .build()
  rules.push(ruleForInProgressText)
  ruleForPartialText = SpreadsheetApp.newConditionalFormatRule()
                       .setRanges([range])
                       .whenTextEqualTo(""PARTIAL"")
                       .setBackground(""yellow"")
                       .setFontColor(""black"")
                       .build()
  rules.push(ruleForPartialText)
  ruleForClosedTilTestableText = SpreadsheetApp.newConditionalFormatRule()
                       .setRanges([range])
                       .whenTextEqualTo(""CLOSED TIL TESTABLE"")
                       .setBackground(""black"")
                       .setFontColor(""white"")
                       .build()
  rules.push(ruleForClosedTilTestableText)
  sheet.setConditionalFormatRules(rules)

}
</code></pre>

<p><strong>The tests</strong></p>

<pre><code>function testCreateDriverMenu() { 
  var menuStub // the stub for the menu
  var savedSpreadsheetApp // the state of SpreadsheetApp from Google's Sheets API

  QUnit.testStart(function() { 
    // create a menu stub
    menuStub = {
      addItemCalls : [],
      addItem : function(txt, funcName) { 
        this.addItemCalls.push({ args : { displayTxt : txt, funcName: funcName } })
        return this
      },
      addToUiCalled : false,
      addToUi : function() { this.addToUiCalled = true } 
    }
    // save the state of SpreadsheetApp to temporary variable
    savedSpreadsheetApp = SpreadsheetApp;
    SpreadsheetApp = {
      ui : { 
        createMenuCalls : [],
        createMenu : function(str)  { 
          this.createMenuCalls.push({ args: str })
          return menuStub
        }

      },
      getUi : function() { return this.ui }
    }

  })
  QUnit.test(""testing createDriverMenu"", 
             function() { 

               // hit the method under test
               createDriverMenu({})
               // do assertions
               ok(SpreadsheetApp.ui.createMenuCalls.length, ""SpreadsheetApp.getUi().createMenu was invoked at least once"");
               ok(menuStub.addItemCalls.length, ""SpreadsheetApp.getUi().createMenu().addItem was invoked at least once"");
               ok(menuStub.addToUiCalled, ""menu added to ui"")

             })
  QUnit.testDone(function() { 
    // set SpreadsheetApp back
    SpreadsheetApp = savedSpreadsheetApp;

  })
}

function testSetFormattingFor() { 
  var sheet
  var savedSpreadsheetApp
  var rule

  QUnit.testStart(function() { 
    savedSpreadsheetApp = SpreadsheetApp

    rule = {
      setRangesCalls : [],
      setRanges: function(arr) { 
        this.setRangesCalls.push({ args: arr })
        return this
      },
      whenEqualToCalls : [],
      whenEqualTo : function(str) { 
        this.whenEqualToCalls.push({ args: str })
        return this
      },
      setBackgroundCalls : [],
      setBackground : function(str) { 
        this.setBackgroundCalls.push({ args: str })
        return this
      },
      setFontColorCalls : [],
      setFontColor : function(str) { 
        this.setFontColorCalls.push({ args: str })
        return this
      },
      buildCalls : [],
      build : function() { 
        this.buildCalls.push({ args: null })
        return this
      }
    }

    SpreadsheetApp = {
      newConditionalFormatRuleCalls : [],
      newConditionalFormatRule : function() { 
        this.newConditionalFormatRuleCalls.push({ args : null })
        return rule
      }

    }
    sheet = {
      rule  : [],
      setConditionalFormatRulesCalls : [],
      setConditionalFormatRules : function(rules) {
        this.setConditionalFormatRulesCalls.push({ args: rules }) 
      },
      getConditionalFormatRulesCalls : [],
      getConditionalFormatRules : function() { 
        return this.rules
      },
      range: [],
      getRangeCalls: [],
      getRange: function(str) { 
        this.getRangeCalls.push({ args : str })
        return this.range;
      }
    }

  })

  QUnit.test(""test setFormattingFor"",
             function() {
               val = setFormattingFor(sheet)
               // sheet.getRange should have been called
               ok(sheet.getRangeCalls.length, ""sheet.getRange was called at least once"")
               equal(val, sheet, ""setFormattingFor returned something"")
             })
  QUnit.test(""test setFormattingFor with no args"",
             function() { 
               throws(function() { 
                 setFormattingFor()

               })
             })
  QUnit.testDone(function() { 
    SpreadsheetApp = savedSpreadsheetApp
  })
}
</code></pre>

<p><strong>Result</strong></p>

<p>In introducing the second tests, both tests now fail: </p>

<p><a href=""https://i.stack.imgur.com/wPE12.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/wPE12.png"" alt=""Test against createDriverMenu""></a></p>

<p>Full text:</p>

<pre><code>Died on test #1  at qunit.js (QUnit):1494 (sourceFromStacktrace) at qunit.js (QUnit):461 at gas-qunit (QUnit):191 (test) at tests:54 (testCreateDriverMenu) at tests:6 (tests) at gas-qunit (QUnit):56 (load) at Code:11 (doGet) : Cannot find function getUi in object [object Object].
Source:     
 at Code:47 (createDriverMenu) at tests:58 at qunit.js (QUnit):213 at qunit.js (QUnit):399 at qunit.js (QUnit):1542 (process) at qunit.js (QUnit):528 at qunit.js (QUnit):1294 at gas-qunit (QUnit):57 (load) at Code:11 (doGet) 
</code></pre>

<p><a href=""https://i.stack.imgur.com/sTTAY.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/sTTAY.png"" alt=""Test against setFormattingFor""></a></p>

<p>Full text:</p>

<pre><code>Died on test #1  at qunit.js (QUnit):1494 (sourceFromStacktrace) at qunit.js (QUnit):461 at gas-qunit (QUnit):191 (test) at tests:592 (testSetFormattingFor) at tests:15 (tests) at gas-qunit (QUnit):56 (load) at Code:11 (doGet) : Cannot find function whenTextEqualTo in object [object Object].
Source:     
 at Code:173 (setFormattingFor) at tests:594 at qunit.js (QUnit):213 at qunit.js (QUnit):399 at qunit.js (QUnit):1542 (process) at qunit.js (QUnit):528 at qunit.js (QUnit):1294 at gas-qunit (QUnit):57 (load) at Code:11 (doGet) 
</code></pre>

<p>If I were to remove the new test, I simply get all tests passing.</p>

<p><strong>Why is state pollution occurring in QUnit, even though I set the global objects to their stubs in the test setups, and revert the states back in the test teardowns?</strong></p>
",https://stackoverflow.com/questions/52595947/qunit-global-object-states-being-polluted-in-the-unit-tests,"['unit-testing', 'google-apps-script', 'qunit']",98,FALSE,1,0
How to test keyboard navigation with Vue?,"<p>I'm unit-testing a component using <code>@vue/test-utils</code> which come with the Vue CLI (version 3). I want to test for keyboard interaction.</p>

<p>The docs <a href=""https://vue-test-utils.vuejs.org/guides/#testing-key-mouse-and-other-dom-events"" rel=""nofollow noreferrer"">mention the keyboard</a> but it seems like that only applies to actual listeners.
For example, if I have a button like</p>

<pre><code>&lt;button @click=""trigger()""&gt;Button&lt;/button&gt;
</code></pre>

<p>and I try to do </p>

<pre><code>wrapper.find('button').trigger('keydown.enter')
</code></pre>

<p>that doesn't register (I think) because I never explicitly do</p>

<pre><code>&lt;button @keydown.enter=""trigger()""&gt;Button&lt;/button&gt;.
</code></pre>

<p>Also, it seems like I cannot navigate around with the keyboard. How do I test that <a href=""https://hiddedevries.nl/en/blog/2017-01-29-using-javascript-to-trap-focus-in-an-element"" rel=""nofollow noreferrer"">focus is trapped</a> in a popover menu if I cannot press the <kbd>Tab</kbd> key from the tests?</p>

<p><a href=""https://github.com/vuejs/vue-test-utils/issues/484"" rel=""nofollow noreferrer"">This</a> seems relevant but doesn't offer any solution.</p>
",https://stackoverflow.com/questions/52269846/how-to-test-keyboard-navigation-with-vue,"['testing', 'vue.js', 'accessibility', 'vue-test-utils']",884,FALSE,1,0
Testing NGXS states with sub states feeds wrong state into action handler,"<p>Setup:</p>

<p>I have a parent state defined as </p>

<pre><code>@State&lt;ParentStateModel&gt;({
  name: 'grid',
  defaults: {
    parentData: 'some data'
  },
  children: [LoadingState]
})
export class ParentState {
  @Action(Action1)
  action1(ctx: stateContext&lt;ParentStateModel&gt;, action: Action1) {
    // In production this state will be ParentStateModel as expected
    // but in unit test, it will be of type LoadingState 
    const state = ctx.getState();
  }
}
</code></pre>

<p>And a child state defined as</p>

<pre><code>@State&lt;LoadingStateModel&gt;({
  name: 'gridLoading',
  defaults: {
    loading: false
  }
})
export class LoadingState{
  @Action(Action1)
  action1(ctx: stateContext&lt;LoadingStateModel&gt;, action: Action1) {
    ctx.setState({loading: true});
  }
}
</code></pre>

<p>Notice that both states respond to <code>Action1</code>.</p>

<p>When running this in production, it works as it should. The loading state takes care of the LoadingStateModel and the ParentState takes care of the ParentStateModel.</p>

<p>But when unit testing the code, the action handler in ParentState is fed the LoadingStateModel instead of the ParentStateModel (see comment in code).</p>

<p>My unit test is setup as follows </p>

<pre><code>TestBed.configureTestingModule({
  imports: [NgxsModule.forRoot([CashflowState, LoadingState])]
});
</code></pre>

<p>If I do not include LoadingState in the imports array, NGXS fails with <code>Child state not found: function LoadingState()</code></p>

<p>Am I doing something wrong, or is it a bug in NGXS?</p>
",https://stackoverflow.com/questions/53411562/testing-ngxs-states-with-sub-states-feeds-wrong-state-into-action-handler,['ngxs'],509,FALSE,1,0
Not able to mock the getTimestamp method on mocked Row,"<p>I am writing an application that interacts with Cassandra using Scala. While performing unit testing, I am using mockito wherein I am mocking the resultSet and row</p>

<pre><code>  val mockedResultSet = mock[ResultSet]
  val mockedRow = mock[Row]
</code></pre>

<p>Now while mocking the methods of the mockedRow, such as </p>

<pre><code>  doReturn(""mocked"").when(mockedRow).getString(""ColumnName"")
</code></pre>

<p>works fine. However, I am not able to mock the getTimestamp method of the mockedRow. I have tried 2 approaches but was not successful. </p>

<p>First approach</p>

<pre><code>  val testDate = ""2018-08-23 15:51:12+0530""
  val formatter = new SimpleDateFormat(""yyyy-mm-dd HH:mm:ssZ"")
  val date: Date = formatter.parse(testDate)
  doReturn(date).when(mockedRow).getTimestamp(""ColumnName"")
</code></pre>

<p>and second approach</p>

<pre><code>when(mockedRow.getTimestamp(""column"")).thenReturn(Timestamp.valueOf(""2018-08-23 15:51:12+0530""))
</code></pre>

<p>Both of them return null i.e it does not return the mocked value of the getTimestamp method. I am using cassandra driver core 3.0 dependency in my project.
Any help would br highly appreciated. Thanks in advance !!!</p>
",https://stackoverflow.com/questions/52001040/not-able-to-mock-the-gettimestamp-method-on-mocked-row,"['scala', 'cassandra', 'mockito']",182,TRUE,0,1
Is there a di-friendly File management library in Java?,"<p>I've used <a href=""https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html"" rel=""nofollow noreferrer"">this library</a> to work with files, but now I want to write simple unit tests.</p>

<p>Problem: Files class is static final, methods are static and so - are unmockable.
For me it's frustrating, because I now need to actually test the file system and actually test the results, when all I need to do is really just mock methods. Not really unit testing, when you need to actually use the environment.</p>

<p>Example code of the code now:</p>

<pre><code>public class MyClass
{
    public void myMethod(File myFile) throws IOException
    {
        Files.move(myFile.toPath(), myFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    }
}
</code></pre>

<p>I would like the code to be likes this:</p>

<pre><code>public class MyClass
{
    private final Files files;

    public MyClass(Files files)
    {
        this.files = files;
    }

    public void myMethod(File myFile) throws IOException
    {
        this.files.move(myFile.toPath(), myFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    }
}
</code></pre>

<p>So what I need is a class that does the same as ""Files"" , but is injectable</p>
",https://stackoverflow.com/questions/52060434/is-there-a-di-friendly-file-management-library-in-java,"['java', 'dependency-injection', 'filesystems']",953,TRUE,-2,2
"Test case linked to automated test (.NET Core, Jasmine, Jest, Xamarin)","<p>we are working on a system that consists of web and mobile apps. The web app is a SPA and the mobile app is developed with Xamarin. Both consume services written in .NET Core.</p>

<p>We use other unit test frameworks (Jasmine, JUnit, Jest,. Net coree) for unit testing and we need to link some of those test so certain test case in VSTS for regulatory and compliance purposes.</p>

<p>Is there any way we can link this unit tests to our test cases? or Any suggestion how we can document this unit tests with work items in VSTS using these frameworks?</p>
",https://stackoverflow.com/questions/51368915/test-case-linked-to-automated-test-net-core-jasmine-jest-xamarin,"['azure-devops', 'azure-pipelines', 'azure-pipelines-release-pipeline']",679,FALSE,0,1
How to type into input box using Javascript?,"<p>For unit testing, I need to press a key on input box using Javascript so that the input value could be updated.</p>

<p>Here is the example,</p>

<p>After moving cursor to end of input values, and I want to type in number 1 on end of the value using Javascript.</p>

<pre><code>// moving cursor to end of value
val inputVal = $target.val(); // current value 1
$target.val('').val(inputVal);

// now the cursor is end of the value

// using Javascript, typing 1 into input box, so that the value should be 11 

// not working, it couldn't update input value
$target[0].dispatchEvent(new KeyboardEvent('keydown',{'key':'1'}))
</code></pre>

<p>I want to test moving cursor and updating value, so I don't want to update input's value directly,</p>

<pre><code>$target.val(11);
</code></pre>

<p>Is there any way I can simulate pressing a key on input box using Javascript?</p>

<p>For testing I'm using jQuery1.3 which is very old version, so I want to do without jQuery library if I can.</p>
",https://stackoverflow.com/questions/49553799/how-to-type-into-input-box-using-javascript,"['javascript', 'jquery']",308,TRUE,0,2
How to test private member functions of a class using QTestLib?,"<p>I am using QTestLib for Unit Testing and i ask myself how to test private member functions of my classes. I would like to build a test suite for an in-house shared library.</p>

<p>What strategies do i have in Qt's context for this ?</p>

<p>I thought that testing private member functions through public members functions could be a good starting point :</p>

<pre><code>class A {

   public:
      // add an extra function that is only relevant for testing
      int value() const {
         return theFunctionIWantToTest();
      }

   private:
      int theFunctionIWantToTest() {
         // implementation ..
      }      
}
</code></pre>

<p>But the problem is that i don't need this getter in the class A after testing.</p>

<p>I am not very experienced with QTestLib and so far i could not find anything in Qt's Doc related to this specific point.</p>

<p>Thanks. </p>
",https://stackoverflow.com/questions/48600019/how-to-test-private-member-functions-of-a-class-using-qtestlib,"['c++', 'qt', 'testing', 'qtestlib']",357,TRUE,0,1
Angular Jasmine: TypeError: Cannot read property &#39;run&#39; of null,"<p>I am working on a project of Angular 5 with Ionic 3. I am using Jasmine for unit testing. I have integrated Angular-Cli for project. My setup was working till yesterday but today it is not working. On executing <code>test</code> command, it is showing following error:</p>

<blockquote>
  <p>TypeError: Cannot read property 'run' of null
          at 
          at UserContext. node_modules/zone.js/dist/jasmine-patch.js:106:1)
          at 
          at ZoneDelegate.webpackJsonp../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask
  node_modules/zone.js/dist /zone.js:421:1)
          at Zone.webpackJsonp../node_modules/zone.js/dist/zone.js.Zone.runTask
  node_modules/zone.js/dist/zone.js:188:1)
          at drainMicroTaskQueue node_modules/zone.js/dist/zone.js:595:1)
          at </p>
</blockquote>

<p>Any idea why it is happening ?</p>
",https://stackoverflow.com/questions/50075293/angular-jasmine-typeerror-cannot-read-property-run-of-null,"['angular', 'ionic-framework', 'jasmine', 'ionic3', 'angular5']",1072,TRUE,0,1
Angular 6 SSR TypeError: Cannot read property &#39;root&#39; of undefined,"<p>I have an angular 6.03 project using Angular Universal that is deployed to firebase. Until a few days ago all was working perfectly but last time I deployed I started getting cannot read property 'root' of undefined error.</p>

<pre><code>error: TypeError: Cannot read property 'root' of undefined
at new rootRoute (/Users/rebekahapelt/Projects/hapkido-website/functions/node_modules/@angular/router/bundles/router.umd.js:5390:35)
at _createClass (/Users/rebekahapelt/Projects/hapkido-website/functions/node_modules/@angular/core/bundles/core.umd.js:8445:24)
at _createProviderInstance (/Users/rebekahapelt/Projects/hapkido-website/functions/node_modules/@angular/core/bundles/core.umd.js:8417:30)
at initNgModule (/Users/rebekahapelt/Projects/hapkido-website/functions/node_modules/@angular/core/bundles/core.umd.js:8350:36)
at new NgModuleRef_ (/Users/rebekahapelt/Projects/hapkido-website/functions/node_modules/@angular/core/bundles/core.umd.js:9076:13)
at Object.createNgModuleRef (/Users/rebekahapelt/Projects/hapkido-website/functions/node_modules/@angular/core/bundles/core.umd.js:9065:16)
at NgModuleFactory_.create (/Users/rebekahapelt/Projects/hapkido-website/functions/node_modules/@angular/core/bundles/core.umd.js:11607:29)
at /Users/rebekahapelt/Projects/hapkido-website/functions/node_modules/@angular/core/bundles/core.umd.js:4375:47
at ZoneDelegate.invoke (/Users/rebekahapelt/Projects/hapkido-website/functions/node_modules/zone.js/dist/zone-node.js:388:26)
at Object.onInvoke (/Users/rebekahapelt/Projects/hapkido-website/functions/node_modules/@angular/core/bundles/core.umd.js:3890:37)
</code></pre>

<p>So I am a little confused and all other questions relating to this seem to be about unit testing.</p>

<p>My server.ts file looks like</p>

<pre><code>import 'zone.js/dist/zone-node';
import * as firebaseFunctions from 'firebase-functions';
import { enableProdMode } from '@angular/core';
import * as express from 'express';

const { AppServerModuleNgFactory, LAZY_MODULE_MAP} = require('./main');
import { ngExpressEngine } from '@nguniversal/express-engine';
import { provideModuleMap } from '@nguniversal/module-map-ngfactory-loader';

enableProdMode();

const app = express();

app.engine('html', ngExpressEngine({
  bootstrap:  AppServerModuleNgFactory,
  providers: [
    provideModuleMap(LAZY_MODULE_MAP)
  ]
}));

app.set('view engine', 'html');
app.set('views', __dirname);


app.get('*', (req, res) =&gt; {
  res.render('index', {req});
});


exports.ssrApp = firebaseFunctions.https.onRequest(app);
</code></pre>

<p>My github repo is <a href=""https://github.com/rapelt/hapkido-website"" rel=""nofollow noreferrer"">https://github.com/rapelt/hapkido-website</a></p>

<p>I am using Angular Material which has caused some interesting and annoying problems with animation but I have had all that fixed for quite a while.</p>

<p>Anyone got any suggestions?</p>
",https://stackoverflow.com/questions/52620088/angular-6-ssr-typeerror-cannot-read-property-root-of-undefined,"['angular', 'firebase', 'google-cloud-functions', 'angular6', 'server-side-rendering']",568,FALSE,0,1
Jenkins server integration with bitbucket cloud,"<p>Im new to jenkins server. I have a task. i will explain clearly here. I already created jenkins server on ubuntu ec2 server. my task that, 
1. jenkins should auto pull the code from bitbucket cloud(one repos url), when user raise Pull request. Then this code should send to unit testing.
2. If unit test passed , then this code send to future test like web testing as well jenkins send the unit test report as html report to user by mail notification. (if unit test failed then jobs should drop)
3. webtesting should run on maven project.(becuase the webtesting code have pom.xml file- which is used to test the code after the unit testing. This webtesting code in another repos url).
4. If webtesting passed ,then this report as html document send to user by mail notification. 
5. Then when  user merge and approve the code then jenkins should deploy the code on target server automatically. Then jenkins update build status(passwed/failed) in bitbucket cloud. Thats all</p>

<p>so finally im having two repos url, one for code deploy and another one for webtesting. Im new to jenkins server. I m struggling with jenkins server.Please help me to finish it.so please tell me the steps and what are the plug ins should i install and how to execute this? guide me ..i hope you people understand my task. 
else mail me: slakshminarayanan@live.com</p>
",https://stackoverflow.com/questions/53276102/jenkins-server-integration-with-bitbucket-cloud,['jenkins'],61,FALSE,1,0
How can you access a link function scope value in Jasmine test spec?,"<p>I'm unit testing an Angular directive via the link function. By compiling the directive as
suggested here -  <a href=""http://brilliantbritz.com/2015/02/04/getting-the-isolate-scope-of-a-directive/"" rel=""nofollow noreferrer"">http://brilliantbritz.com/2015/02/04/getting-the-isolate-scope-of-a-directive/</a></p>

<p>The first set of tests are running fine and 
I have access to the element.scope() object, i.e, isolatedScope of the directive.</p>

<p>But when running the below test to get the <code>scope.welcomeMessage</code> value from the link function.
it returns undefined:</p>

<pre><code>it(""should contain a welcomeMessage scope value"", function() {
    console.log(element.scope()); //value present in scope object
    expect(element.scope().welcomeMessage).toBe(""Hello World!""); //undefined
  });
</code></pre>

<p>I debugged this issue by logging the element.scope() value which does contain the <code>welcomeMessage</code>.</p>

<p>Question:</p>

<p>How can you access a link function scope value in Jasmine test spec?</p>

<p><em>my-app.spec.js</em></p>

<pre><code> describe(""my-app"", function() {
  var $scope, $compile, element;

  beforeEach(function(){
    //register module and mock dependency
    angular.mock.module(""my-app"");

  });

  beforeEach(inject(function($rootScope, _$compile_) {

    $scope = $rootScope.$new(), //create instance of rootScope
    $compile = _$compile_; // compile attaches directives to HTML template
    element = $compile(""&lt;my-app&gt;&lt;/my-app&gt;"")($scope);
    $scope.$digest(); //loop through DOM watchers, check values and trigger listeners
  }));

  it(""should contain a defined scope"", function() {
    expect(element.scope()).toBeDefined(); //true
  });

  it(""should contain a welcomeMessage scope value"", function() {
    console.log(element.scope());
    expect(element.scope().welcomeMessage).toBe(""Hello World!""); //undefined
  });

});
</code></pre>

<p><em>Log value of element.scope()</em></p>

<pre><code>LOG LOG: Scope{$$childTail: Scope{$id: 12, $$childTail: null, $$childHead: null, $$prevSibling: null, $$nextSibling: null, $$watchers: 
[..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ..., ...], $parent: Scope{$$childTail: ..., $$childHead: ..., 
$$nextSibling: ..., $$watchers: ..., $$listeners: ..., $$listenerCount: ..., $$watchersCount: ..., $id: ..., $$ChildScope: ..., $parent: ..., $$prevSibling: ...}, 
$$phase: null, $root: Scope{$id: ..., $$childTail: ..., $$childHead: ..., $$prevSibling: ..., $$nextSibling: ..., $$watchers: ..., $parent: ..., $$phase: ..., 
$root: ..., $$destroyed: ..., $$listeners: ..., $$listenerCount: ..., $$watchersCount: ..., $$isolateBindings: ..., $$asyncQueue: ..., $$postDigestQueue: ..., 
$$applyAsyncQueue: ..., $$ChildScope: ...}, $$destroyed: false, $$listeners: Object{$destroy: ...}, $$listenerCount: Object{$destroy: ...}, $$watchersCount: 21, 
$$isolateBindings: Object{}, welcomeMessage: 'Hello World!'}, $$childHead: Scope{$id: 12, $$childTail: null, $$childHead: null, $$prevSibling: null, $$nextSibling: null, 
</code></pre>

<p><em>gist of directive</em></p>

<pre><code>(function() {

  var component = {
    id: ""my-app"",
    name: ""my-app"",
    templateUrl: ""my-app/my-app.html""
  };

  component.ui = angular.module(""my-app"");
  component.ui.directive(""myApp"", fizzComponent);

  function fizzComponent() {

    function fizzContainer(scope, element, params) {

      scope.welcomeMessage = ""Hello World!"";  
    }
    return {
      scope: {},
      replace: true,
      link: fizzContainer,
      templateUrl: component.templateUrl
    };
  }
})();
</code></pre>
",https://stackoverflow.com/questions/48526747/how-can-you-access-a-link-function-scope-value-in-jasmine-test-spec,"['angularjs', 'unit-testing', 'jasmine']",561,TRUE,0,1
Exception Handling - try blocks,"<p>I just started reading about error handling. I understand the basics and how the exceptions are thrown and caught. But I'm lost where I'm supposed to have the try blocks. If I have a program and I want to catch multiple errors that are located in various places, would I enclose my entire code in one try block. From what I've read you can have one try block? Or is error handling use for unit testing? For example, when you run into an error, you would manually enclose that part of the code in the try block to fix it.</p>
",https://stackoverflow.com/questions/51522202/exception-handling-try-blocks,"['c++', 'exception', 'try-catch']",48,FALSE,0,0
Python Mockito configuration for running test cases,"<p>I am writing unit tests for a Flask app using <code>unittest</code> and using <code>mockito</code> to mock the services which require the server to be up and running.</p>

<p>However I am unable to figure out how to mock the server. I am getting some error. </p>

<p>Here are the code snippets:</p>

<p><strong>node.py</strong></p>

<pre><code>@app.route('/transaction', methods = [""POST""])
def transaction():
    req = request.get_json()
    print(""\nreq"")
    i = bitcoin.addTransaction(req)

    if req['purpose'] != 'redeem':
        users = getColumn(sheet_u,0)
        index = users.index(req['recipient'])
        user = getRow(sheet_u,index)
        hasPoints = int(user[labels_u.index(""POINTS"")])
        hasPoints += req['amount']
        setCell(sheet_u, index, labels_u.index(""POINTS""), hasPoints)
        wb.save(""db.xlsx"")
    else:
        users = getColumn(sheet_u,0)
        index = users.index(req['sender'])
        user = getRow(sheet_u,index)
        hasPoints = int(user[labels_u.index(""POINTS"")])
        hasPoints -= req['amount']
        setCell(sheet_u, index, labels_u.index(""POINTS""), hasPoints)
        wb.save(""db.xlsx"")
    r = requests.get(url = bitcoin.currentNodeUrl+""/save"")  
    return jsonify({""note"":""New transaction will be added to block ""+str(i)})


@app.route('/transaction/broadcast', methods = [""POST""])
def transactionBroadcast():
    check = True
    failure = """"
    req = request.get_json()
    # Hiding some methods that change the value of check flag 
    if check:
        newTransaction = bitcoin.createNewTransaction(req['amount'],req['sender'],req['recipient'],req['purpose'],time.time())
        bitcoin.addTransaction(newTransaction)
        promises = []
        for node in bitcoin.networkNodes:
            response = """"
            try:
                r = requests.post(url=node+""/transaction"",json=newTransaction) #this line throws error
                response = r.text   #program control doesn't come here
                print(newTransaction)
                print(""\n"")
                print(response)
            except requests.exceptions.ConnectionError:
                response = ""{\""note\"":\""The node is unavailable. It will sync itself later on.\""}""
            if 'note' in json.loads(response):
                promises.append(json.loads(response))
        if len(promises) == len(bitcoin.networkNodes):
            r = requests.get(url = bitcoin.currentNodeUrl+""/save"")  
            return jsonify({""note"":""Transaction broadcasted successfully""})
    else:
        return jsonify({""fail"":""Invalid transaction. ""+failure})
if __name__ == '__main__':
    bitcoin = Blockchain(sys.argv[1])
    app.run(port=sys.argv[1])
</code></pre>

<p><strong>test_t2.py</strong></p>

<pre><code>from node import app
from flask import json
import unittest
import node
import requests

from mockito import when, mock, unstub

class TestSearch(unittest.TestCase):
    print(""inside TEST class"")

    def test_transactionBroadcast(self):  

        node.bitcoin = node.Blockchain('5000')
        response = mock({""note"": ""New transaction will be added to block 5""})
        when(requests).post('http://localhost:5001/transaction', strict = False ).thenReturn(response)

        data1 = {
            ""sender"" : ""ph1000005"",
            ""recipient"" : ""TIAA"",
            ""amount"" : 1,
            ""purpose"" : ""redeem""
        }
        response = app.test_client().post(
            '/transaction/broadcast',
            json = data1,
            content_type='application/json',
        )
        print(""running TransactionBroadcast test"")
        print(response)
        self.assertEqual(response.get_json(), {
            # 'fail': ""Invalid transaction. This user doesn't exist. Check userid again.""
            ""note"": ""Transaction broadcasted successfully""
        })
        unstub()
if __name__ == '__main__':
    unittest.main()
</code></pre>

<p><strong>error log</strong></p>

<pre><code>C:\POC&gt;coverage run test_t2.py
inside TEST class
[2018-12-12 19:58:22,181] ERROR in app: Exception on /transaction/broadcast [POST]
Traceback (most recent call last):
  File ""c:\program files\python36\lib\site-packages\flask\app.py"", line 2292, in wsgi_app
    response = self.full_dispatch_request()
  File ""c:\program files\python36\lib\site-packages\flask\app.py"", line 1815, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File ""c:\program files\python36\lib\site-packages\flask\app.py"", line 1718, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File ""c:\program files\python36\lib\site-packages\flask\_compat.py"", line 35, in reraise
    raise value
  File ""c:\program files\python36\lib\site-packages\flask\app.py"", line 1813, in full_dispatch_request
    rv = self.dispatch_request()
  File ""c:\program files\python36\lib\site-packages\flask\app.py"", line 1799, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File ""C:\POC\node.py"", line 230, in transactionBroadcast
    r = requests.post(url=node+""/transaction"",json=newTransaction)
  File ""c:\program files\python36\lib\site-packages\mockito\mocking.py"", line 89, in new_mocked_method
    self, method_name, *args, **kwargs)
  File ""c:\program files\python36\lib\site-packages\mockito\mocking.py"", line 44, in remembered_invocation_builder
    return invoc(*args, **kwargs)
  File ""c:\program files\python36\lib\site-packages\mockito\invocation.py"", line 103, in __call__
    """""" % (self, ""\n    "".join(str(invoc) for invoc in stubbed_invocations)))
mockito.invocation.InvocationError:
You called

        post(url='http://localhost:5001/transaction', json={'amount': 1, 'purpose': 'redeem', 'recipient': 'TIAA', 'sender': 'ph1000005', 'timestamp': 1544624902.1440911, 'transactionId': 'd919ffb4080f47e890957f3f3edc97a1'}),

which is not expected. Stubbed invocations are:

        post('http://localhost:5001/transaction', strict=False)

(Set strict to False to bypass this check.)

running TransactionBroadcast test
&lt;Response streamed [500 INTERNAL SERVER ERROR]&gt;
F
======================================================================
FAIL: test_transactionBroadcast (__main__.TestSearch)
----------------------------------------------------------------------
Traceback (most recent call last):
  File ""test_t2.py"", line 49, in test_transactionBroadcast
    ""note"": ""Transaction broadcasted successfully""
AssertionError: None != {'note': 'Transaction broadcasted successfully'}

----------------------------------------------------------------------
Ran 1 test in 0.682s

FAILED (failures=1)
</code></pre>

<p>Now, I'm not sure what am I doing wrong. there is an internal route call to <code>/transaction</code> in the route <code>/transaction/broadcast</code> which is failing.
Since this is a unit testing, it doesn't require the server to be up and running. and the route is calling <code>localhost</code></p>

<p>Any ideas on how to deal with it?</p>
",https://stackoverflow.com/questions/53756239/python-mockito-configuration-for-running-test-cases,"['python', 'flask', 'mockito', 'python-unittest']",673,TRUE,0,1
Should we unit test predicate methods,"<p>I am working on unit testing and I am trying to increase the line coverage to 90% of a class. The class contains lot of predicate methods which only compare some of its fields and based on that it returns true or false. 
My question is, should I write unit tests for those predicate methods or not. 
Currently, I have written unit tests which just initialize the object and set its fields and then assert if return value of predicate is correct. </p>

<p>For example:</p>

<pre><code>public boolean isScheduled() {
   return getShippingDate() != null;
}
</code></pre>

<p>How should I unit test it and what should be the unit test method name? </p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/51396469/should-we-unit-test-predicate-methods,"['unit-testing', 'junit']",1504,TRUE,0,1
Jasmine unit test on HTML Element attribute that is changed in setTimeout(),"<p>I'm new to Jasmine unit testing, and I can't seem to wrap my head around this issue, and I wasn't able to find a solution by searching google.</p>

<p>The user clicks the button, which changes the display property from ""none"" to ""block"", then resets it to ""none"" in the setTimeout()</p>

<p>HTML:</p>

<pre><code>&lt;div style=""display: none"" [attr.id]=""'copy-tooltip' + rowIndex""&gt;VIN Copied&lt;/div&gt;
&lt;button (click)=""showTooltip(rowIndex)""&gt;Show Tooltip&lt;button&gt;
</code></pre>

<p>TS:</p>

<pre><code>showTooltip(index: number){
    var elem = document.getElementById('copy-tooltip' + index);
    elem.style.display = ""block"";
    setTimeout( () =&gt; {
      elem.style.display = ""none"";
    }, 2500);
}
</code></pre>

<p>I need to write a unit test that creates a mock HTML element with the id of ""copy-tooltip0"", then check a) that it sets <code>display</code> to ""block"", and b) that it sets <code>display</code> to ""none"" after the setTimeout(). None of the solutions I've come up with have seemed to work.</p>
",https://stackoverflow.com/questions/52045699/jasmine-unit-test-on-html-element-attribute-that-is-changed-in-settimeout,"['javascript', 'unit-testing', 'jasmine']",226,FALSE,0,0
NUnit test of constructor fails because of missing parameter,"<p>I am trying to run a Unit Test using NUnit and have therefore followed a tutorial, which states the following:</p>

<pre><code>[TestFixture]
public class TestFootballplayerController
{
    [Test]
    public void FootBallPlayer_CheckingIfControllerReturnsCorrectView_MustReturnTrue()
    {
        string expected = ""CreatePlayer"";
        FootballplayerController controller = new FootballPlayerController();

        var result = controller.CreateIngredient() as ViewResult;

        Assert.AreEqual(expected, result.ViewName);
    }
}
</code></pre>

<p>The tutorial assumes I have a empty default constructor, but my constructor contains a parameter with my DBContext as follows:</p>

<pre><code>    public class FootballplayerController : Controller
{
    private readonly FootballContext _context;

    public FootballplayerController(FootballContext context)
    {
        _context = context;
    }

    public IActionResult CreatePlayer()
    {
        return View();
    }
}
</code></pre>

<p>Visual Studio suggests that I create an empty constructor, but in that way I think I will just test something, that shouldn't be tested, instead of the correct constructor with the parameter.</p>

<p>If the answer is obvious, then I must say, I am new to unit testing, and can't work a way around this. Do I have to fake a parameter?</p>
",https://stackoverflow.com/questions/53416218/nunit-test-of-constructor-fails-because-of-missing-parameter,"['c#', 'asp.net-mvc', 'unit-testing', 'testing', 'nunit']",359,FALSE,0,1
Combining TextContent and information from elements with jQuery,"<p>How can I combine text content and content of elements with jQuery?</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 getText(key, node) {
    if (node.tagName == 'INPUT') {
        return node.value;
    } else {
        return node.textContent;
    }
}

console.log($(""div"").find('*').map(getText).get().join(' ').trim().replace(/\s+/g, ' '));</code></pre>
<pre class=""snippet-code-html lang-html prettyprint-override""><code>&lt;script src=""https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js""&gt;&lt;/script&gt;
&lt;div&gt;
 &lt;span&gt;A&lt;/span&gt;
 &lt;div&gt;
   B
   &lt;input value='4'&gt;
   &lt;span&gt;C&lt;/span&gt;
 &lt;/div&gt;
&lt;/div&gt;</code></pre>
</div>
</div>
</p>

<p>should be rendered to the string ""A B 4 C"". </p>

<p>It is no problem to get just the textContent with <code>.text()</code> or render the values of the input elements with <code>.map(function(){return $(this).val();}).get().join(' ')</code> but getting both combined in the right order is difficult.</p>

<p>EDIT: The implementation should work on every depth of nesting elements. It is used to get a comparable output for unit testing parts of a web page where some visible texts like labels are rendered into span and other parts like editable values are in input elements.</p>
",https://stackoverflow.com/questions/49366009/combining-textcontent-and-information-from-elements-with-jquery,"['javascript', 'jquery']",294,FALSE,0,3
Do I need Mocha if looks like pure JS is enough for me?,"<p>I am developing a WebExtension for browsers, and I want to start TDD. Usually, folks without experience in testing of client-side JS just google for a popular framework and stick with it - even without trying to test functions in pure JS. I do not like dependencies - I use anything only if I understand what problem it resolves, I like simplicity. Currently, I do not know why I need any Javascript unit-testing framework. Now I see at popular <a href=""https://mochajs.org"" rel=""nofollow noreferrer"">https://mochajs.org</a> and do not see reasons to use it.</p>

<p>Now my code looks like this:</p>

<pre><code>function unitTests() {  // eslint-disable-line no-unused-vars

(function _prepareRemoving_test() {
    (function _setUp() {
        _testUtils._fillDB();
    })();

    (async function _isUnique() {
        const {itemFeed, isUniqueForUser} = await _prepareRemoving(_testUtils['id']);
        console.assert(itemFeed['hashArticle'] === _testUtils['val']['hashArticle'], itemFeed);
        console.assert(isUniqueForUser === true, isUniqueForUser);
    })();
    _testUtils._addArticleWithDuplicatedHash();
    (async function _isNotUniqueWhenPreviousWithTheSameHash() {
        const {itemFeed, isUniqueForUser} = await _prepareRemoving(_testUtils['id3']);
        console.assert(itemFeed['hashArticle'] === _testUtils['val3']['hashArticle'], itemFeed);
        console.assert(isUniqueForUser === false, isUniqueForUser);
    })();
    (async function _isNotUniqueWhenNextWithTheSameHash() {
        const {itemFeed, isUniqueForUser} = await _prepareRemoving(_testUtils['id2']);
        console.assert(itemFeed['hashArticle'] === _testUtils['val2']['hashArticle'], itemFeed);
        console.assert(isUniqueForUser === false, isUniqueForUser);
    })();

    (function _tearDown() {
        _testUtils._clearDB();
    })();

})();

(function _syncHistory_test() {
    // ===== setup =====
    const fetchOriginal = window.fetch;
    const chromeOriginal = window.chrome;
    // ===== end of setup =====

    (function _added() {
        (function _mock() {
            window.fetch = function() {
                _testUtils._mock(fetch, arguments);
                return fetchOriginal('unitTests/_syncHistory/mockResponses/added.json');
            };
            window._getArticle = function() {
                _testUtils._mock(_getArticle, arguments);
                return Promise.resolve();
            };
            window._persistItemFeed = function() {
                _testUtils._mock(_persistItemFeed, arguments);
            };
            chrome.runtime.sendMessage = function() {
                _testUtils._mock(chrome.runtime.sendMessage, arguments);
            };
            chrome.storage.sync.set = function() {
                _testUtils._mock(chrome.storage.sync.set, arguments);
            };
        })();

        _syncHistory(0, 'myFakeIdToken');

        console.assert(fetch['hasCalls'].length === 1);
        console.assert(fetch['hasCalls'][0][0] === `${stageUrlNew}history?updated=0`);
        console.assert(
            fetch['hasCalls'][0][1]['headers']['Authorization'] = 'myFakeIdToken'
        );

        setTimeout(_ =&gt; {  // setTimeout for waiting all callbacks from fetch()
            console.assert(_getArticle['hasCalls'].length === 1);
            console.assert(_getArticle['hasCalls'][0][0] === 1537886629);
            console.assert(
                _persistItemFeed['hasCalls'][0][0] === '1537886629'
            );
            console.assert(
                _persistItemFeed['hasCalls'][0][1] === 'https://example.com/favicon.ico'
            );
            console.assert(
                _persistItemFeed['hasCalls'][0][2] === 'https://example.com/my-article'
            );
            console.assert(
                _persistItemFeed['hasCalls'][0][3] === 'The title of article'
            );
            console.assert(
                _persistItemFeed['hasCalls'][0][4] === false
            );
            console.assert(
                _persistItemFeed['hasCalls'][0][5] === true
            );
            console.assert(
                _persistItemFeed['hasCalls'][0][6] === false
            );
            console.assert(
                _persistItemFeed['hasCalls'][0][7] === '75042f43e7ba2228934f75d96a02f7a1'
            );
            console.assert(
                _persistItemFeed['hasCalls'][0][8] === 1
            );

            console.assert(chrome.runtime.sendMessage['hasCalls'].length === 1);
            console.assert(
                chrome.runtime.sendMessage['hasCalls'][0][0]['fromPopup'] === '_cacheSynced'
            );
            console.assert(
                chrome.runtime.sendMessage['hasCalls'][0][0]['hashArticle'] ===
                    '75042f43e7ba2228934f75d96a02f7a1'
            );
            console.assert(
                chrome.runtime.sendMessage['hasCalls'][0][0]['id'] === '1537886629'
            );
            console.assert(
                chrome.runtime.sendMessage['hasCalls'][0][0]['lenChunks'] === '1'
            );
            console.assert(
                chrome.runtime.sendMessage['hasCalls'][0][0]['idToken'] === 'myFakeIdToken'
            );

            console.assert(
                chrome.storage.sync.set['hasCalls'].length === 1
            );
            console.assert(
                typeof chrome.storage.sync.set['hasCalls'][0][0]['updated'] === 'number'
            );
            console.assert(
                Number.isInteger(chrome.storage.sync.set['hasCalls'][0][0]['updated'])
            );
            console.assert(
                (chrome.storage.sync.set['hasCalls'][0][0]['updated'] + '').length === 10
            );

            _syncHistory(1537886629, 'myFakeIdToken');
            console.assert(fetch['hasCalls'].length === 2);
            console.assert(
                fetch['hasCalls'][1][0] === `${stageUrlNew}history?updated=1537886629`
            );
            console.assert(
                fetch['hasCalls'][1][1]['headers']['Authorization'] = 'myFakeIdToken'
            );

            (function _tearDown() {
                window.fetch = fetchOriginal;
                window.chrome = chromeOriginal;
            })();

        }, 100);
    })();
}
</code></pre>

<p>My helper function:</p>

<pre><code>const _testUtils = {  // eslint-disable-line no-unused-vars
    id:  1000000,
    id1: 1111111,
    id2: 2222222,
    id3: 3333333,
    val:  {'hashArticle': '75042f43e7ba2228934f75d96a02f7a0', 'cache': [new Blob(), new Blob()]},
    val1: {'hashArticle': '75042f43e7ba2228934f75d96a02f7a1', 'cache': [new Blob(), new Blob()]},
    val2: {'hashArticle': '75042f43e7ba2228934f75d96a02f7a2', 'cache': [new Blob(), new Blob()]},
    val3: {'hashArticle': '75042f43e7ba2228934f75d96a02f7a2', 'cache': [new Blob(), new Blob()]},

    _fillDB: function() {
        return Promise.all([
            _insertOrReplace(this.id,  this.val),
            _insertOrReplace(this.id1, this.val1),
            _insertOrReplace(this.id2, this.val2)
        ]);
    },
    _addArticleWithDuplicatedHash: function() {
        _insertOrReplace(this.id3, this.val3);
    },
    _clearDB: function() {
        _deleteArticle(this.id);
        _deleteArticle(this.id1);
        _deleteArticle(this.id2);
        _deleteArticle(this.id3);
    },
    _hasCallsify: function(obj) {
        if (!obj['hasCalls']) {
            obj['hasCalls'] = [];
        }
    },
    _mock: function(obj, _arguments) {
        this._hasCallsify(obj);
        obj['hasCalls'].push(_arguments);
    }
};
</code></pre>
",https://stackoverflow.com/questions/52535237/do-i-need-mocha-if-looks-like-pure-js-is-enough-for-me,"['javascript', 'unit-testing', 'testing', 'mocha.js', 'firefox-addon-webextensions']",58,FALSE,0,0
Mockito when-thenReturn with SharedPreference value,"<p>I'm doing my first deep dive into unit testing with Mockito, so please bear with me. I'm working on this test:</p>

<pre><code>class PasswordStateManagerTest {

    private lateinit var passwordStateManager: PasswordStateManager

    @MockK
    private lateinit var mockContext: Context

    @MockK
    private lateinit var mockSharedPreferences: SharedPreferences

    @Before
    fun setup() {
        MockKAnnotations.init(this, true)
        every{ mockContext.getApplicationSharedPreferences() } returns mockSharedPreferences

        // this is the line that won't compile
Mockito.when(mockSharedPreferences.getBoolean(""save_password"", false)
    )
                    .thenReturn(true)

        passwordStateManager = PasswordStateManager(mockSharedPreferences)
    }    
}
</code></pre>

<p>The when.thenReturn line won't compile. It is expecting an open bracket <code>{</code> character where I am trying to execute on <code>.thenReturn</code>. As I read the docs, there is no place for an open bracket in this statement, so I must be off the rails.</p>

<p>Here is the part of the init method of the class being tested, which is what creates the need for the when-thenReturn line in the test:</p>

<pre><code>init {
    willSavePassword = prefs.getBoolean(""save_password"", false)
}
</code></pre>

<p>Thanks for any help (and patience while I get up to speed!).</p>
",https://stackoverflow.com/questions/53857204/mockito-when-thenreturn-with-sharedpreference-value,"['android', 'unit-testing', 'mockito']",153,TRUE,0,1
Mocking Services in ASP.NET Core,"<p>I have a simple form to save and then use MailKit to provide email notification, with xUnit and Moq used for unit testing. I'm having difficulty setting up the unit test and associated services. I have a workaround ('if' statement in the action method) to only test the core repo saving functionality without also testing the email service. If I take out the if statement, the unit test does not have access to the appropriate methods, such as setting the web root path. The error is a null exception. If I default this value, there are other errors, such as ""no database provider being configured for DbContext.""</p>

<p>Is there a more appropriate way to set a unit test of this sort up? Or is it wrong to set up a unit test to test both the Create() and email functionality because it violates the one-function unit testing rule? </p>

<p>Unit test:</p>

<pre><code> [Fact]
        public void Can_Create_New_Lesson()
        {
            //Arrange
            //create a mock repository
            Mock&lt;IHostingEnvironment&gt; mockEnv = new Mock&lt;IHostingEnvironment&gt;();
            Mock&lt;ILessonRepository&gt; mockRepo = new Mock&lt;ILessonRepository&gt;();
            Mock&lt;UserManager&lt;AppUser&gt;&gt; mockUsrMgr = GetMockUserManager();
            Mock&lt;RoleManager&lt;IdentityRole&gt;&gt; mockRoleMgr = GetMockRoleManager();
            var opts = new DbContextOptions&lt;AppIdentityDbContext&gt;();
            Mock &lt;AppIdentityDbContext&gt; mockCtx = new Mock&lt;AppIdentityDbContext&gt;(opts);
            //create mock temporary data
            Mock&lt;ITempDataDictionary&gt; tempData = new Mock&lt;ITempDataDictionary&gt;();
            //create the controller
            LessonController target = new LessonController(mockRepo.Object, mockEnv.Object, mockUsrMgr.Object, mockRoleMgr.Object, mockCtx.Object)
            {
                TempData = tempData.Object
            };
            //create a lesson
            Lesson lesson = new Lesson { Title = ""Unit Test"", Domain= ""Unit Test""};

            //Act
            //try to save the product using the Create method of the controller
            IActionResult result = target.Create(lesson);

            //Assert
            //check that the repository was called
            mockRepo.Verify(m =&gt; m.SaveLesson(lesson));
            //check the result type is a redirection to the List action method of the controller
            Assert.IsType&lt;RedirectToActionResult&gt;(result);
            Assert.Equal(""Success"", (result as RedirectToActionResult).ActionName);
        }
</code></pre>

<p>The Create() action method:</p>

<pre><code>[HttpPost]
        public IActionResult Create(Lesson lesson)
        {
            if (ModelState.IsValid)
            {
                repository.SaveLesson(lesson);

                //This IF statement is a workaround for the unit test
                //don't email users if the Title is ""Unit Test""
                if (lesson.Title != ""Unit Test"")
                {
                    emailUsers(lesson);
                }

                TempData[""message""] = $""{lesson.Title} has been saved"";

                //show the user that the update was made successfully
                return RedirectToAction(""Success"");
            }
            else
            {
                //there is a problem with the data values
                return View(lesson);
            }
        }
</code></pre>

<p>Email function:</p>

<pre><code>public void emailUsers(Lesson lesson)
{
    var webRoot = environment.WebRootPath;
    var filePath = System.IO.Path.Combine(webRoot, ""email\\NewLessonSubmitted.txt"");
    string message = System.IO.File.ReadAllText(filePath);
    string domain = lesson.Domain;
    IQueryable&lt;AppUser&gt; userList = GetUsersInRole(identityContext, domain); 

    //if there are users in that domain, send the email
    if (userList != null)
    {
        foreach (AppUser user in userList)
        {
            sendEmail(domain, message, user.Email);
        }
    }
}
</code></pre>

<p>EDIT: I've instead implemented the email service as a class, as pointed out by MotoSV. However, I'm still getting an error for ""No database provider has been configured for this DbContext"" The stack trace for the exception points to the following method:</p>

<pre><code>public static IQueryable&lt;AppUser&gt; GetUsersInRole(AppIdentityDbContext db, string roleName)
        {
            if (db != null &amp;&amp; roleName != null)
            {
                var roles = db.Roles.Where(r =&gt; r.Name == roleName);
                if (roles.Any())
                {
                    var roleId = roles.First().Id;
                    return from user in db.Users
                           where user.Roles.Any(r =&gt; r.RoleId == roleId)
                           select user;
                }
            }
            return null;
        }
</code></pre>

<p>I have this constructor in my dbContext class:</p>

<pre><code>public AppIdentityDbContext(DbContextOptions&lt;AppIdentityDbContext&gt; options)
            : base(options) { }
</code></pre>

<p>EDIT: The solution (provided by MotoSV) was to:
1) Create an email service class with appropriate methods and
2) Install the appropriate Nuget package for Microsoft.EntityFrameworkCore.InMemory
3) mock the DbContext as:</p>

<pre><code>var opts = new DbContextOptionsBuilder&lt;AppIdentityDbContext&gt;()
                  .UseInMemoryDatabase(Guid.NewGuid().ToString())
                  .Options;
            Mock&lt;AppIdentityDbContext&gt; mockCtx = new Mock&lt;AppIdentityDbContext&gt;(opts);
</code></pre>
",https://stackoverflow.com/questions/48066758/mocking-services-in-asp-net-core,"['asp.net', 'unit-testing', 'asp.net-core-mvc']",3184,TRUE,1,3
Unit test for a config module that loads values from a file,"<p>New to Unit testing (using pytest) and trying to workout how I can test a config module which loads its values from an ini file in a way that isolates it from its environment. </p>

<p>I want to test that the values in the file are the same as what was loaded to the Configuration instance.</p>

<p>As shown the ini file is hardcoded in the module but don't want to be tied to config.ini when its potentially unavailable.</p>

<p>This is a simplied version of the config module:</p>

<pre><code>from configparser import ConfigParser

class Configuration():
    def __init__(self, ini_file):
        parser = ConfigParser()
        parser.read(ini_file)

        for section_name in parser.sections():
            self.__dict__.update(parser.items(section_name))

config = Configuration('config.ini')
</code></pre>

<p>I access the config values like this:</p>

<pre><code>from config import config

print(config.port)
</code></pre>

<p>Any help much appreciated.</p>
",https://stackoverflow.com/questions/53847262/unit-test-for-a-config-module-that-loads-values-from-a-file,"['python', 'unit-testing', 'pytest']",1304,TRUE,0,1
unit testing Module failed to load + karma + ionic angularAngular,"<p>Trying to load controller module in unit testing karma + jasmine + ionic Angular 1.5.3.</p>

<p>Module/Controller file</p>

<pre><code>angular.module('App.View.Controllers', []).controller('ListController',
function($scope){
$scope._userName = UserService.getUserObject().maxperson;
});

describe(""ListController"", function(){
var $scope, $controller, ListController;
beforeEach(function () {
module('App.View.Controllers');
});
beforeEach(inject(function(_$rootScope_, _$controller_) {
$scope = $rootScope.$new();
$controller = _$controller_;
ListController = $controller('ListController', {$scope: $scope});
}));
it(""has a dummy controller"", function(){
expect(2+2).toEqual(4);
});
it('should be defined', function() {
expect(ListController).toBeDefined();
});
});
</code></pre>

<p>Gives me error:     </p>

<blockquote>
  <p>Error: [$injector:modulerr] Failed to instantiate module App.View.Controllers due to:
      Error: [$injector:nomod] Module 'App.View.Controllers' 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.<br>
      <a href=""http://errors.angularjs.org/1.5.3/"" rel=""nofollow noreferrer"">http://errors.angularjs.org/1.5.3/</a>$injector/nomod?p0=App.View.Controllers
          at node_modules/angular/angular.js:68:12  </p>
</blockquote>

<p>It is ionic app. Actually controller loads dependency also but for time sake I have commented it out to make a simple controller loads.  </p>

<pre><code>package.json file
{
    ""name"": ""karma-2174"",
    ""version"": ""1.0.0"",
    ""description"": """",
    ""devDependencies"": {
    ""@uirouter/angularjs"": ""^1.0.3"",
    ""angular"": ""^1.5.3"",
    ""angular-mocks"": ""^1.5.3"",
    ""jasmine-core"": ""^2.0.4"",
    ""karma"": ""^1.5.0"",
    ""karma-chrome-launcher"": ""^2.0.0"",
    ""karma-jasmine"": ""^1.1.0""
    },
    ""scripts"": {
    ""test"": ""karma start""
    },
    ""author"": """",
    ""license"": ""ISC""
}
</code></pre>
",https://stackoverflow.com/questions/49107466/unit-testing-module-failed-to-load-karma-ionic-angularangular,"['angularjs', 'unit-testing', 'ionic-framework', 'karma-runner']",252,TRUE,0,1
C++ boost test can&#39;t test operator &lt;,"<p>I am having trouble with the Boost C++ unit testing framework.  Here is
the file someclass.h</p>

<pre><code>class someclass {
   public:
      someclass(int a_x, int b_x);
      someclass();

      friend bool operator&lt;(someclass&amp; lhs, someclass&amp; rhs);
      friend ostream&amp; operator&lt;&lt;(ostream&amp; stream, const someclass&amp; sa);

   private:
      int a;
      int b;
};
</code></pre>

<p>Here is the file someclass.cpp</p>

<pre><code>#include &lt;iostream&gt;
#include &lt;ostream&gt;
#include &lt;vector&gt;
#include &lt;tuple&gt;

using std::cout;
using std::endl;
using std::vector;
using std::ostream;

#include ""someclass.h""

someclass::someclass(int a_x, int b_x)
:a(a_x), b(b_x)
{
}

//-------------------------------------------------------

someclass::someclass()
{
}

//-------------------------------------------------------

bool operator&lt;(someclass&amp; lhs, someclass&amp; rhs)
{
   return std::tie(lhs.a, lhs.b) &lt; std::tie(rhs.a, rhs.b);
}

//-------------------------------------------------------
ostream&amp; operator&lt;&lt;(ostream&amp; stream, const someclass&amp; rhs)
{
   stream &lt;&lt; ""("" &lt;&lt; rhs.a &lt;&lt; "","" &lt;&lt; rhs.b &lt;&lt; "")"";
   return stream;
}
</code></pre>

<p>Here is the program to test it:</p>

<pre><code>#define BOOST_TEST_MODULE test_someclass
#define BOOST_TEST_DYN_LINK
#include &lt;boost/test/unit_test.hpp&gt;

#include &lt;ostream&gt;

using std::ostream;

#include ""someclass.h""

BOOST_AUTO_TEST_CASE( someclass_lt )
{
   someclass sa1(1,4);
   someclass sa2(1,5);
   someclass sa3(2,3);
   someclass sa4(2,4);
   someclass sa5(2,5);

   BOOST_TEST( sa1 &lt; sa2 );
   BOOST_TEST( !(sa2 &lt; sa1) );
   BOOST_TEST( sa1 &lt; sa3 );
   BOOST_TEST( sa1 &lt; sa4 );
   BOOST_TEST( sa1 &lt; sa5 );
}
</code></pre>

<p>The file someclass.cpp compiles fine by itself, but when I try to compile the
whole thing together I get a huge set of error messages which read, in part,</p>

<pre><code>In file included from testsomeclass.cpp:9:0:
someclass.h:6:19: note: bool operator&lt;(someclass&amp;, someclass&amp;)
       friend bool operator&lt;(someclass&amp; lhs, someclass&amp; rhs);
                   ^
someclass.h:6:19: note:   no known conversion for argument 1 from ‘someclass’ to ‘someclass&amp;’
</code></pre>

<p>I have tried every way I can think of to correct this, to no avail.
I have also searched in stackoverflow.com and many other sites, to no avail.
Can someone tell me what's wrong and EXACTLY how to fix it?  Thanks.</p>

<p>Bruce</p>
",https://stackoverflow.com/questions/48119868/c-boost-test-cant-test-operator,"['c++', 'unit-testing', 'boost']",124,FALSE,0,1
Mock Stub and Moq Setup act differently ? What is the equivalent of Stub in Moq?,"<p>I realized while writing unit testing in two different projects that the behavior of setup in Moq is different than Stub in Rhino-Mocks. </p>

<p>One class uses Mock which has one of these scenarios where I stub</p>

<pre><code>for (int i=0; i&lt;ObjectAList.Count; i++)
{
     _translator.Stub(x =&gt; x.TranslateToObjectB(ObjectAList[i])).Return(ObjectBList[i]);
}
</code></pre>

<p>the above example works like a charm.</p>

<p>But when I tried to do the same thing in a different project that uses Moq, using setup, it failed. </p>

<pre><code>for (int i=0; i&lt;ObjectAList.Count; i++)
{
     _translator.SetUp(x =&gt; x.TranslateToObjectB(ObjectAList[i])).Returns(ObjectBList[i]);
}
</code></pre>

<p>Instead I had to do something like this,</p>

<pre><code>int i = 0;
foreach (var ObjectA in ObjectAList)
{
     _translator.Setup(x =&gt; x.ConvertToProcessingFilter(ObjectA)).Returns(ObjectBList[i]);
     i++;
}
</code></pre>

<p>I am just looking for a reason why stub vs setup behaved so differently. If this is the expected from setup, then what is the equivalent of stub in Moq ? </p>
",https://stackoverflow.com/questions/53754754/mock-stub-and-moq-setup-act-differently-what-is-the-equivalent-of-stub-in-moq,"['c#', 'unit-testing', 'moq', 'rhino-mocks']",279,TRUE,0,1
Run all tests with coverage not showing,"<p>We are currently learning about unit testing in IntelliJ but I am running into the issue that I am missing something.</p>

<p>Taking the following video as an example (<a href=""https://www.youtube.com/watch?v=QDFI19lj4OM"" rel=""nofollow noreferrer"">https://www.youtube.com/watch?v=QDFI19lj4OM</a>), at 5.09, you see the option ""<em>Run 'All Tests' with coverage</em>"".</p>

<p><a href=""https://i.stack.imgur.com/zs4IJ.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/zs4IJ.png"" alt=""screenshot at 05:10""></a></p>

<p>This option is missing in IntelliJ for me.</p>

<p>I've tried searching using google but I can't find the solution to this. All I get using google are links to tutorials where this option is being used.</p>

<p>I don't know if it matters but I am using Maven and JUnit 5.</p>

<p>Does anyone have an idea what could be wrong?</p>
",https://stackoverflow.com/questions/52243423/run-all-tests-with-coverage-not-showing,"['java', 'intellij-idea', 'junit', 'junit5']",3131,TRUE,0,2
How do I run a custom C unit test with Appveyor?,"<p>I'm currently writing an open source library in C (<a href=""https://github.com/Srekel/sralloc"" rel=""nofollow noreferrer"">https://github.com/Srekel/sralloc</a>) and have a simple unit test solution/project running. It uses a simple C unit testing framework and generates a unittest.exe that prints out the results and returns 1 or 0 depending on if it was successful or not.</p>

<p>My problem is that I'm not sure how to configure Appveyor to run this executable after building. The Appveyor executable is produced at <code>C:\projects\sralloc\examples\Build\x64_Debug\unittest.exe</code></p>

<p>So I tried this:</p>

<pre><code>test_script:
  - '%APPVEYOR_BUILD_FOLDER%\examples\build\%PLATFORM%_%CONFIGURATION%\unittest.exe'
</code></pre>

<p>However Appveyor says: <code>The system cannot find the path specified.</code></p>

<p>I've searched online a fair amount but haven't really found anything.</p>

<p>Here's my full appveyor.xml</p>

<pre><code>version: 1.0.{build}

image: Visual Studio 2017

configuration:
 - Debug
 - Release

build:
  parallel: true
  project: examples/sralloc.sln

test_script:
  - '%APPVEYOR_BUILD_FOLDER%\examples\build\%PLATFORM%_%CONFIGURATION%\unittest.exe'
</code></pre>
",https://stackoverflow.com/questions/48733140/how-do-i-run-a-custom-c-unit-test-with-appveyor,"['c', 'unit-testing', 'appveyor']",166,TRUE,0,1
ngxs: How to test dynamic selectors,"<p>I followed the official documentation on testing ngxs selectors (<a href=""https://ngxs.gitbook.io/ngxs/recipes/unit-testing#testing-selectors"" rel=""nofollow noreferrer"">https://ngxs.gitbook.io/ngxs/recipes/unit-testing#testing-selectors</a>), however it doesn't cover how to unittest dynamic selectors created with <code>createSelector</code>.</p>

<p>My normal selector just gets the state as an argument so I can easly test it by passing a prepared state and comparing the output.</p>

<pre><code>@Selector()
static nachweise(state: NachweisStateModel) {
  return state.nachweise;
}



//Setup state   
const state = {...};

//Compare expectations
expect(NachweisState.nachweise(state)).toEqual(...);
</code></pre>

<p>My dynamic selector looks like this: </p>

<pre><code>@Selector()
static nachweisById(id: string) {
  return createSelector([NachweisState], state =&gt; {
    return state.nachweise.find(nachweis =&gt; nachweis.id === id);
  });
}
</code></pre>

<p>The only parameter it gets is the id by which it selects, but not the state. The State is automagically passed in by specifying it as the first parameter to <code>createSelector</code> and I don't know how I should test this selector.</p>
",https://stackoverflow.com/questions/52070753/ngxs-how-to-test-dynamic-selectors,"['unit-testing', 'testing', 'selector', 'ngxs']",1301,TRUE,0,1
Testing Vue Components - Mocking State and Methods,"<p>I've been trying to get my head around unit testing Vue components, but I can't seem to quite work out how to Mock/Stub out store objects and methods that call an API async.</p>

<p>This is an example of a Vue component we have:</p>

<pre><code>import { mapState, mapGetters } from 'vuex'
import router from 'components/admin/router'

export default {
name: 'Users',
computed: {
    ...mapState('admin', [
        'users',
    ]),
    ...mapGetters({
        requestInProgress: 'requestInProgress',
    }),
},
data: function() {
    return {
        filterTerm: '',
        usersLoaded: false,
    }
},
methods: {        
    getUsers(filter) {
            this.$store.dispatch('admin/getUserList', filter)
                .then(res =&gt; {
                    this.usersLoaded = true
                })
                .catch(e =&gt; {
                    this.$toast.error({
                        title: 'Failed to retrieve data',
                        message: this.$options.filters.normaliseError(e),
                    })
                })            
    },
},
mounted() {
    this.getUsers('*')
},
</code></pre>

<p>}</p>

<p>And this is the test I want to write. I can't even get the test to run cleanly without actually trying to assert anything</p>

<pre><code>import Vue from 'vue'
import { shallowMount } from '@vue/test-utils'
import Users from 'components/admin/pages/user/users.vue'

describe('Users Vue', () =&gt; {
    it('Page Should Load', () =&gt; {
     const mockResponse = {
          data: [{
            ""id"": ""1"",
            ""emailAddress"": ""beakersoft@gmail.com"",
            ""firstName"": ""Luke"",
            ""lastName"": ""Niland"",
            ""staffNumber"": ""12345"",
            ""phoneNumber"": ""07707 999999"",
            ""active"": true
        }
    ]};

    let actions
    let store

    beforeEach(() =&gt; {
        actions = {
            'admin/getUserList': sinon.stub()                      
                  .returns(Promise.resolve(mockResponse))
        }
        store = new Vuex.Store({
            state: {},
            actions
        })
    })                   

    const wrapper = shallowMount(Users, { store })

    const h5 = wrapper.find('h5')
    expect(h5.text()).toBe('User Administration')  
  })
 })
</code></pre>

<p>The errors I tend to get back are about items being undefined, normally, in this case, <code>$store.dispatch</code> is <code>undefined</code>. I feel like I'm missing something with the mocking somewhere, or the fact that the <code>getUsers()</code> being called on the mount is tripping it up.</p>
",https://stackoverflow.com/questions/52598812/testing-vue-components-mocking-state-and-methods,"['vue.js', 'vuex', 'vue-test-utils']",4215,TRUE,5,2
How to unit test files that import VSS SDK components - cannot find VSS module,"<p>I'm trying to use <a href=""https://github.com/ALM-Rangers/Countdown-Widget-Extension"" rel=""nofollow noreferrer"">ALM-Rangers/Countdown-Widget-Extension</a> as an example to add unit testing to my own VSS SDK web extension. </p>

<p>I was able to download and run the tests, but when I try to apply this to my own project ( a fork of Microsoft/vsts-team-calendar), I get an error when I run <code>tsc ./tests/TestSpec.ts</code>:</p>

<blockquote>
  <p>src/Calendar/Utils/TestDate.ts(1,29): error TS2307: Cannot find module 'VSS/Utils/Date'.</p>
</blockquote>

<p>TestSpec.ts:</p>

<pre><code>import jasmine = require(""jasmine"");
import * as DateUtils from ""../src/Calendar/Utils/TestDate"";

describe('JavaScript addition operator', function() {
    it ('adds two numbers together', function(){
        expect(1+2).toEqual(3);
    });
});

describe('getDatesInRange', () =&gt; {
    it('gets dates in range', () =&gt; {
        expect(DateUtils.getDatesInRange(
            new Date(2018, 4, 25), 
            new Date(2018,4,26)
        ))
        .toEqual([
            new Date(2018, 4, 25), 
            new Date(2018,4,26)
        ]);
    });
});
</code></pre>

<p>TestDate.ts:</p>

<pre><code>import Utils_Date = require(""VSS/Utils/Date"");

export function getDatesInRange(startDate:Date, endDate: Date): Date[] {
    const dates = [];
    let current: Date = startDate;
    while (current.getTime() &lt;= endDate.getTime()) {
        dates.push(new Date(&lt;any&gt;current));
        current = Utils_Date.addDays(current, 1);
    }
    return dates;
}
</code></pre>

<p>webpack module.rules:</p>

<pre><code>module: {
    rules: [{ test: /\.tsx?$/, loader: ""ts-loader"" }],
},
</code></pre>

<p>tsconfig.json:</p>

<pre><code>{
    ""compilerOptions"": {
        ""allowSyntheticDefaultImports"": true,
        ""noUnusedLocals"": true,
        ""module"": ""amd"",
        ""moduleResolution"": ""node"",
        ""target"": ""es5"",
        ""outDir"": ""dist/"",
        ""rootDir"": ""src/"",
        ""lib"": [
            ""es5"",
            ""dom"",
            ""es2015.promise""
        ],
        ""importHelpers"": true,
        ""noEmitHelpers"": true,
        ""skipLibCheck"": true,
        ""types"": [
            ""vss-web-extension-sdk"",
            ""fullcalendar"",
            ""jquery""
        ]
    },
    ""include"": [
        ""src/**/*.ts""
    ]
}
</code></pre>

<p>File structure:</p>

<pre><code>root
|-- dist
|-- node_modules
|-- scripts
|-- tests
     |-- TestSpec.js
     |-- TestSpec.ts
|-- src
     |-- Calendar
            |-- Controls
                  |-- *Control.ts
            |-- Dialogs
                  |-- EditEventDialog.ts
            |-- Enhancers
                  |-- *Enhancer.ts
            |-- EventSources
                  |-- *EventSource.ts
            |-- Utils
                  |-- TestDate.ts
                  |-- Color.ts
                  |-- Date.ts
                  |-- Guid.ts
                  |-- Promise.ts
            |-- Views
                  |-- CalendarView.ts
                  |-- CalendarView.ts
            |-- Calendar.ts
            |-- CalendarServices.ts
            |-- Contracts.ts
            |-- DateRelativeToValidator.ts
            |-- EventSourceCollection.ts
            |-- Extension.ts
            |-- NamedListData.ts
|-- static
     |-- css
     |-- images
     |-- *.html
package.json
tsconfig.json
vss-extension.json
webpack.config.js
</code></pre>

<p>Here are some potentially relevant sections of vss-extension.json.  Can't say I understand this part:</p>

<pre><code>""files"": [
    {
        ""path"": ""static/images"",
        ""addressable"": true
    },
    {
        ""path"": ""static/css"",
        ""addressable"": true
    },
    {
        ""path"": ""dist"",
        ""packagePath"": ""js"",
        ""addressable"": true
    },
    {
        ""path"": ""node_modules/vss-web-extension-sdk/lib"",
        ""addressable"": true,
        ""packagePath"": ""sdk""
    },
    {
        ""path"": ""node_modules/fullcalendar/dist"",
        ""addressable"": true,
        ""packagePath"": ""dist/fullcalendar""
    },
    {
        ""path"": ""node_modules/moment"",
        ""addressable"": true,
        ""packagePath"": ""dist/moment""
    },
    {
        ""path"": ""node_modules/moment-timezone"",
        ""addressable"": true,
        ""packagePath"": ""dist/moment-timezone""
    },
    {
        ""path"": ""node_modules/jquery/dist"",
        ""addressable"": true,
        ""packagePath"": ""dist/jquery""
    },
    {
        ""path"": ""node_modules/tablesorter/dist"",
        ""addressable"": true,
        ""packagePath"": ""dist/tablesorter""
    },
    {
        ""path"": ""static/calendar.html"",
        ""addressable"": true,
        ""contentType"": ""text/html""
    },
    {
        ""path"": ""static/calendarServices.html"",
        ""addressable"": true,
        ""contentType"": ""text/html""
    },
    {
        ""path"": ""static/daysOffControls.html"",
        ""addressable"": true,
        ""contentType"": ""text/html""
    },
    {
        ""path"": ""static/freeFormControls.html"",
        ""addressable"": true,
        ""contentType"": ""text/html""
    },
    {
        ""path"": ""LICENSE.txt"",
        ""addressable"": true,
        ""contentType"": ""text/html""
    }
],
</code></pre>

<p>and more from webpack config:</p>

<pre><code> return {
        entry: {
            ""main"": ""./"" + path.relative(process.cwd(), path.join(__dirname, ""src"", ""Calendar"", ""Extension.ts"")),
            ""calendarServices"": ""./"" + path.relative(process.cwd(), path.join(__dirname, ""src"", ""Calendar"", ""CalendarServices.ts"")),
            ""freeformEventControl"":  ""./"" + path.relative(process.cwd(), path.join(__dirname, ""src"", ""Calendar"", ""Controls"", ""FreeFormEventControl.ts"")),
            ""capacityEventControl"":  ""./"" + path.relative(process.cwd(), path.join(__dirname, ""src"", ""Calendar"", ""Controls"", ""CapacityEventControl.ts""))
        },
        output: {
            filename: path.relative(process.cwd(), path.join(__dirname, ""dist"", ""[name].js"")),
            libraryTarget: ""amd"",
        },
</code></pre>
",https://stackoverflow.com/questions/50241143/how-to-unit-test-files-that-import-vss-sdk-components-cannot-find-vss-module,"['unit-testing', 'typescript', 'azure-devops', 'vssdk']",177,FALSE,0,0
React unit test with Jest - issue on simulating localStorage,"<p>I've an issue on unit testing a simple component (even more simplified here) :</p>

<pre><code>import React, { Component } from 'react';
import Logout from '../auth/Logout';
import { logoutUser } from '../../actions/auth';

export default class Navbar extends Component {

  render() {
    const { dispatch, isAuthenticated } = this.props;

    if (isAuthenticated) {
      logStatus = &lt;Logout onLogoutClick={() =&gt; dispatch(logoutUser())} /&gt;;
    } else {
      logStatus = (
        &lt;Link to=""/login/""&gt;
          &lt;Button&gt;Login&lt;/Button&gt;
        &lt;/Link&gt;
      );
    }

    return (
      &lt;AppBar&gt;        
        {logStatus}
      &lt;/AppBar&gt;
    );
  }
}
</code></pre>

<p>in <code>import { logoutUser } from '../../actions/auth';</code><br>
I have a function removeItem on <code>localStorage</code>. I won't be using it for my test but that's where I have an error.</p>

<p>My test is : </p>

<pre><code>test('Navbar test series', () =&gt; {
  //Enzyme testing
  it('show the login button', () =&gt; {
    const wrapper = shallow(&lt;Navbar isAuthenticated={true} /&gt;);
    expect(wrapper.find(Login)).to.have.length(1);
  });
});
</code></pre>

<p>I got : </p>

<pre><code>ReferenceError: localStorage is not defined      
      at Object.&lt;anonymous&gt; (src/axios/axios.js:8:15) [I don't know why this is here...]
      at Object.&lt;anonymous&gt; (src/actions/auth.js:89:38) [my logoutUser using localStorage is here ]
      at Object.&lt;anonymous&gt; (src/components/UI/Navbar.js:3:13)
      at Object.&lt;anonymous&gt; (src/components/UI/Navbar.test.js:2:15)
</code></pre>

<p>Doing something like suggested here <a href=""https://stackoverflow.com/questions/32911630"">How do I deal with localStorage in jest tests?</a>  : </p>

<pre><code>var localStorageMock = (function () { [...]})();
Object.defineProperty(window, 'localStorage', { value: localStorageMock });
</code></pre>

<p>is not helping.</p>

<p>What I don't get is that I'm not even calling <code>dispatch(logoutUser())</code> so why trying to access localStorage ?? Is the issue due to redux through dispatch ? </p>

<p>Thanks a lot for your help !</p>

<p>EDIT1 : 
Logout component : </p>

<pre><code>import React from 'react';
import Button from '@material-ui/core/Button';

const Logout = props =&gt; (
  &lt;Button onClick={() =&gt; props.onLogoutClick()}     color=""secondary""&gt;LOGOUT&lt;/Button&gt;
);

export default Logout;
</code></pre>

<p>And code from actions/auth.js and logoutUser() :</p>

<pre><code>export function logoutUser() {
  return dispatch =&gt; {
    dispatch(requestLogout());
    localStorage.removeItem('token');
    dispatch(receiveLogout());
  };
}
</code></pre>
",https://stackoverflow.com/questions/51439407/react-unit-test-with-jest-issue-on-simulating-localstorage,"['reactjs', 'redux', 'jestjs', 'enzyme']",2020,TRUE,0,3
Not able to get state of component,"<p>I have a component with a checkbox and text field when the user clicks the checkbox I am showing the text field which is hidden by default. To achieve this functionality I am using state of this component, as user checks the checkbox I am calling onChangeHandler and setting the state to showAccountNumberField text field and when user unchecks the checkbox hiding the text field. But when I am trying to test this component by doing </p>

<p><code>wrapper.setSatate({showAccountNumberField: true})</code> </p>

<p>I am getting error that state can only be accessed on class component. I am using React 16 and Jest for unit testing. Any help is appreciated.</p>
",https://stackoverflow.com/questions/51086993/not-able-to-get-state-of-component,"['reactjs', 'jestjs', 'enzyme']",39,FALSE,0,0
Spring/MongoDB/Junit: Unit test with Fongo is giving the Null Pointer Exception,"<p>I am fairly new to unit testing and trying to test a simple function that returns a query. In my unit test, I am getting the <code>NullPointerException</code> after calling the method. I assume <code>mongoOperations</code> is <code>null</code>, and guessing that is the reason why it is returning NPE. I am using fongo to mock the mongoDB and I configured the spring context in <code>testConfigurationContext.xml</code> file. </p>

<p>This is the class I want to test:</p>

<pre><code>@Repository
public class DataVersionDaoMongo extends MongoBaseDao&lt;DataVersion&gt; implements DataVersionDao {

public DataVersionDaoMongo() {
    initType();
}

@Override
public DataVersion 

findByDBAndCollection(String dbName, String collectionName) {
//below is the line 27 on error console
return mongoOperations.findOne(Query.query(Criteria.where(""dbName"").is(dbName).and(""collectionName"").is(collectionName)), DataVersion.class);
    }
}
</code></pre>

<p>This is my unit test:</p>

<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(""classpath:/testApplicationContext.xml"")
public class DataVersionDaoMongoTest {
    private DataVersionDaoMongo dataVersionDaoMongo = new DataVersionDaoMongo();
    private MongoOperations mongoOperations;
    private DataVersion dataVersion;

    @Rule
    public FongoRule fongoRule = new FongoRule();

    @Test
    public void findByDBAndCollection() {
        String dbname = ""mydb"";
        String collectionName = ""mycollection"";
        DB db = fongoRule.getDB(dbname);
        DBCollection collection = db.getCollection(collectionName);
        Mongo mongo = fongoRule.getMongo();
        collection.insert(new BasicDBObject(""name"", ""randomName""));
//below is the line 63 on error console
        assertThat(dataVersionDaoMongo.findByDBAndCollection(dbname, collectionName)).isNotNull();
    }
}
</code></pre>

<p>This is the applicationContext file:</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:mongo=""http://www.springframework.org/schema/data/mongo""
       xsi:schemaLocation=""http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd""&gt;


    &lt;bean name=""fongo"" class=""com.github.fakemongo.Fongo""&gt;
        &lt;constructor-arg value=""InMemoryMongo"" /&gt;
    &lt;/bean&gt;
    &lt;bean id=""mongo"" factory-bean=""fongo"" factory-method=""getMongo"" /&gt;

    &lt;mongo:db-factory id=""mongoDbFactory"" mongo-ref=""mongo"" /&gt;

    &lt;!-- localhost settings for mongo --&gt;
    &lt;!--&lt;mongo:db-factory id=""mongoDbFactory"" /&gt;--&gt;

    &lt;bean id=""mongoTemplate"" class=""org.springframework.data.mongodb.core.MongoTemplate""&gt;
        &lt;constructor-arg ref=""mongoDbFactory""/&gt;
    &lt;/bean&gt;

&lt;/beans&gt;
</code></pre>

<p>This is the error on console:</p>

<pre><code>java.lang.NullPointerException
    at com.absolute.common.repository.mongodb.springdata.DataVersionDaoMongo.findByDBAndCollection(DataVersionDaoMongo.java:27)
    at com.absolute.common.repository.mongodb.springdata.DataVersionDaoMongoTest.findByDBAndCollection(DataVersionDaoMongoTest.java:63)
    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.junit.rules.ExternalResource$1.evaluate(ExternalResource.java:48)
    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.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)
</code></pre>

<p>I am guessing I am missing something. Any help would be greatly appreciated!</p>
",https://stackoverflow.com/questions/53136535/spring-mongodb-junit-unit-test-with-fongo-is-giving-the-null-pointer-exception,"['spring', 'spring-mvc', 'junit', 'nullpointerexception', 'fongo']",1390,TRUE,0,2
How to compare IReadOnlyCollection&lt;bool&gt; to List&lt;bool&gt; for equality by value?,"<p>I am trying to write a unit test to compare actual results to expected results, where the class I am testing gives me a IReadOnlyCollection and my expected results are List.</p>

<p>I read over the this answer about comparing Lists using CollectionAssert at <a href=""https://stackoverflow.com/questions/11055632/how-to-compare-lists-in-unit-testing"">How to compare Lists in Unit Testing</a>, however when I attempt to do so, I get compiler error ""cannot convert from 'System.Collections.Generic.IReadOnlyCollection' to 'System.Collections.ICollection'""</p>

<p>Here is my test method:</p>

<pre><code>    [TestMethod]
    public void EveningMotion()
    {
        IDateTimeProvider dateTimeProvider = new MockDateTimeProvider(new DateTime(2018, 1, 1, 20, 0, 0));
        ILightHardwareInterface frontyardLights = new MockLightHardwareInterface();
        MockLightHardwareInterface backyardLights = new MockLightHardwareInterface();

        LightController controller = new LightController(dateTimeProvider, frontyardLights, backyardLights);
        controller.ActuateLights(true);

        IReadOnlyCollection&lt;bool&gt; actualResult = backyardLights.GetRecording();
        List&lt;bool&gt; expectedResult = new List&lt;bool&gt;
        {
            true
        };

        CollectionAssert.AreEqual(expectedResult, actualResult);
    }
</code></pre>

<p>What is one to do? I kind of want to keep the expected and actual results comparison rather than iterating through both element by element, if possible.</p>
",https://stackoverflow.com/questions/48068777/how-to-compare-ireadonlycollectionbool-to-listbool-for-equality-by-value,['c#'],1055,TRUE,-2,1
How can I unit test async database calls without changing the route?,"<p>So I have a route with a database call in a separate file:</p>

<pre><code>module.exports = (req, res) =&gt; {
  const sql = `SELECT Topic FROM surveys WHERE ID=""${req.params.id}""`;
  model.connection.query(sql, (err, result) =&gt; {
    if (err) res.status(500).send(err);
    res.send(result);
  });
};
</code></pre>

<p>In my test file, I create fake req and res objects to test different inputs:</p>

<pre><code>const req = {
  body: {},
  params: {
  id: '',
  }
};

const res = {
  message: '',
  stat: 200,
  send(arg) {
     this.message = arg;
  },
  status(number) {
     this.stat = number;
     return this;
  }
};
</code></pre>

<p>And call it in every test:</p>

<pre><code> it('Should return status 200 if parameter is a number string', () =&gt; {
   req.params.id = '1';
   getTopic(req, res);
   chai.expect(res.stat).to.equal(200);
 });
</code></pre>

<p>My question is, how can I test it asynchronously, without <strong>affecting my route</strong>?
I've seen Mocha documentation explaining this, but they require a callback in a function.</p>

<pre><code>it('Should return status 200 if parameter is a number string', (done) =&gt; {
   req.params.id = '1';
   getTopic(req, res); // Cannot give any callback
   chai.expect(res.stat).to.equal(200);
   done(); //Doesn't work
});
</code></pre>

<p>I also tried using <code>async/await</code>, but it didn't work (I lack knowledge of how to use it, maybe that's why)</p>

<pre><code>it('Should return status 200 if parameter is a number string', async () =&gt; {
   req.params.id = '1';
   await getTopic(req, res);
   chai.expect(res.stat).to.equal(200);
});
</code></pre>

<p>And I've seen this question, and didn't help at all: <a href=""https://stackoverflow.com/questions/27721082/unit-testing-express-route-with-async-callback"">unit testing express route with async callback</a></p>
",https://stackoverflow.com/questions/53343282/how-can-i-unit-test-async-database-calls-without-changing-the-route,"['node.js', 'unit-testing', 'routes', 'mocha.js']",290,FALSE,0,0
Is there a type of logic/flow errors that cannot be discovered by unit tests?,"<p>Assuming I have contracts defined and clear requirements (covering input ranges, boundary values etc.), and unit tests validating all those conditions, can there still be integration errors when I put those units together? I do not consider external services now.
I have seen the following as an example of integration error but I believe this is just a missing test at unit level:</p>

<pre><code>class Engine
{
   int RPM;

   void SetRPMtoZero()
   {
      RPM=0;
   }
}

class Display
{
  CalculateAverage(Engine e)
  {
    if (e.IsRunning)
    {
      int X=smth/e.RPM;  //could be division by 0
    }
  }
}

class IntegratingClass
{
  Engine e
  Display d..

  ...

  e.SetRPMtoZero();
  d.CalculateAverage(e);

  //this sequence would lead to the division by zero

}
</code></pre>

<p>I do not think this shows an integration error - the CalculateAverage simply lacks the check for RPM!=0.</p>

<p>Is there actually a type of logical errors (or control flow) that cannot by discovered by unit testing? </p>
",https://stackoverflow.com/questions/50041812/is-there-a-type-of-logic-flow-errors-that-cannot-be-discovered-by-unit-tests,"['unit-testing', 'language-agnostic', 'defects']",95,TRUE,0,2
Diff between DebugElement and DOM element,"<p>In angular unit testing using jasmine, we can test the view (html content) in two ways.</p>
<ol>
<li><p>Getting the elements from DebugElement</p>
<p><code>fixture.debugElement.queryAll(By.css('.tableData.billStatus.text-center'))</code></p>
</li>
<li><p>Getting the elements from DOM.</p>
<p><code>fixture.debugElement.nativeElement.querySelectorAll('.tableData.billStatus.text-center')</code></p>
</li>
</ol>
<p>My question is not related to <code>queryAll</code> vs <code>querySelectorAll</code>. It is <code>DOM</code> vs <code>DebugElement</code>. Because when I use either of them, they give me the correct result most of the time.</p>
<p>This question has some relation to this <a href=""https://github.com/angular/angular/issues/13066#issuecomment-395155562"" rel=""nofollow noreferrer"">issue</a></p>
<p>They give a work around to look through <code>DOM</code> elements as opposed to <code>DebugElement</code> as a work around. So what makes these two differ from each other?</p>
<p>I have looked through several posts for the difference, before making this question. But I did not find anything appropriate to this.</p>
",https://stackoverflow.com/questions/50736070/diff-between-debugelement-and-dom-element,"['javascript', 'angular', 'dom', 'jasmine', 'karma-jasmine']",1494,FALSE,5,2
xUnit.net Class Fixture needs name of test class about to run,"<p>I have a project where multiple test classes share a base class fixture.  </p>

<p>As expected, the fixture's constructor runs before any test in the test class is run.</p>

<p>Is there a way for this class fixture's constructor to know the name of the test class that is about to run?</p>

<p>Background: My project is not doing unit testing, but rather I'm using xUnit.net to run an alternate type of testing.  All the classes and tests will run in order, so a class is guaranteed to run completely before another class tries to run.</p>

<p>Here is an example of what I'd like to be able to do:</p>

<pre class=""lang-cs prettyprint-override""><code>using Xunit;
using Xunit.Abstractions;

namespace TestingProject
{
    // In my project, the classes are guaranteed to run in order, one after the other.  Tests won't randomly execute between classes.
    // This fixture is used by multiple test classes.  It handles logging test class starts and stops to the db.
    public class SharedTestingClassFixture : IDisposable
    {
        // This will run at the start of every testing class.
        public SharedTestingClassFixture()
        {
            // Need to get name of class that is about to execute, i.e. ""TestingClassName""
            var nameOfTestingClass = """";

            // Log name of class that is about to start to the db BEFORE any tests run.
            var logMessage = $""{nameOfTestingClass} class starting"";
        }

        // This will run at the end of every testing class.
        public void Dispose()
        {
            // Log class ending to db after all tests in this class have finished.
        }
    }

    public class TestingClassName : TestClassBase, IDisposable, IClassFixture&lt;SharedTestingClassFixture&gt;
    {
        // This will run before each individual test.
        public TestingClassName(ITestOutputHelper testOutputHelper) : base(testOutputHelper)
        {
            // At this point, I need to already have written the class name to the db; BEFORE this constructor is called.
            // The TestClassBase (not shown) constructor then extracts the test name from testOutputHelper and logs to db.
        }

        // This will run after each individual test.
        public void Dispose()
        {

        }

        [Fact]
        public void Test1()
        {
            // Testing code here
        }

        [Fact]
        public void Test2()
        {
            // Testing code here
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/49817569/xunit-net-class-fixture-needs-name-of-test-class-about-to-run,"['c#', 'xunit.net']",801,FALSE,5,0
How to unit test Controller and mock @InjectModel in the Service constructor,"<p>I am getting issues while unit testing my controller and getting an error &quot;Nest can't resolve dependencies of my service&quot;.</p>
<p>For maximum coverage I wanted to unit test controller and respective services and would like to mock external dependencies like mongoose connection. For the same I already tried suggestions mentioned in the below link but didn't find any luck with that:</p>
<p><a href=""https://github.com/nestjs/nest/issues/194#issuecomment-342219043"" rel=""noreferrer"">https://github.com/nestjs/nest/issues/194#issuecomment-342219043</a></p>
<p>Please find my code below:</p>
<pre><code>export const deviceProviders = [
    {
        provide: 'devices',
        useFactory: (connection: Connection) =&gt; connection.model('devices', DeviceSchema),
        inject: ['DbConnectionToken'],
    },
];


export class DeviceService extends BaseService {
    constructor(@InjectModel('devices') private readonly _deviceModel: Model&lt;Device&gt;) {
        super();
    }

    async getDevices(group): Promise&lt;any&gt; {
        try {
            return await this._deviceModel.find({ Group: group }).exec();
        } catch (error) {
            return Promise.reject(error);
        }
    }
}


@Controller()
export class DeviceController {
    constructor(private readonly deviceService: DeviceService) {
    }

   @Get(':group')
   async getDevices(@Res() response, @Param('group') group): Promise&lt;any&gt; {
        try {
            const result = await this.deviceService.getDevices(group);
            return response.send(result);
        }
        catch (err) {
            return response.status(422).send(err);
        }
    }
}


@Module({
    imports: [MongooseModule.forFeature([{ name: 'devices', schema: DeviceSchema }])],
    controllers: [DeviceController],
    components: [DeviceService, ...deviceProviders],
})
export class DeviceModule { }
</code></pre>
<p>Unit test:</p>
<pre><code>describe('DeviceController', () =&gt; {
    let deviceController: DeviceController;
    let deviceService: DeviceService;

    const response = {
        send: (body?: any) =&gt; { },
        status: (code: number) =&gt; response,
    };

    beforeEach(async () =&gt; {
        const module = await Test.createTestingModule({
            controllers: [DeviceController],
            components: [DeviceService, ...deviceProviders],
        }).compile();

        deviceService = module.get&lt;DeviceService&gt;(DeviceService);
        deviceController = module.get&lt;DeviceController&gt;(DeviceController);
    });

    describe('getDevices()', () =&gt; {
        it('should return an array of devices', async () =&gt; {
            const result = [{
                Group: 'group_abc',
                DeviceId: 'device_abc',
            },
            {
                Group: 'group_xyz',
                DeviceId: 'device_xyz',
            }];
            jest.spyOn(deviceService, 'getDevices').mockImplementation(() =&gt; result);

            expect(await deviceController.getDevices(response, null)).toBe(result);
        });
    });
});
</code></pre>
<p>When I am running my test case above, I am getting two errors:</p>
<blockquote>
<p>Nest can't resolve dependencies of the DeviceService (?). Please make sure that the argument at index [0] is available in the current context.</p>
<p>Cannot spyOn on a primitive value; undefined given</p>
</blockquote>
",https://stackoverflow.com/questions/52878055/how-to-unit-test-controller-and-mock-injectmodel-in-the-service-constructor,"['node.js', 'unit-testing', 'jestjs', 'nestjs']",8978,TRUE,10,3
vue unit test with jest,"<p>I was using jest for my web-app unit testing,but got an tough case.
I import a component in a test.spec.js file , this component imports a http request function from another file , this http request function use the var I defined in the vuex state,and this state data use the window object, which cause the test file error.Here's some codes.<br></p>

<p><strong>test.spec.js:</strong> imports a component called Info.vue</p>

<pre><code>import Info from '@/pages/user/Info.vue'
</code></pre>

<p><strong>Info.vue:</strong> imports a http request function <code>requestData</code> from <code>get-api-data.js</code></p>

<pre><code>import { requestData } from '@/service/get-api-data'
</code></pre>

<p><strong>get-api-data.js:</strong> imports the store(vuex) data
<code>
    import store from '@/store'
</code></p>

<p><strong>store</strong> have those vars which involve the window object:</p>

<pre><code>env: {
    apiUrl: window._env.apiUrl,
    name: window._env.user,
    password: window._env.apiKey
},
</code></pre>

<p>and the test suite fails to run.
here's the error:<br>
<a href=""https://i.stack.imgur.com/1b55Z.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/1b55Z.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/51742021/vue-unit-test-with-jest,"['vue.js', 'jestjs', 'vue-test-utils']",311,FALSE,0,0
How to give a timestamp value as an argument in java?,"<p>I am learning about unit testing and I want to write a test method for a method which converts a string to timestamp. The return type of the method is Timestamp and the parameter is String. I know that the function returns the correct value when I debug it. For example if the input is <code>""07.10.2018 08:45:00""</code>, then the value returned should be <code>2018-10-07 08:45:00.0</code> (of type timestamp). How do I pass this value to assertEquals in test method? What is the correct format of passing a Timestamp value to a function? </p>

<p>Or is there any other way for testing it?</p>

<pre><code>public void test() {
        IDManager  test = new IDManager();

        Timestamp output = test.convertStringToTimestamp(""07.10.2018 08:45:00"");
        //assertEquals(2018-10-07 08:45:00.0,output );
    }
</code></pre>
",https://stackoverflow.com/questions/52665879/how-to-give-a-timestamp-value-as-an-argument-in-java,"['java', 'unit-testing', 'timestamp', 'junit4']",4247,TRUE,0,2
Modify method logic MOQ,"<p>I am new to unit testing so my questions might seem basic, apologies for that.</p>

<p>I am trying to figure out if there is such API in MOQ that can help me to modify a method logic.
I mean,
When calling . I want to increase lets say my ""count"" variable by 1 and then call the method or do something else, doesn't really matter.</p>

<p>There is no code yet, this is a principle question. Could not find it in the MOQ Documentation on GitHub.</p>

<p>Hope I was clear and you can help me with that.</p>

<p>Thank you!</p>
",https://stackoverflow.com/questions/53729084/modify-method-logic-moq,"['c#', 'unit-testing', 'moq']",394,TRUE,-1,1
How to unit test a class with multiple boolean fields,"<p>Sorry if this is a dumb question. I'd like to unit test the following class (there's more to the class but I stripped it down to illustrate my question).</p>

<p>The class consists of multiple boolean fields that get assigned in the constructor.</p>

<p>When I'm unit testing how can I test the parameters are assigned to the correct class field e.g. ans1 -> mIsOption1Ans ?</p>

<p>For example if I assert that all the class fields are ""true"" this will not identify if another developer has accidentally swapped the assignment in the constructor and assigned a parameter to the wrong class field. I'd like to test that ""ans1"" always gets assigned to ""mIsOption1Ans"", etc, etc</p>

<pre><code>public class MultipleChoiceQuizAnswer {
   private Boolean mIsOption1Ans,mIsOption2Ans,mIsOption3Ans,mIsOption4Ans;

   public QuizAnswer (Boolean ans1,Boolean ans2, Boolean ans3,Boolean ans4) {
         mIsOption1Ans = ans1;
         mIsOption2Ans = ans2;
         mIsOption3Ans = ans3;
         mIsOption4Ans = ans4;
    }
}
</code></pre>
",https://stackoverflow.com/questions/49535686/how-to-unit-test-a-class-with-multiple-boolean-fields,"['java', 'junit4']",1315,TRUE,4,2
Test navigation guard &#39;beforeRouteLeave&#39; on vue component,"<p>I am currently stuck on unit testing the routing behavior of a vue component with jest. When leaving the component, the 'beforeRouteLeave' navigation guard of Vue-router runs some logic. This guard gets called in my application running in production, but won't gets called when I try to test it.</p>

<p>I use jest as a testing framework and vue-test-utils to mount my component and set up a local Vue instance with vue-router. </p>

<p>Here you can find a minimal working example (test in 'src/components/HelloWorld.spec'):</p>

<p><a href=""https://codesandbox.io/s/72536ojvp6?module=%2Fsrc%2Fcomponents%2FHelloWorld.spec.js"" rel=""noreferrer"">https://codesandbox.io/s/72536ojvp6?module=%2Fsrc%2Fcomponents%2FHelloWorld.spec.js</a></p>

<p>Why isn't the router hook called and how can I make it work?
Thanks in advance!</p>
",https://stackoverflow.com/questions/51380878/test-navigation-guard-beforerouteleave-on-vue-component,"['javascript', 'vue.js', 'jestjs', 'vue-router', 'vue-test-utils']",2913,FALSE,9,1
Mocking a SignInManager,"<p>New to unit testing with Moq and xUnit. I am trying to mock a <code>SignInManager</code> that is used in a controller constructor to build a unit test. The documentation that I can find for the <code>SignInManager</code> constructor says it accepts a <code>UserManager</code> and <code>AuthenticationManager</code> object: <a href=""https://msdn.microsoft.com/en-us/library/mt173769(v=vs.108).aspx#M:Microsoft.AspNet.Identity.Owin.SignInManager"" rel=""noreferrer"">https://msdn.microsoft.com/en-us/library/mt173769(v=vs.108).aspx#M:Microsoft.AspNet.Identity.Owin.SignInManager</a>`2.</p>

<p>When I try to mock the controller, I get an error saying it was unable to instantiate a proxy of the <code>SignInManager</code> and <code>AuthenticationManager</code> classes.</p>

<p>Error: </p>

<blockquote>
  <p>""Message:
  Castle.DynamicProxy.InvalidProxyConstructorArgumentsException : Can
  not instantiate proxy of class:
  Microsoft.AspNetCore.Identity.SignInManager1[[Models.AppUser,
  , Version=1.0.0.0, Culture=neutral,
  PublicKeyToken=null]]. Could not find a constructor that would match
  given arguments: Castle.Proxies.UserManager`1Proxy
  Castle.Proxies.AuthenticationManagerProxy""</p>
</blockquote>

<p>The unit test:</p>

<pre><code>public void Can_Send_Password_Reset_Email()
{
    //Arrange
    //create mock services
    Mock&lt;IEmailService&gt; mockEmailService = new Mock&lt;IEmailService&gt;();
    Mock&lt;ILessonRepository&gt; mockRepo = new Mock&lt;ILessonRepository&gt;();
    Mock&lt;UserManager&lt;AppUser&gt;&gt; mockUsrMgr = GetMockUserManager();
    var mockSignInMgr = GetMockSignInManager();
    Mock&lt;UserValidator&lt;AppUser&gt;&gt; mockUsrVal = new Mock&lt;UserValidator&lt;AppUser&gt;&gt;();
    Mock&lt;PasswordValidator&lt;AppUser&gt;&gt; mockPwdVal = new Mock&lt;PasswordValidator&lt;AppUser&gt;&gt;();
    Mock&lt;PasswordHasher&lt;AppUser&gt;&gt; mockPwdHshr = new Mock&lt;PasswordHasher&lt;AppUser&gt;&gt;();
    Mock&lt;ForgotPasswordModel&gt; model = new Mock&lt;ForgotPasswordModel&gt;();
    model.Object.Email = ""joe@example.com"";

    var user = new AppUser();
    var token = mockUsrMgr.Object.GeneratePasswordResetTokenAsync(user).Result;

    //create mock temporary data, needed for controller message
    Mock&lt;ITempDataDictionary&gt; tempData = new Mock&lt;ITempDataDictionary&gt;();
    //create the controller
    //ERROR ON THIS LINE
    AccountController controller = new AccountController(mockUsrMgr.Object, mockSignInMgr.Object, mockUsrVal.Object, mockPwdVal.Object, mockPwdHshr.Object, mockEmailService.Object)
    {
        TempData = tempData.Object
    };

    //Act
    //the controller should call the email action method
    controller.PasswordResetEmail(model.Object);

    //Assert
    //verify that the email service method was called one time
    mockEmailService.Verify(m =&gt; m.PasswordResetMessage(user, ""Test Email""), Times.Once());
}
</code></pre>

<p>The SignInManager mocking function:</p>

<pre><code>//create a mock SignInManager class
private Mock&lt;SignInManager&lt;AppUser&gt;&gt; GetMockSignInManager()
{
    var mockUsrMgr = GetMockUserManager();
    var mockAuthMgr = new Mock&lt;AuthenticationManager&gt;();
    return new Mock&lt;SignInManager&lt;AppUser&gt;&gt;(mockUsrMgr.Object, mockAuthMgr.Object);
}
</code></pre>

<p>The <code>GetMockUserManager()</code> works fine in other unit tests and doesn't appear to be the issue.</p>
",https://stackoverflow.com/questions/48189741/mocking-a-signinmanager,"['c#', 'asp.net', 'unit-testing', 'asp.net-core', 'moq']",11388,TRUE,13,7
Unit tests slow execution on build server,"<p>I have a .NET solution that contains some Service Fabric library projects (.NET Standard 2.0) that are published as nuget packages. The unit-test projects in the solution (.NET Core 2.0) are using xUnit.</p>

<p>I noticed the tests are taking too much time when running on the build server, <strong>comparing to previous builds</strong>. </p>

<p>I tried running the tests in my local machine using Reshaper/Visual Studio or a powershell script and it takes less than 5 minutes:</p>

<pre><code>$stopwatch = [system.diagnostics.stopwatch]::StartNew()

Get-ChildItem -recurse *tests.csproj | % { 
    dotnet test $_.FullName --no-build --no-restore;
}

$stopwatch.Stop()
Write-Host $stopwatch.Elapsed
</code></pre>

<p>But in Azure Devops the unit-testing task took more than 27 minutes to finish!!!</p>

<p>This is the Build pipeline/unit test task:</p>

<p><a href=""https://i.stack.imgur.com/p6BDQ.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/p6BDQ.png"" alt=""Build pipeline tasks""></a></p>

<p>Any idea on what is going on?</p>
",https://stackoverflow.com/questions/53779195/unit-tests-slow-execution-on-build-server,"['unit-testing', '.net-core', 'azure-devops', 'azure-service-fabric', 'xunit']",2419,TRUE,3,1
How to use testthat to test a package calling usethis::use_template,"<p>I'm trying to use <code>usethis::use_template</code> in a function inside an R package and I'm running into issues when unit testing because the templates I put in my package's <code>inst/templates</code> directory are not found when testing with <strong>testthat</strong> even though they are found just fine during interactive use. I assume this 
is in some way related to use of <code>load_all</code> when the package is being loaded for testing? I looked at <strong>usethis</strong>'s unit tests and tried to copy some of the logic but it's pretty involved and I couldn't quite figure out what I need to do when testing so that I can test a function that calls <code>use_template</code>. Thanks in advance for any tips.  </p>
",https://stackoverflow.com/questions/49801951/how-to-use-testthat-to-test-a-package-calling-usethisuse-template,"['r', 'devtools', 'testthat']",140,FALSE,3,0
Unit testing using Jasmine: Unable to query input element in Shadow DOM of Polymer 2 component inside Angular page,"<p>I am working with some Polymer 2 components which implement ShadowDOM v1 spec and I need to select elements (e.g. input) inside their shadowRoots to run unit tests and few integration tests using Jasmine.</p>

<p>Expected Behavior:</p>

<p>We should be able to access Shadow DOM elements using Jasmine selectors.</p>

<p>var allInputs = fixture.debugElement.queryAll(By.css('input')); // does not give the input elements inside shadow DOM.</p>

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

<pre><code>import { TestBed, ComponentFixture, async } from '@angular/core/testing';

import { AppComponent } from './app.component';

import { NgModule, CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA} from '@angular/core';

import { FormsModule } from '@angular/forms';

import { By } from '@angular/platform-browser';

describe('AppComponent', () =&gt; 
{


let component: AppComponent;

let fixture: ComponentFixture&lt;AppComponent&gt;;



beforeEach(async(() =&gt; 
{

    TestBed.configureTestingModule({

        declarations: [
    AppComponent
  ],

        imports: [
    FormsModule
  ],

        schemas: [CUSTOM_ELEMENTS_SCHEMA]
}).compileComponents();

    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;

}));

  it('should have default value set for first name and last name', () =&gt; 
  {
    fixture.detectChanges();
    var allInputs =  fixture.debugElement.queryAll(By.css('input'));
    var firstNameInput = allInputs[0].nativeElement; // Unable to retrieve the input element from the polymer web component.

    var lastNameInput = allInputs[1].nativeElement; // Unable to retrieve the input element from the polymer web component.
    expect(firstNameInput.value).toBe('');
    expect(lastNameInput.value).toBe('');

  });
});
</code></pre>

<p>What is the best way I can test the Polymer Web Components inside Angular page?
Or whether we have a mechanism to mock web components while unit testing Angular component?</p>

<p>My environment:</p>

<p>Angular CLI: 1.6.4
Node: 6.10.0
Angular: 5.2.0</p>

<p>""devDependencies"": {
""karma-jasmine"": ""^0.3.6"",
""jasmine"": ""^2.4.1"",
""jasmine-core"": ""^2.2.0""
}</p>
",https://stackoverflow.com/questions/48537466/unit-testing-using-jasmine-unable-to-query-input-element-in-shadow-dom-of-polym,"['angular', 'jasmine', 'css-selectors', 'polymer']",797,FALSE,3,0
getting Error: Expected spy onSubmit to have been called,"<p>I am new in angular and trying to write unit testing in angular 5 using karma-jasmine.</p>

<p>i have a login page which has 2 parameter username and password, and onSubmit() is function which is used to call api to authenticate user. check below file for login component.</p>

<p><strong>login.component.ts</strong></p>

<pre><code>@Component({

  selector: 'app-login',

  templateUrl: './login.component.html',

  styleUrls: ['./login.component.scss']

})

export class LoginComponent implements OnInit {

  myform: FormGroup;

  username: FormControl;

  password: FormControl;

  errMsg: string;

  loginErr: boolean;


  model: any = {};

  constructor(

    private http: Http,

    private router: Router

  ) {
  }

  ngOnInit() {

    this.createFormControls();

    this.createForm();
  }


  createFormControls() {

    this.username = new FormControl('', Validators.required);

    this.password = new FormControl('', [

      Validators.required,

      Validators.minLength(6)

    ]);

  }

  createForm() {

    this.myform = new FormGroup({

      username: this.username,

      password: this.password

    });
    enter code here

  }

  onSubmit() {
    this.errMsg = """";
    if (this.myform.valid) {

      var data = {
        'Username': this.username.value,
        'Password': this.password.value
      };

      var options = {
        type: ""POST"",
        url: GlobalVariable.BASE_API_URL + ""authentication/authenticate-user"",
        content: ""application/json; charset=utf-8"",
        contentType: 'application/json',
        async: false,
        processing: true,
        crossDomain: true,
        xhrFields: { withCredentials: true },
        body: JSON.stringify(data),
      };

      let headers = new Headers({ 'Content-Type': 'application/json' });

      this.http.post(options.url, options.body, { headers: headers }).subscribe((data) =&gt; {

        console.log(JSON.parse(data['_body']));

      }, (err) =&gt; {
        console.log(data['_body']);
        this.errMsg = ""Invalid Login Attempt."";
      }, () =&gt; {
        console.log(""All Good With The Data"")
      });
    }
    else
    {

     }
  }

}
</code></pre>

<p>Now i am trying to write unit test for above file, check below spec.ts file for sample code</p>

<p>****login.component.spec.ts****</p>

<pre><code>describe('LoginComponent', () =&gt; {

  let component//: LoginComponent;

  let fixture//: ComponentFixture&lt;LoginComponent&gt;;

   beforeEach(async(() =&gt; {

      TestBed.configureTestingModule({
      declarations: [ LoginComponent],
      imports: [ReactiveFormsModule, HttpModule, AppRoutingModule, RouterModule, FormsModule],
      providers: [
        {provide: Globals, useValue: GlobalVariable.BASE_API_URL},
        {provide: APP_BASE_HREF, useValue: '/'}
      ],
    })
    .compileComponents();
  }));

  beforeEach(() =&gt; {

    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create login component', () =&gt; {

    spyOn(component,'onSubmit').and.callThrough();
    component.username = 'username';
    component.password = '12345678';
    expect(component.onSubmit).toHaveBeenCalled();
  });
});
</code></pre>

<p>when I have run this unit test it shows error as image attached, please suggest me what mistake is in my code. how I can write a unit test to authenticate user by passing username and password and call the onSubmit function.</p>

<p><a href=""https://i.stack.imgur.com/spOY7.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/spOY7.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/48745524/getting-error-expected-spy-onsubmit-to-have-been-called,"['karma-jasmine', 'angular5']",3189,TRUE,3,1
How to unit test a class which uses Google Guice?,"<p>I have a java class that looks like this:</p>

<pre><code>@Inject
PerPixelImageUpdater(PixelUpdaterFactory pixelUpdaterFactory, @Assisted BufferedImage image){
    this.pixelUpdater = pixelUpdaterFactory.create(image);
}

public void someMethod(){
    // some stuff
    this.pixelUpdater.doSomething();
}
</code></pre>

<p>Google Guice is being used for dependency injection.</p>

<p>I am trying to write unit tests to cover <code>someMethod()</code> and I'm not sure the best way to instantiate the class under test.</p>

<p>My initial attempt was to use Guice to create the class:</p>

<pre><code>ImageUpdaterFactory imageUpdaterFactory = injector.getInstance(ImageUpdaterFactory.class);
PerPixelImageUpdater perPixelImageUpdater = (PerPixelImageUpdater) imageUpdaterFactory.create(image);
</code></pre>

<p>But I'm not sure the best way to mock the call to <code>this.pixelUpdater.doSomething()</code> so I can test the other logic in the method under different scenarios.</p>

<p>Would it be better to use <code>new</code> to call the constructor and pass in a mocked factory? I'm struggling to find any documentation on the recommended best practice when unit testing classes using Guice.</p>
",https://stackoverflow.com/questions/49942599/how-to-unit-test-a-class-which-uses-google-guice,"['java', 'unit-testing', 'guice']",2709,TRUE,3,1
Best way to unit test classes using streams?,"<p>I am currently writing some code to try to experiment with separating and abstracting two parts of our storage strategies at work.  We currently use JSON format stored into a file and then retrieve it as our persistent storage.  I am trying to experiment with separating the two concepts:</p>

<p>1) Concept one keeps the serialization separate from the storage type</p>

<p>2) Concept two keeps the storage type separate from the serialization strategy.</p>

<p>I found a good way that works doing some research on various threads, such as using TextWriter/TextReader instead of directly using Files so that any Stream type can be used (FileStream/MemoryStream/etc) so that the unit tests can be done without files.  However, I am running into a problem since the TextWriter/TextReader classes which wrap the streams automatically close and dispose of the streams when they are themselves disposed, which is what I want in practice, but gets me stuck in unit testing.</p>

<p>Here is the code I have so far... this is for concept 1, the serialization process.  Here are the interfaces for it:</p>

<pre><code>/// &lt;summary&gt;
/// Interface for a serializer which reads from a stream and creates a type
/// &lt;/summary&gt;
public interface IInSerializer
{
    /// &lt;summary&gt;
    /// Load type from a stream
    /// &lt;/summary&gt;
    /// &lt;param name=""reader""&gt;&lt;/param&gt;
    /// &lt;returns&gt;&lt;/returns&gt;
    bool Load(TextReader reader);
}

/// &lt;summary&gt;
/// Interface for writing a type out into a stream
/// &lt;/summary&gt;
public interface IOutSerializer
{
    /// &lt;summary&gt;
    /// Save to the stream
    /// &lt;/summary&gt;
    /// &lt;param name=""writer""&gt;&lt;/param&gt;
    /// &lt;returns&gt;&lt;/returns&gt;
    bool Save(TextWriter writer);
}

/// &lt;summary&gt;
/// Helper interface which provides interface &lt;see cref=""IInSerializer""/&gt; 
/// and &lt;see cref=""IOutSerializer""/&gt; for both reading/writing
/// &lt;/summary&gt;
public interface IInOutSerializer : IInSerializer, IOutSerializer
{
}
</code></pre>

<p>Here is an abstract implementation of the serializer for JSON format:</p>

<pre><code>/// &lt;summary&gt;
/// Implementation of &lt;see cref=""IInOutSerializer""/&gt; which serializes into JSON format
/// &lt;/summary&gt;
/// &lt;typeparam name=""T""&gt;Type to be serialized&lt;/typeparam&gt;
public abstract class JSONSerializer&lt;T&gt; : IInOutSerializer
{
    /// &lt;summary&gt;
    /// Source of serialization
    /// &lt;/summary&gt;
    public T Source { get; set; }

    /// &lt;summary&gt;
    /// Provided by very specific type to load the Jobject into type T
    /// &lt;/summary&gt;
    /// &lt;param name=""jObject""&gt;&lt;/param&gt;
    /// &lt;returns&gt;&lt;/returns&gt;
    protected abstract bool LoadJObject(JObject jObject);
    /// &lt;summary&gt;
    /// Provided by very specific type to save type T into a Jobject
    /// &lt;/summary&gt;
    /// &lt;param name=""jObject""&gt;&lt;/param&gt;
    /// &lt;returns&gt;&lt;/returns&gt;
    protected abstract bool Serialize(JObject jObject);

    /// &lt;summary&gt;
    /// &lt;see cref=""IInOutSerializer.Load""/&gt;
    /// &lt;/summary&gt;
    /// &lt;param name=""reader""&gt;&lt;/param&gt;
    /// &lt;returns&gt;&lt;/returns&gt;
    public bool Load(TextReader reader)
    {
        using (var json = new JsonTextReader(reader))
        {
            var jObject = JToken.ReadFrom(json) as JObject;
            if (jObject != null)
                return LoadJObject(jObject);
        }
        return false;
    }

    /// &lt;summary&gt;
    /// &lt;see cref=""IInOutSerializer.Save""/&gt;
    /// &lt;/summary&gt;
    /// &lt;param name=""writer""&gt;&lt;/param&gt;
    /// &lt;returns&gt;&lt;/returns&gt;
    public bool Save(TextWriter writer)
    {
        var jObject = new JObject();
        if (Serialize(jObject))
        {
            using (var json = new JsonTextWriter(writer))
            {
                json.Formatting = Formatting.Indented;
                jObject.WriteTo(json);
                return true;
            }
        }
        return false;
    }
}
</code></pre>

<p>And here is one of the concrete types for serializing my class MetroLineDetails:</p>

<pre><code>public class MetroLineJSONSerializationStrategy : JSONSerializer&lt;MetroLineDetails&gt;
{
    private class MetroLineHelper : IMetroLine, IMetroLineWritable
    {
        public string DestinationStation
        {
            get;
            set;
        }

        public Color LineColor
        {
            get;
            set;
        }

        public char LineLetter
        {
            get;
            set;
        }

        public string Name
        {
            get;
            set;
        }

        public bool SaturdayService
        {
            get;
            set;
        }

        public string SourceStation
        {
            get;
            set;
        }

        public bool SundayHolidayService
        {
            get;
            set;
        }

        public static explicit operator MetroLineDetails(MetroLineHelper source)
        {
            return new MetroLineDetails(source.Name, source.LineColor, source.SourceStation, source.DestinationStation, source.SaturdayService, source.SundayHolidayService);
        }
    }
    protected override bool LoadJObject(JObject jObject)
    {
        var helper = new MetroLineHelper();
        jObject.Read(nameof(MetroLineDetails.Name), (t) =&gt; (string)t, (v) =&gt; helper.Name = v);
        jObject.Read(nameof(MetroLineDetails.LineLetter), (t) =&gt; (char)t, (v) =&gt; helper.LineLetter = v);
        jObject.Read(nameof(MetroLineDetails.SourceStation), (t) =&gt; (string)t, (v) =&gt; helper.SourceStation = v);
        jObject.Read(nameof(MetroLineDetails.DestinationStation), (t) =&gt; (string)t, (v) =&gt; helper.DestinationStation = v);
        jObject.Read(nameof(MetroLineDetails.SaturdayService), (t) =&gt; (bool)t, (v) =&gt; helper.SaturdayService = v);
        jObject.Read(nameof(MetroLineDetails.SundayHolidayService), (t) =&gt; (bool)t, (v) =&gt; helper.SundayHolidayService = v);

        var color = jObject.Read(nameof(MetroLineDetails.LineColor), (t) =&gt; (JObject)t);
        helper.LineColor = color.ToColor();

        Source = (MetroLineDetails)helper;

        return true;
    }

    protected override bool Serialize(JObject jObject)
    {
        jObject.Add(nameof(MetroLineDetails.Name), Source.Name);
        jObject.Add(nameof(MetroLineDetails.LineLetter), Source.LineLetter);
        jObject.Add(nameof(MetroLineDetails.SourceStation), Source.SourceStation);
        jObject.Add(nameof(MetroLineDetails.DestinationStation), Source.DestinationStation);
        jObject.Add(nameof(MetroLineDetails.SaturdayService), Source.SaturdayService);
        jObject.Add(nameof(MetroLineDetails.SundayHolidayService), Source.SundayHolidayService);
        jObject.Add(nameof(MetroLineDetails.LineColor), Source.LineColor.ToJObject());

        return true;
    }
}
</code></pre>

<p>And now here are my storage type interfaces:</p>

<pre><code>/// &lt;summary&gt;
/// Interface for the storage medium
/// &lt;/summary&gt;
public interface IStorageMedium
{
    /// &lt;summary&gt;
    /// Save the information in the serializer
    /// &lt;/summary&gt;
    /// &lt;param name=""serializer""&gt;&lt;/param&gt;
    void Save(IOutSerializer serializer);
    /// &lt;summary&gt;
    /// Load the information to the serializer
    /// &lt;/summary&gt;
    /// &lt;param name=""serializer""&gt;&lt;/param&gt;
    void Load(IInSerializer serializer);
}
</code></pre>

<p>And the type specifically for files:</p>

<pre><code>/// &lt;summary&gt;
/// Implementation of &lt;see cref=""IStorageMedium""/&gt; which stores into a file
/// &lt;/summary&gt;
public class FileStorageMedium : IStorageMedium
{
    private readonly string _fileName;

    public FileStorageMedium(string fileName)
    {
        _fileName = fileName;
    }

    public void Save(IOutSerializer serializer)
    {
        using (var stream = new FileStream(_fileName, FileMode.Truncate))
        {
            using (var writer = new StreamWriter(stream))
            {
                serializer.Save(writer);
            }
        }
    }

    public void Load(IInSerializer serializer)
    {
        using (var stream = new FileStream(_fileName, FileMode.Open))
        {
            using (var reader = new StreamReader(stream))
            {
                serializer.Load(reader);
            }
        }
    }
}
</code></pre>

<p>As you can see in each layer I want to follow best practices and make sure each method closes and flushes the stream for the caller and not leave things open for the sake of unit testing (I know I could probably change the code to not close the streams, but I don't think that is appropriate).</p>

<p>So, now, using the ideas I've found on the forums to not have anything tied specifically to file streams to help with unit testing, I'm still running into problems finding the best way to unit test this.  Here is the unit test I am trying to write:</p>

<pre><code>[TestClass]
public class MetroLine
{
    [TestMethod]
    public void TestSerialize()
    {
        var serializer = new MetroLineJSONSerializationStrategy();
        serializer.Source = new MetroLineDetails(""A"", Colors.Blue, ""LA Union Station"", ""San Bernardino"", true, true);
        using (var stream = new MemoryStream())
        {
            var writer = new StreamWriter(stream);
            serializer.Save(writer);
            stream.Seek(0, SeekOrigin.Begin);
            using (var reader = new StreamReader(stream))
            {
                var text = reader.ReadToEnd();
            }
        }
    }
}
</code></pre>

<p>The stream is closed no matter what I do in the serializer.Save() call since that method uses a disposable which closes the stream (as I believe it should to prevent leaks).  The problem is, I can no longer unit test the stream in any way to test whether any of this works.  I get exceptions thrown saying you cannot access closed streams anymore, which makes sense.  But how can I test the contents of my stream in any meaningful way?</p>
",https://stackoverflow.com/questions/53717650/best-way-to-unit-test-classes-using-streams,"['c#', 'unit-testing', 'stream']",2110,TRUE,0,1
Angular2 Unit test for specific components inside folder,"<p>Project scenario is like</p>

<ul>
<li>we have done so many new ui changes for the project.</li>
<li>we want to update the test cases for all the components which has old ui test 
cases.</li>
<li>since it has old ui cases all the components is failing at once, so we are not 
able to write and check unit testing for components simultaneously.</li>
</ul>

<p>I am aware of fdescribe , fit , xdescribe and xit methods. if we use this mthods also we need to manually change in all components.</p>

<p>Is there any other way to achieve this. We want to run components in a specific folder alone. say folder name is formelemets.</p>
",https://stackoverflow.com/questions/49429805/angular2-unit-test-for-specific-components-inside-folder,"['angular', 'unit-testing', 'angular-cli', 'karma-jasmine']",2426,TRUE,2,1
Jenkins CI/CD pipeline tools and stages,"<p>I am trying to understand the CI/CD pipeline. 
I know that there are different stages like getting the requirement (using JIRA), fetching the source code from SCM, building it (Maven, Ant, Gradle, NPM), Artifact archival (Nexus, JFrog, Artifactory), unit testing (JUnit), other testings and deployment.</p>

<p>I am missing some advanced steps like integrating tools like Code Quality check (SonarQube), Configuration Managment (Chef/Ansible), Deployment tools (Docker) and maybe more.</p>

<p>What would be a good example of a full Continuous Integration, Continuous Deployment and Continuous Delivery pipeline including the popular tools and plugins used with Jenkins for a Java, PHP, JavaScript or Node based project?</p>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/51596885/jenkins-ci-cd-pipeline-tools-and-stages,"['jenkins', 'continuous-integration', 'devops', 'continuous-deployment']",370,FALSE,2,0
Angular - Use Jasmine to spy on chained methods within HttpClient,"<p>I have a situation where I need to spy on a method that is called after another method is called.</p>

<p>Here's the class/method under test:</p>

<pre><code>@Injectable()
export class SomeService {

  constructor(private customHttpClient: CustomHttpClient) {
  }

    updateSomethingCool(signerVO: SignerVO): Observable&lt;SignerVO&gt; {

    // ...

    return this.customHttpClient.withCustomOverrides(new CustomErrorHandlerHttpInterceptorOverride({ passthroughStatusCodes: [BAD_REQUEST, BAD_GATEWAY] }))
        .put&lt;SignerVO&gt;(`/my/url/goes/here`, signerVO);
    }
}
</code></pre>

<p>This class uses CustomHttpClient which looks like this:</p>

<pre><code>    @Injectable()
    export class CustomHttpClient extends HttpClient {
        private interceptors: HttpInterceptor[] | null = null;

        constructor(private injector: Injector,
            originalHandler: HttpHandler, private originalBackend: HttpBackend) {
            super(originalHandler);
        }

        public withCustomOverrides(...overrides: CustomHttpInterceptorOverride[]): HttpClient {

            // do very customizable things here

            return new CustomDelegatingHttpClient(
                new CustomHttpInterceptingHandler(this.originalBackend, this.interceptors, overrides));
        }
    }

    export class CustomDelegatingHttpClient extends HttpClient {
        constructor(private delegate: HttpHandler) {
            super(delegate);
        }
}
</code></pre>

<p>Here's my attempt at unit testing that the <code>put</code> method has indeed been called, hence I need to spy on the <code>put</code> method:</p>

<pre><code>describe(SomeService.name, () =&gt; {
let service: SomeService;
let customHttpClient: CustomHttpClient;

let emptySignerVO: SignerVO = new SignerVO();

beforeEach(() =&gt; {
    customHttpClient= &lt;CustomHttpClient&gt;{};
    customHttpClient.put = () =&gt; null;
    customHttpClient.withCustomOverrides = () =&gt; null;

    service = new SomeService(customHttpClient);
});

describe('updateSomethingCool', () =&gt; {

    it('calls put', () =&gt; {
        spyOn(customHttpClient, 'put').and.stub();

        service.updateSomethingCool(emptySignerVO);

        expect(customHttpClient.put).toHaveBeenCalled();
    });
});
</code></pre>

<p>Now clearly when I run this I receive this failure message:</p>

<pre><code>TypeError: Cannot read property 'put' of null
</code></pre>

<p>However, I do not know exactly how to define either the <code>put</code> or <code>withCustomOverrides</code> methods in the <code>beforeEach</code> portion of the test.</p>

<p>Note that <code>CustomHttpClient</code> is simply a customized wrapper class around Angular's <code>HttpClient</code> that allows some more detailed functionality.</p>

<p>Thank you for your help!</p>
",https://stackoverflow.com/questions/53010766/angular-use-jasmine-to-spy-on-chained-methods-within-httpclient,"['angular', 'typescript', 'jasmine', 'angular-httpclient']",2140,TRUE,2,3
How to use path alias in a react project with Typescript + Jest,"<p>I have been using jest for unit testing in my react project (typescript). Now I have enabled path alias in webpack and tsconfig. In order to use path alias with jest, I have followed this <a href=""https://medium.com/@martin_hotell/type-safe-es2015-module-import-path-aliasing-with-webpack-typescript-and-jest-fe461347e010"" rel=""noreferrer"">tutorial</a>. But I am getting this error when I run my tests:</p>

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

<p>Here is my webpack configuration to enable path alias:</p>

<pre><code>alias: {
  'ui': path.resolve(__dirname, 'src/framework/components/ui')
}
</code></pre>

<p>Here is my jest configuration to enable path alias (package.json)</p>

<pre><code>""moduleNameMapper"": {
    ""ui"": ""&lt;rootDir&gt;/src/framework/components/ui/""
}
</code></pre>

<p>I also tried this version from the tutorial:</p>

<pre><code>""moduleNameMapper"": {
   ""^ui/(.*)$1"": ""&lt;rootDir&gt;/src/framework/components/ui/$1""
}
</code></pre>

<p>Finally here is my tsconfig.json configuration:</p>

<pre><code>""baseUrl"": ""src"",
""paths"": {
  ""ui"": [""framework/components/ui""]      
}
</code></pre>

<p>When I run my test, jest actually resolves the path alias. But it fails to pick up components exposed as default. For e.g this line:</p>

<pre><code>import Button from './FormComponents/Button';
</code></pre>

<p>fails because 'Button' is exported as default from its module.</p>

<p>I hope my question makes sense. Thank you in advance for your help.</p>
",https://stackoverflow.com/questions/51080947/how-to-use-path-alias-in-a-react-project-with-typescript-jest,"['typescript', 'jestjs']",15590,TRUE,17,2
Visual Studio 2017 UnitTest not running,"<p>I am learning C# so I apologise if I cannot be extremely precise in describing the error.</p>

<p>I was following Pluralsight course and at the section of Unit Testing I realised that the Unit Test does not run on my projects.</p>

<p>It casts the following error:</p>

<pre><code>[19/11/2018 22:13:26 Error] Failed to launch testhost with error: System.AggregateException: One or more errors occurred. ---&gt; Microsoft.Build.Exceptions.InvalidProjectFileException: The project file could not be loaded. Could not find file 'C:\Users\Daniele\source\repos\DateTime\UnitTestProject1\bin\x86\Debug\UnitTestProject1.build.appxrecipe'.  C:\Users\Daniele\source\repos\DateTime\UnitTestProject1\bin\x86\Debug\UnitTestProject1.build.appxrecipe ---&gt; System.IO.FileNotFoundException: Could not find file 'C:\Users\Daniele\source\repos\DateTime\UnitTestProject1\bin\x86\Debug\UnitTestProject1.build.appxrecipe'.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
   at Microsoft.Build.Internal.XmlReaderExtension..ctor(String file)
   at Microsoft.Build.Construction.ProjectRootElement.LoadDocument(String fullPath, Boolean preserveFormatting)
   --- End of inner exception stack trace ---
   at Microsoft.Build.Shared.ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(Boolean condition, String errorSubCategoryResourceName, BuildEventFileInfo projectFile, Exception innerException, String resourceName, Object[] args)
   at Microsoft.Build.Construction.ProjectRootElement.LoadDocument(String fullPath, Boolean preserveFormatting)
   at Microsoft.Build.Construction.ProjectRootElement..ctor(String path, ProjectRootElementCache projectRootElementCache, Boolean preserveFormatting)
   at Microsoft.Build.Construction.ProjectRootElement.CreateProjectFromPath(String projectFile, ProjectRootElementCache projectRootElementCache, Boolean preserveFormatting)
   at Microsoft.Build.Construction.ProjectRootElement.&lt;&gt;c.&lt;OpenProjectOrSolution&gt;b__201_0(String path, ProjectRootElementCache cache)
   at Microsoft.Build.Evaluation.ProjectRootElementCache.Get(String projectFile, OpenProjectRootElement openProjectRootElement, Boolean isExplicitlyLoaded, Nullable`1 preserveFormatting)
   at Microsoft.Build.Construction.ProjectRootElement.OpenProjectOrSolution(String fullPath, IDictionary`2 globalProperties, String toolsVersion, ProjectRootElementCache projectRootElementCache, Boolean isExplicitlyLoaded)
   at Microsoft.Build.Evaluation.ProjectCollection.LoadProject(String fileName, IDictionary`2 globalProperties, String toolsVersion)
   at Microsoft.VisualStudio.UwpTestHostRuntimeProvider.RecipeFile.get_Project()
   at Microsoft.VisualStudio.UwpTestHostRuntimeProvider.RecipeFile.get_Architecture()
   at Microsoft.VisualStudio.UwpTestHostRuntimeProvider.Deployer.Microsoft.VisualStudio.UwpTestHostRuntimeProvider.IDeployer.get_DeploymentArchitecture()
   at Microsoft.VisualStudio.UwpTestHostRuntimeProvider.UwpTestHostManager.&lt;LaunchHostAsync&gt;d__35.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.UwpTestHostRuntimeProvider.UwpTestHostManager.&lt;Microsoft-VisualStudio-TestPlatform-ObjectModel-Host-ITestRuntimeProvider-LaunchTestHostAsync&gt;d__30.MoveNext()
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at System.Threading.Tasks.Task`1.get_Result()
   at Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Client.ProxyOperationManager.SetupChannel(IEnumerable`1 sources)
---&gt; (Inner Exception #0) Microsoft.Build.Exceptions.InvalidProjectFileException: The project file could not be loaded. Could not find file 'C:\Users\Daniele\source\repos\DateTime\UnitTestProject1\bin\x86\Debug\UnitTestProject1.build.appxrecipe'.  C:\Users\Daniele\source\repos\DateTime\UnitTestProject1\bin\x86\Debug\UnitTestProject1.build.appxrecipe ---&gt; System.IO.FileNotFoundException: Could not find file 'C:\Users\Daniele\source\repos\DateTime\UnitTestProject1\bin\x86\Debug\UnitTestProject1.build.appxrecipe'.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share)
   at Microsoft.Build.Internal.XmlReaderExtension..ctor(String file)
   at Microsoft.Build.Construction.ProjectRootElement.LoadDocument(String fullPath, Boolean preserveFormatting)
   --- End of inner exception stack trace ---
   at Microsoft.Build.Shared.ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(Boolean condition, String errorSubCategoryResourceName, BuildEventFileInfo projectFile, Exception innerException, String resourceName, Object[] args)
   at Microsoft.Build.Construction.ProjectRootElement.LoadDocument(String fullPath, Boolean preserveFormatting)
   at Microsoft.Build.Construction.ProjectRootElement..ctor(String path, ProjectRootElementCache projectRootElementCache, Boolean preserveFormatting)
   at Microsoft.Build.Construction.ProjectRootElement.CreateProjectFromPath(String projectFile, ProjectRootElementCache projectRootElementCache, Boolean preserveFormatting)
   at Microsoft.Build.Construction.ProjectRootElement.&lt;&gt;c.&lt;OpenProjectOrSolution&gt;b__201_0(String path, ProjectRootElementCache cache)
   at Microsoft.Build.Evaluation.ProjectRootElementCache.Get(String projectFile, OpenProjectRootElement openProjectRootElement, Boolean isExplicitlyLoaded, Nullable`1 preserveFormatting)
   at Microsoft.Build.Construction.ProjectRootElement.OpenProjectOrSolution(String fullPath, IDictionary`2 globalProperties, String toolsVersion, ProjectRootElementCache projectRootElementCache, Boolean isExplicitlyLoaded)
   at Microsoft.Build.Evaluation.ProjectCollection.LoadProject(String fileName, IDictionary`2 globalProperties, String toolsVersion)
   at Microsoft.VisualStudio.UwpTestHostRuntimeProvider.RecipeFile.get_Project()
   at Microsoft.VisualStudio.UwpTestHostRuntimeProvider.RecipeFile.get_Architecture()
   at Microsoft.VisualStudio.UwpTestHostRuntimeProvider.Deployer.Microsoft.VisualStudio.UwpTestHostRuntimeProvider.IDeployer.get_DeploymentArchitecture()
   at Microsoft.VisualStudio.UwpTestHostRuntimeProvider.UwpTestHostManager.&lt;LaunchHostAsync&gt;d__35.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.UwpTestHostRuntimeProvider.UwpTestHostManager.&lt;Microsoft-VisualStudio-TestPlatform-ObjectModel-Host-ITestRuntimeProvider-LaunchTestHostAsync&gt;d__30.MoveNext()&lt;---

[19/11/2018 22:13:26 Informational] ========== Run test finished: 0 run (0:00:00.0535907) ==========
</code></pre>

<p>I have found different resources online
<a href=""https://developercommunity.visualstudio.com/content/problem/212059/unable-to-debug-unit-test-visual-studio-enterprise.html"" rel=""nofollow noreferrer"">https://developercommunity.visualstudio.com/content/problem/212059/unable-to-debug-unit-test-visual-studio-enterprise.html</a></p>

<p>And different solutions:
first to disable a VPN (which I don't have) and then to Run <code>“set-mppreference -EnableNetworkProtection 0”</code> in an elevated PowerShell prompt, and restart VS.</p>

<p>None of this method has ultimately work and I am unable to run any test.</p>
",https://stackoverflow.com/questions/53383482/visual-studio-2017-unittest-not-running,"['c#', 'visual-studio', 'unit-testing']",704,TRUE,2,1
Google mock for qabstractsocket class,"<p>I'm trying to solve my unit testing problem. I have a class with a <code>QTcpSocket</code> object in it. This class has derived from the <code>QObject</code> to use the signal/slot system and the socket object is used inside slots. 
I have tried to mock (gmock) this socket object, but I couldn't find any solution to incorporate the mock object to my class. </p>

<p>I cannot do this through a template, because the MOC compiler doesn't work with templates. And I cannot create a general interface for the QTcpSocket and my mock class. Though the QAbstractSocket has virtual methods, it has non-virtual methods like <code>waitForReadyRead()</code> too. That confuse me.</p>
",https://stackoverflow.com/questions/51151409/google-mock-for-qabstractsocket-class,"['qt', 'googlemock', 'qt-signals', 'qtcpsocket', 'qt-slot']",305,FALSE,2,0
How to integrate meteor in SauceLabs?,"<p>I am working on a meteor-balze app. </p>

<p>I have started to write mocha test cases for this app. And I want to use mocha with SauceLabs.</p>

<p>But I am not getting any helpful link for it. I go through below links:</p>

<p><a href=""https://saucelabs.com/products/javascript-unit-testing/mocha-js"" rel=""nofollow noreferrer"">https://saucelabs.com/products/javascript-unit-testing/mocha-js</a></p>

<p><a href=""https://github.com/pbakaus/mocha-sauce"" rel=""nofollow noreferrer"">https://github.com/pbakaus/mocha-sauce</a></p>

<p>I also add mocha-sauce package and also take clone from its repository and tried to run its dummy app but getting below errors:-</p>

<pre><code>{ 
    Error: connect ECONNREFUSED 127.0.0.1:4444
        at Object.exports._errnoException (util.js:1018:11)
        at exports._exceptionWithHostPort (util.js:1041:20)
        at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1090:14)
    code: 'ECONNREFUSED',
    errno: 'ECONNREFUSED',
    syscall: 'connect',
    address: '127.0.0.1',
    port: 4444
}
</code></pre>

<p>There is no video available on YouTube for integrating mocha with saucelabs.</p>

<p>Please advise how I can integrate mochaJS with SauceLabs.</p>

<p>Thanks &amp; Regards,</p>

<p>Saransh</p>
",https://stackoverflow.com/questions/48166141/how-to-integrate-meteor-in-saucelabs,"['javascript', 'node.js', 'mocha.js', 'meteor-blaze', 'saucelabs']",71,FALSE,2,0
How to test presenter on android (MVP)?,"<p>I've never create unit testing before. I'm planning to create UI test &amp; Unit test for my presenter &amp; datasource. I use Retrofit, RxJava, and Dagger in my apps. </p>

<p>Here's what i've tried so far</p>

<p>DataSource (My Datasource is coming from API)</p>

<pre><code>public class DataSource implements DataSourceContract {

    private static DataSource dataSource;

    @Inject
    SharedPreferences sharedPreferences;
    @Inject
    NewsService newsService;

    private DataSource(Context context) {
        DaggerAppComponent.builder()
                .networkModule(new NetworkModule(API_URL))
                .appModule(new AppModule(context.getApplicationContext()))
                .preferencesModule(new PreferencesModule())
                .build()
                .inject(this);
    }

    public static synchronized DataSource getInstance(Context context) {
        if(dataSource == null) {
            dataSource = new DataSource(context);
        }

        return dataSource;
    }

    public String parseError(Throwable e) {
        if(e instanceof SocketTimeoutException) {
            return ERROR_TIMEOUT;
        }
        else if(e instanceof SocketException) {
            return ERROR_NO_CONNECTION;
        }
        else {
            return ERROR_SERVER;
        }
    }

    @Override
    public DisposableObserver&lt;NewsResponse&gt; getNews(final Callback&lt;NewsResponse&gt; callback) {
        return newsService.getNews()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new DisposableObserver&lt;NewsResponse&gt;() {
                    @Override
                    public void onNext(NewsResponse value) {
                        callback.onSuccess(value);
                    }

                    @Override
                    public void onError(Throwable e) {
                        callback.onFailure(e);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
</code></pre>

<p>Presenter</p>

<pre><code>public class MainPresenter implements MainContract.Presenter {
    private MainContract.View view;
    private DataSource dataSource;
    private Disposable dispossable;

    public MainPresenter(MainContract.View view, DataSource dataSource) {
        this.view = view;
        this.dataSource = dataSource;
    }

    @Override
    public void onStart() {
        getNews();
    }

    @Override
    public void onStop() {
        if(dispossable != null &amp;&amp; !dispossable.isDisposed()) {
            dispossable.dispose();
        }
    }

    @Override
    public void getNews() {
        view.setLoading(true);

        dispossable = dataSource.getNews(new DataSourceContract.Callback&lt;NewsResponse&gt;() {
            @Override
            public void onSuccess(NewsResponse responseData) {
                try {
                    switch (responseData.getStatus()) {
                        case API_SUCCESS:
                            view.setLoading(false);
                            view.getNewsSuccess(responseData.getArticles());
                            break;
                        default:
                            view.setLoading(false);
                            view.getNewsFailed(responseData.getStatus());
                            break;

                    }
                }
                catch (Exception e) {
                    view.setLoading(false);
                    view.getNewsFailed(ERROR_SERVER);
                }
            }

            @Override
            public void onFailure(Throwable e) {
                view.setLoading(false);
                view.isNetworkFailed(dataSource.parseError(e), false);
            }
        });
    }
}
</code></pre>

<p>And this is the test of my presenter</p>

<pre><code>public class MainPresenterTest {
    @Mock
    DataSource dataSource;

    @Mock
    MainContract.View view;

    MainContract.Presenter presenter;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        presenter = new MainPresenter(view, dataSource);
    }

    @Test
    public void getNews() throws Exception {
        List&lt;Article&gt; articleList = new ArrayList&lt;&gt;();
        presenter.getNews();
        Mockito.verify(view, Mockito.only()).getNewsSuccess(articleList);
    }
}
</code></pre>

<p>But there is error when I run the test</p>

<pre><code>Wanted but not invoked:
view.getNewsSuccess([]);
-&gt; at com.java.mvp.view.main.MainPresenterTest.getNews(MainPresenterTest.java:37)
</code></pre>

<p>I have no problem running this apps on the device, but I can't make it work on testing</p>

<p>Any idea how to fix this presenter test? Am I doing it right?</p>

<p>And how do I test my datasource? I have no idea how to test this one</p>

<p>Thank you</p>
",https://stackoverflow.com/questions/48766017/how-to-test-presenter-on-android-mvp,"['android', 'testing', 'mvp']",4545,TRUE,2,2
Which layer of my application should have integration tests: Controller vs Service VS DAO?,"<p>If my application has three layers
1. Controller
2. Service
3. DAO</p>

<p>Which of the above layers should have integration tests?</p>

<p>Currently, I have covered the controller and service layers with extensive unit test cases, including any validations in the respective layers. Also I have mocked out any dependencies in these layers.</p>

<p>I only have integration tests for my DAO methods, to actually test the DB interaction.</p>

<p>Is this a good approach of having integration tests only for the DAO layer and unit testing all the other layers using mocks wherever required ? Or should I also write integration tests for my controller and service layers? Please share thoughts.</p>
",https://stackoverflow.com/questions/52779636/which-layer-of-my-application-should-have-integration-tests-controller-vs-servi,"['unit-testing', 'integration-testing']",450,TRUE,2,1
How to exclude generated mocks from package coverage in Visual Studio Code,"<p>I'm unit-testing a Golang project, via Visual Studio Code, and one of the dependencies I make use of is called <a href=""https://github.com/vektra/mockery/"" rel=""nofollow noreferrer""><code>mockery</code></a>. It works by creating mocks of the target Golang interfaces, in the package they're found. As consequence, even though I could have sworn to test everything in said package, my test coverage is only at 58%. However, when I remove the mock (turns out that I didn't need it) from the package, my test coverage, sure as rain, shoots up to the 97.9% that I was expecting.</p>

<p>Is there any way to tell Visual Studio Code ""hey, don't include mockery mocks (which start with <code>mock_</code>) in your package coverage calculations""?</p>
",https://stackoverflow.com/questions/51847412/how-to-exclude-generated-mocks-from-package-coverage-in-visual-studio-code,"['go', 'visual-studio-code']",1995,TRUE,2,1
Is it possible to unit test this Go function that uses the AWS SDK without changing the parameters?,"<p>I am new to Go and have written a function that uses the AWS Secrets Manager to fetch a secret: </p>

<pre><code>//Helper function to get secret from AWS Secret Manager
func getAWSSecrets() (secretMap map[string]string, err error) {
    // Create new AWS session in order to get db info from SecretsManager
    sess, err := session.NewSession()
    if err != nil {
        return nil, err
    }

    // Create a new instance of the SecretsManager client with session
    svc := secretsmanager.New(sess)

    //Get secret config values
    req, resp := svc.GetSecretValueRequest(&amp;secretsmanager.GetSecretValueInput{
        SecretId: aws.String(""my/secret/string""),
    })

    err = req.Send()
    if err != nil {
        return nil, err
    }

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

<p>I need to create a unit test for the function, and to do so I need to mock the AWS Secrets Manager.  I discovered a <a href=""https://docs.aws.amazon.com/sdk-for-go/api/service/secretsmanager/secretsmanageriface/"" rel=""nofollow noreferrer"">Secrets Manager Interface that AWS was created to help with unit testing</a>.  In the example displayed, the AWS Secrets Manager is passed into the function being tested, making it easy to pass in the mock service.  Is this the only way to successfully unit test the function?  Or can the service be mocked in the function I have above? </p>
",https://stackoverflow.com/questions/50451159/is-it-possible-to-unit-test-this-go-function-that-uses-the-aws-sdk-without-chang,"['amazon-web-services', 'unit-testing', 'go', 'mocking']",2219,TRUE,2,1
How to mock elastic search python?,"<p>I need to mock elasticsearch calls, but I am not sure how to mock them in my python unit tests. I saw this framework called <code>ElasticMock</code>. I tried using it the way indicated in the documentation and it gave me plenty of errors.
It is here : 
<a href=""https://github.com/vrcmarcos/elasticmock"" rel=""noreferrer"">https://github.com/vrcmarcos/elasticmock</a></p>

<p>My question is, is there any other way to mock elastic search calls?</p>

<p>This doesn't seem to have an answer either: <a href=""https://stackoverflow.com/questions/40084131/mock-elastic-search-data"">Mock elastic search data</a>.
And this just indicates to actually do integration tests rather than unit tests, which is not what I want:
<a href=""https://stackoverflow.com/questions/36128632/unit-testing-elastic-search-inside-django-app"">Unit testing elastic search inside Django app</a>.</p>

<p>Can anyone point me in the right direction? I have never mocked things with <code>ElasticSearch</code>.</p>
",https://stackoverflow.com/questions/48788314/how-to-mock-elastic-search-python,"['python', 'unit-testing', 'elasticsearch']",14473,TRUE,7,3
C# embedding test code inside a console app,"<p>Is it possible to embed test code (based on one of the MSTEST, NUNIT, or XUNIT) inside a dotnet core console app?</p>

<p>Based on the tutorials like the one below, it seems there is the requirement that the test code has always to be a separate project than the actual project.</p>

<p>I understand some of the cons of embedding testing code in the actual project, but I really don’t want to turn many of the internal classes to public, or adding the InternalTo attribute everywhere, just to make them accessible to the test code.</p>

<p><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>
",https://stackoverflow.com/questions/48837458/c-embedding-test-code-inside-a-console-app,"['c#', 'unit-testing', 'nunit', 'mstest', 'xunit']",1741,TRUE,2,2
How to get last value from an ArrayList using reflection?,"<p>I simply want to get the last value in an ArrayList using reflection. Typically this is achieved by doing:</p>

<pre><code>String s = ArrayList.get(ArrayList.size()-1);
</code></pre>

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

<pre><code>String s = Object.get(ClassInstance, Object.get(ClassInstance, ArrayList.size()-1));
</code></pre>

<p>Obviously this isn't the correct syntax. What would the correct syntax be to achieve this?</p>

<p><strong>EDIT:</strong></p>

<p>The reason for trying to do this is because I am unit testing my code and the ArrayList located inside the class I am testing is private. One of my boolean methods takes a parameter and I wanted to test it using the last value in the ArrayList (I don't know the value as it is randomly generated, but the value should always return true). Any solutions for this problem are much appreciated.</p>
",https://stackoverflow.com/questions/53529537/how-to-get-last-value-from-an-arraylist-using-reflection,"['java', 'unit-testing', 'reflection']",159,TRUE,1,1
FakeRequest seem to be Null when passed to a controller in unit test,"<p>Getting <code>Null Pointer</code> error when unit testing controller. The issue seem to be in the line</p>

<pre><code>def signupUser = Action.async{
    implicit request =&gt; { //requeust seem to be null
</code></pre>

<p>I suspect so because the stacktrace from previous tests point to implicit request line. But I don’t know what could be wrong in this because I am using FakeRequest like so <code>val request = FakeRequest(""POST"", ""/ws/users/signup"").withJsonBody(Json.parse(""""""{""bad"": ""field""}""""""))</code></p>

<p>Following is a snippet of a controller I want to unit-test</p>

<pre><code>  class UserController @Inject()(userRepo: UsersRepository,cc: ControllerComponents, silhouette: Silhouette[JWTEnv])(implicit exec: ExecutionContext) extends AbstractController(cc){ 

def signupUser = Action.async{
    implicit request =&gt; {...}
 }
</code></pre>

<p>I only want to test that the controller returns an error when it gets a request without <code>json</code> body. Thus I don't need <code>Silhouette</code> and I want to mock it. But I am getting null pointer error.</p>

<p>Following is the way I have written my unit test case is</p>

<pre><code>class UserControllerUnitSpec extends PlaySpec with MockitoSugar {

  ""User signup request with non-JSON body"" should {

    ""return  400 (Bad Request) and the validation text 'Incorrect body type. Body type must be JSON'"" in {

      val email = ""d@d.com""
      val loginInfo = LoginInfo(CredentialsProvider.ID, email);
      val passwordInfo = PasswordInfo(""someHasher"",""somePassword"",Some(""someSalt""))
      val internalUserProfile = InternalUserProfile(loginInfo,true,Some(passwordInfo))
      val externalUserProfile = ExternalUserProfile(email,""d"",""d"",Some(""somePassword""))
      val userProfile = UserProfile(Some(internalUserProfile),externalUserProfile)
      val user = User(UUID.randomUUID(),userProfile)

      println(""testing with mocked User value"",user);

      val mockUserRepository = mock[UsersRepository]
      when(mockUserRepository.findUser(loginInfo)).thenReturn(Future(Some(user)))
      when(mockUserRepository.saveUser(user)).thenReturn(Future(Some(user)))

      val mockSilhouette = mock[Silhouette[JWTEnv]] //I am probably not doing this correctly
      val mockControllerComponents = mock[ControllerComponents] //I am not sure if this is correct either
      val controller = new UserController(mockUserRepository,mockControllerComponents,mockSilhouette)

      val result:Future[Result] = controller.signupUser(FakeRequest())
      (result.map(response =&gt; {
        println(""response: "",response)
        response mustBe BadRequest
      }))
    }
  }
}
</code></pre>
",https://stackoverflow.com/questions/50762033/fakerequest-seem-to-be-null-when-passed-to-a-controller-in-unit-test,"['mockito', 'scalatest', 'playframework-2.6', 'silhouette']",293,TRUE,1,2
Is it possible to write a unittest script that does not close the browser on each test?,"<p>I am running on windows 10 with python 3.6.2 and selenium 3.11. I currently have a small unit test which works but on each new test it opens up a new browser. The first test is to login but when I move to the next test it starts a new browser therefore I cannot continue my unit testing. Below is my current code </p>

<pre><code>class LoginTest(unittest.TestCase):
logging.basicConfig(filename='test.log', level=logging.INFO,
                    format='%(asctime)s:%(levelname)s:%(lineno)d:%(message)s')

def setUp(self):
    logging.info('starting browser')
    self.driver = DriverFactory().run_browser()
    base_page = Page(self.driver)
    base_page.open(""url"")
    page_title = self.driver.title
    assert page_title == ""title""
    logging.info('Login page title: ' + page_title)

def test_login(self):
    logging.info('Logging in')
    login_page = LoginPage(self.driver)
    login_page.username().send_keys(""username"")
    login_page.password().send_keys(""password"")
    login_page.sign_in().click()
    page_title = self.driver.title
    Page(self.driver).wait()
    assert page_title == ""title""
    logging.info('Main page title: ' + page_title)

def test_search(self):
    logging.info(""Search"")
    main_page = MainMenu(self.driver)
    tab = main_page.Loans(self.driver)
    main_page.tab_search('Foo')
    main_page.switchTo_left_frame()
    tab.search().send_keys('bar')
    tab.top_result()
    page_title = self.driver.title
    logging.info(""Loan Page Title: "" + page_title)

def tearDown(self):
    self.driver.quit()

if __name__ == ""__main__"":
    unittest.main()
</code></pre>

<p>This script will login then close that browser and start a new one and try to complete the search test which fails. I am unable to use url navigation due to the security of the webpage. Any help would be greatly appreciated thanks. </p>
",https://stackoverflow.com/questions/51504428/is-it-possible-to-write-a-unittest-script-that-does-not-close-the-browser-on-eac,"['python', 'unit-testing', 'selenium']",365,TRUE,1,1
Why does &#39;yield&#39; in a test case let the test pass,"<p>I am trying to understand the following python code snippet, taken from the SublimeText3 plugin development <a href=""https://github.com/randy3k/UnitTesting-example/blob/deferred/tests/test_defer.py"" rel=""nofollow noreferrer"">unit testing examples</a>.</p>

<pre><code>def test_delayed_insert(self):
    sublime.set_timeout(
        lambda: self.view.run_command(""delayed_insert_hello_world""),
        100)
    # `delayed_insert_hello_world` will be execulated after the timeout
    # `yield 1000` will yield the runtime to main thread and continue
    # the execution 1 second later
    yield 1000
    row = self.getRow(0)
    self.assertEqual(row, ""hello world"")
</code></pre>

<p>How can this work? If unittest does not support this (call the test as a generator), the code would not be executed, right?
My current understanding is the unittest framework takes the yielded value 'x', and suspends itself for 'x' ms, in this case 1000ms, similar to the semantics of yield/sleep in c++ threads. However, that depends on 'unittest' to really use the yielded value in this way.</p>

<p>If it does, why does this test not fail (tried it within st3 = python 3.3.6 and python 3.5.2) ?</p>

<pre><code>from unittest import TestCase

class TestMe(TestCase):
    def test_failtest(self):
        self.assertTrue(False)
        yield 0
</code></pre>

<p>Running it gives:</p>

<pre><code>~$ python3 -m unittest test_me.py --verbose
test_failtest (test_me.TestMe) ... ok

----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
</code></pre>
",https://stackoverflow.com/questions/49273492/why-does-yield-in-a-test-case-let-the-test-pass,"['python-3.x', 'unit-testing']",847,TRUE,1,1
Why does this NSubstitute Received Call Fail?,"<p>Test in question: ""TestGetAllPeople()""</p>

<p>I was experimenting with Unit testing frameworks (as I don't have a lot of experience using them) and I'm encountering an error I cant see to suss out. </p>

<p>According to the documentation (<a href=""https://nsubstitute.github.io/help/received-calls/"" rel=""nofollow noreferrer"">https://nsubstitute.github.io/help/received-calls/</a>) (I believe). It shouldn't fail, because I ran it through the debugger and it IS called, it retrieves the two people so there is something I'm obviously missing.</p>

<ul>
<li>VS2015, </li>
<li>.NET 4.5.2, </li>
<li>NSubstitute 3.1, </li>
<li>NUnit 3.9 and </li>
<li>NUnitAdapter 3.9.</li>
</ul>

<p>Person.cs</p>

<pre><code>public interface IPersonRepository
{
    List&lt;Person&gt; GetPeople();
    Person GetPersonByID(string ID);
}

public class Person
{
    public string ID;
    public string FirstName;
    public string LastName;

    public Person(string newID, string fn, string ln)
    {
        ID = newID;
        FirstName = fn;
        LastName = ln;
    }
}

public class PersonService
{
    private IPersonRepository personRepo;

    public PersonService(IPersonRepository repo)
    {
        personRepo = repo;
    }

    public List&lt;Person&gt; GetAllPeople()
    {
        return personRepo.GetPeople();
    }

    public List&lt;Person&gt; GetAllPeopleSorted()
    {
        List&lt;Person&gt; people = personRepo.GetPeople();
        people.Sort(delegate (Person lhp, Person rhp)
        {
            return lhp.LastName.CompareTo(rhp.LastName);
        });
        return people;
    }

    public Person GetPerson(string ID)
    {
        try
        {
            return personRepo.GetPersonByID(ID);
        }
        catch(ArgumentException)
        {
            return null; // No person found
        }
    }
}
</code></pre>

<p>Tests</p>

<pre><code>[TestFixture]
public class Tests
{

    //This is our mock object
    private IPersonRepository personRepoMock;

    //Data
    private Person personOne = new Person(""1"", ""A"", ""Test"");
    private Person personTwo = new Person(""2"", ""B"", ""Yest"");
    private List&lt;Person&gt; peopleList;

    [SetUp]
    public void TestInit()
    {
        //For lauching VS debugger
        //System.Diagnostics.Debugger.Launch();

        peopleList = new List&lt;Person&gt;();
        peopleList.AddRange(new Person[] { personOne, personTwo });

        //Mock/Fake object of IPersonRepository
        personRepoMock = Substitute.For&lt;IPersonRepository&gt;();


        //FAKES --------------------------------------------
        //Remember Subtitute.ForPartsOf!
        //https://nsubstitute.github.io/help/partial-subs/
    }

    [TearDown]
    public void TearDown()
    {
        //TODO
    }

    [Test]
    public void CanCreate()
    {
        Person person = new Person(""1"", ""A"", ""Test"");
        Assert.IsNotNull(person);
    }

    [Test]
    public void TestGetAllPeople()
    {
        //Expects a call to GetPeople and returns peopleList
        //Weirdly enough the call IS receieved as it DOES return the people list
        //Through the mock, but throws saying it wasnt
        personRepoMock.Received().GetPeople().Returns(peopleList);

        //-------------Expectations-------------
        //Checking for multiple received 
        //personRepoMock.Received(x).etc
        //Clearing
        //personRepoMock.ClearReceivedCalls();
        //-------------Expectations-------------

        //Using this version to continue development for now.
        //personRepoMock.GetPeople().Returns(peopleList);
        PersonService pServ = new PersonService(personRepoMock);
        Assert.AreEqual(2, pServ.GetAllPeople().Count);
    }

    [Test]
    public void TestGetAllPeopleSorted()
    {
        //Expectss a call to get people and returns a peopleList
        //personRepoMock.Received().GetPeople().Returns(peopleList);
        personRepoMock.GetPeople().Returns(peopleList);

        PersonService pServ = new PersonService(personRepoMock);

        List&lt;Person&gt; people = pServ.GetAllPeopleSorted();
        Assert.NotNull(people);
        Assert.AreEqual(2, people.Count);
        Person p = people[0];
        Assert.AreEqual(""Test"", p.LastName);
    }

    [Test]
    public void TestGetSinglePersonWithValidID()
    {
        //Expectss a call to GetPerson and returns personOne
        personRepoMock.GetPersonByID(Arg.Is(""1"")).Returns(personOne);

        PersonService pServ = new PersonService(personRepoMock);

        Person p = pServ.GetPerson(""1"");
        Assert.IsNotNull(p);
        Assert.AreEqual(p.ID, ""1"");
    }

    [Test]
    public void TestGetSinglePersonWithInvalidID()
    {
        //Throwing
        personRepoMock.GetPersonByID(Arg.Any&lt;string&gt;()).Returns(x =&gt; 
        {
            throw new ArgumentException();
        });

        PersonService pServ = new PersonService(personRepoMock);
        Assert.IsNull(pServ.GetPerson(""-1""));
    }
}
</code></pre>

<p>Uncomment to debug.</p>

<pre><code>//System.Diagnostics.Debugger.Launch();
</code></pre>

<p>Any suggestions on style/conventions are welcome (I realise test names arent great right now).</p>

<p>I will update with any information requested.</p>
",https://stackoverflow.com/questions/48271244/why-does-this-nsubstitute-received-call-fail,"['c#', 'visual-studio', 'unit-testing', 'nunit', 'nsubstitute']",1329,TRUE,1,1
How do I get karma to set webpack&#39;s mode to development?,"<p>When I run karma, I'm getting the following warning:</p>

<blockquote>
  <p>WARNING in configuration
  The 'mode' option has not been set, webpack will fallback to 'production' for this value. Set 'mode' option to 'development' or 'production' to enable defaults for each environment.
  You can also set it to 'none' to disable any default behavior. Learn more: <a href=""https://webpack.js.org/concepts/mode/"" rel=""noreferrer"">https://webpack.js.org/concepts/mode/</a></p>
</blockquote>

<p>I tried adding <code>mode: 'development'</code> to my <code>webpack-test.config.js</code> file as suggested in the link above, but not only did that fail to make any difference, Intellij IDEA complained:</p>

<blockquote>
  <p>webpack: Property 'mode' is not allowed</p>
</blockquote>

<p>My unit testing does run anyway, but I'd like to get rid of this warning. Any help is much appreciated.</p>

<p>Here's my <code>webpack-test.config.js</code> file:</p>

<pre><code>const path = require('path');
const webpack = require('webpack');

const ROOT = path.resolve( __dirname, 'src' );

module.exports = {
  mode: 'production',
  context: ROOT,

  resolve: {
    extensions: ['.ts', '.js'],
    modules: [
      ROOT,
      'node_modules'
    ]
  },

  module: {
    rules: [
      // PRE-LOADERS
      {
        enforce: 'pre',
        test: /\.js$/,
        use: 'source-map-loader'
      },

      // LOADERS
      {
        test: /\.ts$/,
        exclude: [ /node_modules/ ],
        use: 'ts-loader'
      }
    ]
  },

  devtool: 'cheap-module-source-map',
  devServer: {}
};
</code></pre>

<p>My <code>karma.conf.js</code>:</p>

<pre><code>module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('karma-webpack')
    ],
    client:{
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    coverageIstanbulReporter: {
      reports: [ 'html', 'lcovonly' ],
      fixWebpackSourcePaths: true
    },
    reporters: ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false,
    files: [
      'spec.bundle.js'
    ],
    preprocessors: {
      'spec.bundle.js': ['webpack']
    },
    webpack: require('./webpack-test.config')
  });
};
</code></pre>

<p>And <code>spec.bundle.js</code>:</p>

<pre><code>const testsContext = require.context(""./"", true, /\.spec\.ts$/);
testsContext.keys().forEach(testsContext);
</code></pre>

<p>I'm launching karma via:</p>

<pre><code>karma start ./karma.conf.js
</code></pre>
",https://stackoverflow.com/questions/50382893/how-do-i-get-karma-to-set-webpacks-mode-to-development,"['javascript', 'unit-testing', 'webpack', 'jasmine', 'karma-runner']",3495,TRUE,6,2
Constructor / Self-reference for instance variables,"<p>How to best refactor a constructor in Java, which instantiates member/instance variables, which need a reference to the class which is going to be constructed/instantiated? I want to pass the dependency in the constructor as a parameter, to enable unit testing of methods which call methods on the instance variable.</p>

<p>Basically it boils down to something like this:</p>

<pre class=""lang-java prettyprint-override""><code>final class Foo {
  private final Bar bar;
  ...

  Foo() {
    bar = new Bar(this);

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

<p>However, all dependencies should be given by dependency injection / per parameter.</p>

<p>Edit: My idea would be adding a factory as a parameter to the constructor and then call a method which passes this in a createInstance method in the methods, which use the instance variables:</p>

<pre><code>final class Foo {
  private final BarFactory factory;

  Foo(BarFactory factory) {
    this.factory = Objects.nonNull(factory);
  }

  public void bla(String fooBar) { 
    final Bar bar = factory.create(this); 
    ...
  }
}
</code></pre>

<p>So I can mock the factory.</p>
",https://stackoverflow.com/questions/49930905/constructor-self-reference-for-instance-variables,"['java', 'refactoring']",1272,TRUE,1,1
Enzyme cannot read this.props.match.params from ComponentDidMount,"<p>I just got into unit testing for my project, the adapter is setup correctly, and I wrote some tests. A few of my tests throw errors, namely the ones where I include a variable from the redux state. The following is just one of them:</p>

<pre><code>export class BasePage extends React.Component {
  componentDidMount() {
    const baseId = this.props.match.params.baseId;
    const access_token = this.props.auth;
    if (this.props.match.params.baseId) {
        this.props.dispatch(fetchSingleBase(baseId, access_token));
    }
  }
}
</code></pre>

<p>The below named error occurred in the above <code>componentDidMount</code> as well, but I was able to mitigated that with the <code>if</code> statement.</p>

<p>The <code>BasePage</code> is rendered via Router in app.js:</p>

<pre><code>    return (
      &lt;div&gt;
        &lt;Navbar /&gt;
        &lt;main&gt;
          ...
          &lt;Route exact path=""/single-base/:baseId"" component={BasePage} /&gt;
        &lt;/main&gt;
      &lt;/div&gt;
    );
</code></pre>

<p>On the basepage, I return:</p>

<pre><code>return (
    &lt;div className=""basepage""&gt;
        {title}
        &lt;UserList baseId={this.props.match.params.baseId} /&gt;
        &lt;MessageList baseId={this.props.match.params.baseId} /&gt;
    &lt;/div&gt;
);
</code></pre>

<p>If statement here does not work.
When running npm test I get the following error message: </p>

<pre><code>TypeError: Cannot read property 'params' of undefined
</code></pre>

<p>And lastly, the very basics of the test:</p>

<pre><code>import React from ""react"";
import ConnectedBasePage, { BasePage } from ""./basepage"";
import { shallow, mount, render } from ""enzyme"";

describe(""&lt;BasePage/&gt;"", () =&gt; {
    it(""Renders without crashing"", () =&gt; {
        shallow(&lt;BasePage/&gt;);
    });
});
</code></pre>

<p>How to solve this error ?</p>
",https://stackoverflow.com/questions/52228042/enzyme-cannot-read-this-props-match-params-from-componentdidmount,"['reactjs', 'unit-testing', 'redux', 'jestjs', 'enzyme']",1366,TRUE,1,1
Unit test All the Actions Methods in Controller in .Net core visual studio 2017,"<pre><code>public async Task&lt;IActionResult&gt; Create(DonorViewModel be, IFormFile pic)
{
    be.RegCampId = Convert.ToInt32(TempData[""Camp""]);
    if (ModelState.IsValid)
    {
        DONOR entity = new DONOR(); 

        #region Insert Entities
        entity.Address = be.Address;
        entity.BarCode = be.BarCode;
        entity.BloodGroupId = be.BloodGroupId;
        entity.CityId = be.CityId;
        entity.CNIC = be.CNIC;
        entity.DOB = be.DOB;
        entity.Email = be.Email;
        entity.EmergencyContact = be.EmergencyContact;
        entity.FullName = be.FullName;
        entity.GenderId = be.GenderId;
        entity.HomeNo = be.HomeNo;
        entity.IsActive = true;
        entity.IsDeleted = false;
        entity.LastDonDate = be.LastDonDate;
        entity.MaritalStatus = be.MaritalStatus;
        entity.MobileNo = be.MobileNo;
        entity.Occupation = be.Occupation;
        entity.PreDonCount = be.PreDonCount;
        if (be.RegCampId != 0) { entity.RegCampId = be.RegCampId; entity.RegistrationTypeId = 3; }
        if (be.RegLocId != 0) { entity.RegLocId = be.RegLocId; entity.RegistrationTypeId = 2; }
        entity.SignPic = entity.SignPic;
        entity.WhatsApp = be.WhatsApp;
        entity.CreatedBy = (int)HttpContext.Session.GetInt32(""UserId"");
        entity.CreatedDateTime = DateTime.Now;

        #endregion
        flag = await _donorContext.AddAsync(entity);

        if (pic == null || pic.Length &lt;= 0)
            be.Pic = Path.Combine(_hostingEnvironment.WebRootPath, ""images"", ""Avatar.png"").Replace(_hostingEnvironment.WebRootPath, """").Replace(""\\"", ""/"");

        if (pic != null &amp;&amp; pic.Length &gt; 0)
        {
            var path = Path.Combine(new string[]
            {
                _hostingEnvironment.WebRootPath,
                ""Reservoir"",""Donor"",entity.Id.ToString(),
                entity.Id + Path.GetExtension(pic.FileName)
            });
            Directory.CreateDirectory(Path.GetDirectoryName(path));
            using (var stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                pic.CopyTo(stream);
            }
            path = path.Replace(_hostingEnvironment.WebRootPath, """").Replace(""\\"", ""/"");
            entity.Pic = path;

            entity.CreatedBy = entity.CreatedBy;
            entity.CreatedDateTime = entity.CreatedDateTime;
            entity.IsActive = true;
            entity.IsDeleted = false;
            await _donorContext.UpdateAsync(entity);
        }

        if (flag)
        {
            TempData[""Message""] = ""Donor is Added Successfully."";
            if (be.RegCampId != 0)
            {
                return RedirectToAction(""Create"", ""Donor"", new { CampId = be.RegCampId });
            }
            else
            {
                return RedirectToAction(""Create"", ""Donor"");
            }
        }
    }
    ViewData[""RegCampId""] = new SelectList(_context.BLOOD_CAMP, ""Id"", ""City"", be.RegCampId);
    ViewData[""BloodGroupId""] = new SelectList(_bloodGroupContext.GetAll(), ""Id"", ""Value"", be.BloodGroupId);
    ViewData[""CityId""] = new SelectList(_cityContext.GetAll(), ""Id"", ""Name"", be.CityId);
    ViewData[""ScreenedBy""] = new SelectList(_context.EMPLOYEE, ""Id"", ""FirstName"", be.ScreenedBy);
    ViewData[""GenderId""] = new SelectList(_genderContext.GetAll(), ""Id"", ""Name"", be.GenderId);
    ViewData[""RegLocId""] = new SelectList(_locationService.GetAll(), ""Id"", ""Name"",be.RegLocId);

    return View(be);
}
</code></pre>

<p>This is My Create method In Controller How to unit test it using UnitTest.</p>

<pre><code>using HMS_Presentation.Controllers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.VisualStudio.TestTools.UnitTesting;

//Unit Test code .

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

            DonorController Controller = new DonorController();

            ViewResult result = Controller.Create() as ViewResult;

            Assert.AreEqual("""",????);
        }
    }
}
</code></pre>

<p>This is my unit test class code how to use my controller object to check the actions and  test it . WHAT should i write the in the assert . I SEARCH it on internet but do not find any proper solution kindly check the code below and tell me what should i have to write in the assert . i am using visual studio 2017 and .NET CORE 2.0 AND adding a project of unit test in my solution.</p>

<p>The link i followed . 
<a href=""https://learn.microsoft.com/en-us/visualstudio/test/getting-started-with-unit-testing?view=vs-2017"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/visualstudio/test/getting-started-with-unit-testing?view=vs-2017</a></p>
",https://stackoverflow.com/questions/52183222/unit-test-all-the-actions-methods-in-controller-in-net-core-visual-studio-2017,"['unit-testing', 'asp.net-core']",426,FALSE,1,1
How to write a PHP unit test for a method that uses live database data?,"<p>How exactly do I write a test for a method that uses live database?  </p>

<p>Consider this code:</p>

<pre><code>class PricingRepository extends GenericRepository
{
    public function getOptionPrice(int $productId, int $quantity, float $productPrice = 0.0): float
    {
        //retrieves option record for a given product
        $row = $this-&gt;getMySql()-&gt;paramQuery(""
            select * from pricing
            where product_id = ?"", array(
            $productId
        ))-&gt;getSingleArray();

        //based on pricing type computes appropriate value
        if ($row['pricing_type'] === 'Quantity-based')
            return $row['base'] + $row['amount_per_quantity'] * $quantity;
        if ($row['pricing_type'] === 'Percentage-based')
            return $productPrice * $row['percentage'];

        throw new \InvalidArgumentException(""invalid pricing type detected"");
    }
}
</code></pre>

<p>I have A LOT of methods like the one above, and so I want to ensure that my tests are solid and will not change when the database data changes.  I am looking for advice/solution towards best-in-class unit testing method and one that perhaps does not rely on changes of data in the database.  </p>

<p>The way I could write a naive unit test now could be something like this:</p>

<pre><code>use PHPUnit\Framework\TestCase;
class OptionPricingTest extends TestCase
{    
    function setUp()
    {
        $this-&gt;pricingRepository = new PricingRepository();
    }

    function testOptionPricing()
    { 
        $actual_option_price = $this-&gt;pricingRepository-&gt;getOptionPrice(111, 1, 100);
        $this-&gt;assertEquals(10.0, $actual_option_price);
    }
}
</code></pre>

<p>But if the data or pricing type changes, my test will also have to change.</p>
",https://stackoverflow.com/questions/48895827/how-to-write-a-php-unit-test-for-a-method-that-uses-live-database-data,"['php', 'unit-testing', 'phpunit', 'php-7']",5934,TRUE,1,3
Mock up a method with ref parameter to return specific value,"<p>I am using Moq on my .NET Project for Unit Testing my code and
I am trying to mock one of my services which has method with <em>ref</em> parameter and return a specific result.</p>

<p>Service code:</p>

<pre><code>public bool CallServiceFunctionTest(IList&lt;TestObject&gt; test, ref IList&lt;TestObjectErrors&gt; errors)
{
    //...
    return !errors.Any();
}
</code></pre>

<p>Controller code:</p>

<pre><code>var test = _dataUnitOfWork.TestRepository.GetTest(id);
IList&lt;TestObjectErrors&gt; errors = new List&lt;TestObjectErrors&gt;();
var testingResponse = service.CallServiceFunctionTest(test, errors);
</code></pre>

<p>TestController code:</p>

<pre><code>IList&lt;TestObject&gt; fakeObjects = new List&lt;TestObject&gt;()
{
    new TestObject(){Id = 1 , Name = 'Test'}
};

_dataUnitOfWork.Setup(x =&gt; x.TestRepository.GetTest(1, null)).Returns(Task.FromResult(fakeObjects));
IList&lt;TestObjectErrors&gt; errors = new It.IsAny&lt;IList&lt;TestObjectErrors&gt;&gt;();
_service.Setup(x =&gt; x.CallServiceFunctionTest(fakeObjects, ref errors)).Returns(true);
</code></pre>

<p>And also tried with same instances as the real call because of the GitHub moq page:</p>

<pre><code>IList&lt;TestObjectErrors&gt; errors = new List&lt;TestObjectErrors&gt;();
_service.Setup(x =&gt; x.CallServiceFunctionTest(fakeObjects, ref errors)).Returns(true);
</code></pre>

<p>I read some solutions and try with a callback, without specific parameters but I still don't get the 'true' result.I am sure that I am missing something but I don't know what.I tried also the solution in the moq page in GitHub but without result, here is the ref = > <a href=""https://github.com/moq/moq4/wiki/Quickstart"" rel=""nofollow noreferrer"">Moq Quickstart</a></p>
",https://stackoverflow.com/questions/49975399/mock-up-a-method-with-ref-parameter-to-return-specific-value,"['c#', '.net', 'unit-testing', 'mocking', 'moq']",3468,TRUE,1,1
php artisan command to make tests file inside a particular folder,"<p>Currently I have started learning about Unit Testing in Laravel 5.6.
By default my laravel project has a 'tests' directory inside which I have 2 more directories namely, 'Features' and 'Unit'. Each of these directories contain a 'ExampleTest.php'</p>

<pre><code>./tests/Features/ExampleTest.php
./tests/Unit/ExampleTest.php
</code></pre>

<p>Whenever I create new test file using command</p>

<pre><code>php artisan make:test BasicTest
</code></pre>

<p>It always creates the test file inside the 'Features' directory by default, where as I want the file to be created under the 'tests' directory.</p>

<p>Is there a command using which I can specify the path fro creation of the test file.
Something like this</p>

<pre><code>php artisan make:test BasicTest --path=""tests""
</code></pre>

<p>I have already tried the above path command but it is not a valid command.</p>

<p>Do I need to change some code in my phpunit.xml file?</p>
",https://stackoverflow.com/questions/53848176/php-artisan-command-to-make-tests-file-inside-a-particular-folder,"['laravel', 'phpunit']",7480,TRUE,6,2
How to use Appium in NativeScript code sharing project?,"<p>I have a code sharing NativeScript project with Angular that uses Jasmine for unit testing. I'm trying to add <a href=""https://github.com/NativeScript/nativescript-dev-appium"" rel=""nofollow noreferrer"">nativescript-dev-appium</a>, so I can use Appium for UI/e2e testing on web and native platforms. </p>

<p>The resulting setup uses Mocha, which clashes with Jasmine. I get “duplicate identifier” errors because of the duplicate typings, and now I have two frameworks that essentially serve the same purpose (as far as I understand it).</p>

<p>Is it possible to use Jasmine with Appium instead of Mocha? Or do I have to change my unit tests to use Mocha? What is the correct way to set this up?</p>
",https://stackoverflow.com/questions/52414864/how-to-use-appium-in-nativescript-code-sharing-project,"['angular', 'jasmine', 'mocha.js', 'appium', 'nativescript']",167,FALSE,0,1
Visual Studio 2017 native unit testing - reference to project doesn&#39;t work,"<p>I'm using the Visual Studio 2017 native unit testing framework to test a C++ exe project <em>Foo</em> with a test project <em>FooTest</em>. I followed <a href=""https://blogs.msdn.microsoft.com/vcblog/2017/04/19/cpp-testing-in-visual-studio/"" rel=""nofollow noreferrer"">this tutorial</a> to set this up.</p>

<p>I added a reference to Foo to FooTest. I can include Foo's files in FooTest with <code>#include ""..\Foo\Foo.h""</code>. However, it doesn't seem to automatically link with Foo's compiler output, so I get lots of ""unresolved external symbol"" linker errors for things which are declared in <code>Foo.h</code> but defined in <code>Foo.cpp</code>.</p>

<p>Do I manually have to add folders to the project's library folders and link to the compiled output of Foo? Neither the tutorial nor <a href=""https://learn.microsoft.com/en-us/visualstudio/test/writing-unit-tests-for-c-cpp"" rel=""nofollow noreferrer"">the docs</a> indicate anything like that.</p>
",https://stackoverflow.com/questions/48069415/visual-studio-2017-native-unit-testing-reference-to-project-doesnt-work,"['c++', 'unit-testing', 'visual-studio-2017', 'vs-unit-testing-framework']",1584,TRUE,0,1
How to unit test this Angular typescript Http Error Interceptor that catches errors from a piped observable?,"<p>I am running an experiment where I am learning angular and typescript via testing  someone else code (e.g. automated unit and end to end tests). After I get it under test, I plan to repurposes it for a pet project I am working on for a university classroom. </p>

<p>I am at least half way through unit testing the code from here: <a href=""http://jasonwatmore.com/post/2018/05/16/angular-6-user-registration-and-login-example-tutorial"" rel=""noreferrer"">http://jasonwatmore.com/post/2018/05/16/angular-6-user-registration-and-login-example-tutorial</a> </p>

<p>I have been trying for some time to get the following code under unit test but everything I have tried from my own ideas or ideas from the internet have been unsuccessful thus far:</p>

<pre><code>import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from ""@angular/common/http"";
import { AuthenticationService } from ""src/app/authenticationService/AuthenticationService"";
import { Observable, throwError } from ""rxjs"";
import { catchError } from ""rxjs/operators"";
import { Injectable } from ""@angular/core"";

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
    constructor(private authenticationService: AuthenticationService) {}

    intercept(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {
        console.log('before error handle')
        return next.handle(request).pipe(catchError(err =&gt; {

            console.log('in error handle')

            if (err.status === 401) { 
                // auto logout if 401 response returned from api
                this.authenticationService.logout();
                location.reload(true);
            }

            const error = err.error.message || err.statusText;
            return throwError(error);
        }))
    }

}
</code></pre>

<p>The following test code and several variations have been unsuccessful to get the 'in error handle' message to show up in the console log:</p>

<pre><code>import { ErrorInterceptor } from ""./ErrorInterceptor"";
import { of, throwError, defer } from ""rxjs"";

describe('ErrorInterceptor', () =&gt; {
    let errorInterceptor;
    let authenticationServiceSpy;

    beforeEach(() =&gt; {
        authenticationServiceSpy = jasmine.createSpyObj('AuthenticationService', ['logout']);
        errorInterceptor = new ErrorInterceptor(authenticationServiceSpy);
    })

    it('should create', () =&gt; {
        expect(errorInterceptor).toBeTruthy();
    })

    describe('intercept', () =&gt; {
        let httpRequestSpy;
        let httpHandlerSpy;
        const error = {status: 401, statusText: 'error'};

        it('should auto logout if 401 response returned from api', () =&gt; {
            //arrange
            httpRequestSpy = jasmine.createSpyObj('HttpRequest', ['doesNotMatter']);
            httpHandlerSpy = jasmine.createSpyObj('HttpHandler', ['handle']);
            httpHandlerSpy.handle.and.returnValue({
                pipe: () =&gt; {
                return fakeAsyncResponseWithError({});
                }
            });

            //act
            errorInterceptor.intercept(httpRequestSpy, httpHandlerSpy);

            //assert
            //TBD

            function fakeAsyncResponseWithError&lt;T&gt;(data: T) {
                return defer(() =&gt; throwError(error));
            }
        })
    })
})
</code></pre>
",https://stackoverflow.com/questions/53683895/how-to-unit-test-this-angular-typescript-http-error-interceptor-that-catches-err,"['angular', 'typescript', 'unit-testing', 'rxjs']",8147,TRUE,15,1
How to PHPUnit test for general errors like &quot;undefined index&quot;,"<p>Let's say I have this very basic class:</p>

<pre><code>class MyClass {

    private $_counters = [
        'counter1' =&gt; 0,
    ];

    public function plus($counter) {
        $this-&gt;_counters[$counter]++;
    }

}
</code></pre>

<p>Now there's a change to the code so that it doesn't break if the $counter does not exist:</p>

<pre><code>public function plus($counter) {
    if (array_key_exists($counter, $this-&gt;_counters)) {
        $this-&gt;_counters[$counter]++;
    }
}
</code></pre>

<p>How would I go about testing this for a possible regression that results in an ""undefined index"" error being thrown?</p>

<p>Would simply calling the function <code>plus()</code> with a non-existing <code>$counter</code> be enough? When all is good nothing happens but if a regression removed the <code>array_key_exists()</code> check for example, the ""undefined index"" would be thrown.</p>

<p>I'm quite new to unit testing so am I missing a better way to test this situation? It feels a bit weird to write a testcase without asserting something.</p>
",https://stackoverflow.com/questions/49257724/how-to-phpunit-test-for-general-errors-like-undefined-index,"['php', 'phpunit']",2708,TRUE,0,1
Pass multiple &#39;testURL&#39; to jest in react,"<p>I have a class in a react application which I'm unit testing with react. This class has methods that operate on the current url (parsing query params etc.). To be able to mock the url, I'm passing it as a config param like so</p>

<pre><code>""test"": ""react-scripts test --env=jsdom --testURL=https://testurl.com?query=randomQuery""
</code></pre>

<p>This works fine but what I want to be able to do is pass multiple variations of the url to my test class to cover multiple conditions. For example, in addition to the above url, I might additionally want to pass something like</p>

<pre><code>--testURL=https://testurl.com?somethingElse=randomQuery""
</code></pre>

<p>Is there a clean way to pass multiple instances of this to my test class. Possibly by declaring them within the test class itself?</p>
",https://stackoverflow.com/questions/51609080/pass-multiple-testurl-to-jest-in-react,"['javascript', 'reactjs', 'unit-testing', 'jestjs']",736,FALSE,0,0
getting undefined method `_&#39; for #&lt;Puppet::Resource::Catalog::Compiler:0x00000003f03338&gt;,"<p>I am getting:</p>

<pre><code>1) ntpd should contain class ntpd
 Failure/Error: is_expected.to contain_class('ntpd')

 NoMethodError:
   undefined method `_' for 
 &lt;Puppet::Resource::Catalog::Compiler:0x00000003f03338&gt;
</code></pre>

<p>when I run the 'rake spec' command against a puppet unit test file.  The code in the unit test file is simple:</p>

<pre><code>require 'spec_helper'
#require 'shared_contexts'

describe 'ntpd' do

# Pre resource tests

   it 'should contain class ntpd' do
      is_expected.to contain_class('ntpd') 
   end

end
</code></pre>

<p>About 18 months ago this code worked.  I downloaded all the required gems to run the 'rake spec' command recently as I am picking up the puppet unit testing project again and now all I can get is the above error.  I did a bunch of searching online but no one seems to have run into this specific error.  I only end up working with ruby when I work with puppet so my ruby skills are basic.  Any help or direction would be greatly appreciated.</p>
",https://stackoverflow.com/questions/51028562/getting-undefined-method-for-puppetresourcecatalogcompiler0x0000000,"['ruby', 'rspec', 'puppet']",461,TRUE,0,1
Which way of object instance creation is the fastest in TypeScript?,"<p>I have the following 3 different ways of creating an object instance.</p>
<p>I was wondering which of one of these is faster, takes less memory and why?</p>
<pre><code>//Option 1        
export interface Animal1 {
    name: string;
    color: string;
    isHungry: boolean;
}
let animal: Animal1 = {
    name: 'cat',
    color: 'brown',
    isHungry: true
};

//Option 2   
export class Animal2 {
    name: string;
    color: string;
    isHungry: boolean;
}
let animal2: Animal2 = new Animal2();
animal2.name = 'cat';
animal2.color = 'brown';
animal2.isHungry = true;
     
//Option 3   
export class Animal3 {
    constructor(public name:string, public color:string, public isHungry:boolean) {}
}
let animal3 = new Animal3('cat', 'brown', true);
</code></pre>
<p>As of coding style and maintenance I prefer option 1 with builder classes in unit testing. Option 3 is the least favourite as it's:</p>
<ul>
<li>Difficult to create an object easily, you have to set all properties</li>
<li>Difficult to maintain, every time a new property is added you need to update every single instance creation</li>
<li>Error prone, when the number of properties with the same type is high, e.g string, string, string. You may set the wrong property.</li>
</ul>
<p>Is there any performance/memory difference between these three?</p>
",https://stackoverflow.com/questions/51973921/which-way-of-object-instance-creation-is-the-fastest-in-typescript,"['javascript', 'typescript']",1983,TRUE,5,2
Integration Test with Typescript does not call callback into subscribe,"<p>I am writing an integration test to check the API on the backend.</p>

<p>The service 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>export class Service {
    check(details: Credential, successBlock, errorBlock){
        let localString = ""changeAuthenticationCredentialAPI/v2/authenticationCredential/check"";


        let url = BASE_URL_SERVER + localString;
        let body = { details };
        let success = (data) =&gt; { 

            let _authorization = data.headers[""Authorization""];
            let _clientID = data.body.relatedParty[0].id[0].value;
            let _token : Token = {};
            _token.token = _authorization;
            _token.clientId = _clientID;


            successBlock(_token);
        }

        this.post(success,errorBlock,url,body);
    }
    
    handleErrorSync(error) {
        try {
            return Observable.throw(JSON.parse(error._body));
        } catch (e) {
            return Observable.throw(error._body);
        }
    }

    
    post(success, error, url, body) {
        const options = {
            headers: new HttpHeaders(HEADER_REQUEST)
        };

        let call = this.http.post(url, body,options).catch(this.handleErrorSync);
        this.makeCall(call, success, error);
    }

    makeCall(call, success, error) {
        call.flatMap(
            (result) =&gt; {

                if (this.responseIsOk(result)) {

                    return Observable.of(result);
                } else {

                    error(result);
                    return Observable.throw(result);
                }
            }
        ).subscribe(
            (result) =&gt; {

                 success(result); },
            (err) =&gt; {

                this.popupError(err);
                error(err);
            }
        );
    }
 }</code></pre>
</div>
</div>
</p>

<p>On that the integration 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-html lang-html prettyprint-override""><code>describe(""authentication-credential-service.spec"", () =&gt; {
    let backend : Service


    beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
            imports: [
                HttpClientModule,
                HttpClientTestingModule
            ],
            providers: [
                Service,
                { provide: ToastController, useClass: class { ToastController = jasmine.createSpy(""ToastController""); } },
                { provide: ModalController, useClass: class { ModalController = jasmine.createSpy(""ModalController""); } },
                FileTransfer,
                File
            ]
        });

        backend = TestBed.get(Service);
    }));



    it(""should be created"", inject([Service], (service: Service) =&gt; {
        expect(service).toBeTruthy();
    }));


    describe(""check"", () =&gt; {
       it( ""should answer 200 with the right token"", async(inject([Service], (service:Service) =&gt; {
            let credential: Credential = {}; 
            credential.credentialType = ""password"";
            credential.usernameText = ""user"";
            credential.passwordText = ""therightpassword"";
            let _result : Token 
            let successBlock = ( (data) =&gt; { 
                _result = data
                expect(data).toBeDefined();
            } );
            let errorBlock = (error) =&gt; {
                expect(false).toBeTruthy();
            };
            service.check(
                credential,
                successBlock,
                errorBlock
            );
        })));
    });

})</code></pre>
</div>
</div>
</p>

<p>The issue is that running the test the subscribe into the ""makeCall"" method is never called. So basically the test pass but only because no test is run.</p>

<p>The main purpose to use this is to check the consistency with the rest api of my backend but out there I have found only testing with mocked backend or mocked http reponses: perfect for Unit Testing but not for Integration tests.</p>

<p>One more thing: of course debugging the code it works and calls the subscribe.</p>

<p>Any clue? Thanks</p>
",https://stackoverflow.com/questions/50045862/integration-test-with-typescript-does-not-call-callback-into-subscribe,"['angular', 'typescript', 'integration-testing']",88,TRUE,0,1
Testing fetch action in react/redux app,"<p>Im starting with unit testing and Jest. What I want is to test the action's response after fetching some resources from the db.</p>

<p>This is the action code:</p>

<pre><code>export function loadPortlets() {
   return function(dispatch) {
     return portletApi.getAllPortlets().then(response =&gt; {
       dispatch(loadPortletsSuccess(response));
       dispatch(hideLoading());
     }).catch(error =&gt; {
        dispatch({ type: null, error: error });
        dispatch(hideLoading());
        throw(error);
     });
   };
}
</code></pre>

<p>This code is fetching data from:</p>

<pre><code>  static getAllPortlets() {

    return fetch(`${API_HOST + API_URI}?${RES_TYPE}`)
      .then(response =&gt;
        response.json().then(json =&gt; {
          if (!response.ok) {
            return Promise.reject(json);
          }

          return json;
        })
      );
}
</code></pre>

<p>And this is the test:</p>

<pre><code>import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import fetch from 'isomorphic-fetch';
import fetchMock from 'fetch-mock';
import * as actions from '../portletActions';
import * as types from '../actionTypes';

const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);

const mockResponse = (status, statusText, response) =&gt; {
  return new window.Response(response, {
    status: status,
    statusText: statusText,
    headers: {
      'Content-type': 'application/json'
    }
  });
};

describe('async actions', () =&gt; {
  afterEach(() =&gt; {
    fetchMock.reset();
    fetchMock.restore();
  })

  it('calls request and success actions if the fetch response was successful', () =&gt; {
    window.fetch = jest.fn().mockImplementation(() =&gt;
      Promise.resolve(mockResponse(200, null, [{ portlets: ['do something'] }])));

    const store = mockStore({ portlets: []});

    return store.dispatch(actions.loadPortlets())
      .then(() =&gt; {
        const expectedActions = store.getActions();
        expect(expectedActions[0]).toContain({ type: types.LOAD_PORTLETS_SUCCESS });
      })
  });

});
</code></pre>

<p>And this is the result of running the test:</p>

<pre><code>FAIL  src\actions\__tests__\portletActions.tests.js                                                                                                                      
  ● async actions › calls request and success actions if the fetch response was successful                                                                                

    expect(object).toContain(value)                                                                                                                                       

    Expected object:                                                                                                                                                      
      {""portlets"": [// here an array of objects], ""type"": ""LOAD_PORTLETS_SUCCESS""}                                                            
    To contain value:                                                                                                                                                     
      {""type"": ""LOAD_PORTLETS_SUCCESS""}                                                                                                                                   

      at store.dispatch.then (src/actions/__tests__/portletActions.tests.js:56:34)
      at &lt;anonymous&gt;
      at process._tickCallback (internal/process/next_tick.js:188:7)
</code></pre>

<p>In the redux docs for this example (<a href=""https://redux.js.org/recipes/writing-tests"" rel=""nofollow noreferrer"">https://redux.js.org/recipes/writing-tests</a>), they receive a result containing only the action types executed, but I'm getting the <strong>real data</strong> and the action inside the array.</p>

<p>So I'm not sure if the code is wrong, or the test, or both!</p>

<p>Thanks in advance, any help is highly appreciated!</p>
",https://stackoverflow.com/questions/48994613/testing-fetch-action-in-react-redux-app,"['reactjs', 'redux', 'fetch', 'jestjs', 'jest-fetch-mock']",1654,FALSE,0,1
MVC or MVP for location tracking and alert android application,"<p>I am creating a simple personal safety application for students at a University. However having spent several hours researching design patterns, I am still struggling to work out whether MVC or MVP would be better. I understand that MVP allows for better unit testing etc.</p>

<p>However would MVC be enough for this type of application or am I better off going with MVP?</p>

<p>The main features are:</p>

<ul>
<li><p>Users will be able to raise emergency alerts and the application would send the users location to the campus security.</p></li>
<li><p>The user can also make calls to university services through the    application</p></li>
<li><p>The user will be able to find the  nearest bus.</p></li>
</ul>

<p>Thank you</p>
",https://stackoverflow.com/questions/48649262/mvc-or-mvp-for-location-tracking-and-alert-android-application,"['android', 'model-view-controller', 'mobile', 'mvp']",310,FALSE,0,1
Should we mock a static function in unit testing which don&#39;t have further external dependencies(like a function which just do c# calculation)?,"<p>One of my colleagues suggested &amp; also in some forums I found people talking that it's fine if we skip to mock a static function call if that function is not making any server or db calls. But as per theory of Unit testing we should be testing a unit of code only, any external calls out of that class should be mocked.</p>

<p>I am confused as if how the calling class knows that if that static function call is having db call or it's a c# calculation? The mocking should be done independent of consideration that the static function is making call to db or not.</p>
",https://stackoverflow.com/questions/49912778/should-we-mock-a-static-function-in-unit-testing-which-dont-have-further-extern,"['c#', '.net', 'nunit', 'moq']",111,FALSE,0,0
Dynamically populate specific generic properties of a mock object with a specific subclass of the same generic type with Moq,"<p>I'm trying to create a generic class that can build a <code>Mock</code> of a generic interface to assist me with various unit testing functions.</p>

<p>I need the built mock object to have all its <code>DbSet&lt;T&gt;</code> properties populated with  <code>TestDbSet&lt;T&gt;</code> instances (<code>TestDbSet&lt;T&gt;</code> inherits from <code>DbSet&lt;T&gt;</code>).</p>

<p>For a specific example, given the interface:</p>

<pre><code>public interface IAppointmentSchedulerContext
{
    DbSet&lt;ServiceCenter&gt; ServiceCenters { get; set; }
}
</code></pre>

<p>I would like to be able to have my <code>TestDbContextBuilder</code> class construct a mock instance where the <code>ServiceCenters</code> property is populated with an instance of a <code>ServiceCenter&lt;T&gt;</code>.</p>

<p>This is what I have so far:</p>

<pre><code>public class TestDbContextBuilder&lt;TDbContextInterface&gt; where TDbContextInterface : class
{
    public TDbContextInterface Build()
    {
        var mock = new Mock&lt;TDbContextInterface&gt;();
        var dbSetProps = typeof(TDbContextInterface).GetProperties(BindingFlags.Public | BindingFlags.Instance)
                                                    .Where(pi =&gt; pi.PropertyType.IsGenericType &amp;&amp;
                                                                 pi.PropertyType.GetGenericTypeDefinition() ==
                                                                 typeof(DbSet&lt;&gt;));

        //populate all the DbSet&lt;TEntity&gt; properties (in dbSetProps) on the mock with TestDbSet&lt;TEntity&gt; instances

        return mock.Object;
    }
}
</code></pre>

<p>If I were doing this statically, outside of the generic builder, I would just do this:</p>

<pre><code>mock.SetupProperty(m=&gt;m.ServiceCenters).Returns(new TestDbSet&lt;ServiceCenter&gt;());
</code></pre>

<p>But how do this dynamically, for all the <code>DbSet&lt;&gt;</code> properties on the generic <code>TDbContextInterface</code> interface?</p>
",https://stackoverflow.com/questions/48345086/dynamically-populate-specific-generic-properties-of-a-mock-object-with-a-specifi,"['c#', 'generics', 'reflection', 'moq']",370,TRUE,0,1
How test driven development is done in Spring?,"<p>As I mentioned in the title, I'm interested in how TDD is done in Spring. I am quite new to the notion of unit testing. I've read some articles about TDD. It is said that in TDD, first the tests are written based on requirements, they fail, then with the correct implementation, they succeed. But what should be tested in Spring? The main question is how they should be tested. I have no clue about how I should start, how to evaluate that what should be tested. I am searching for correct methods or conventions to write test-driven code if there's any.</p>

<p>Thanks in advance</p>
",https://stackoverflow.com/questions/52233461/how-test-driven-development-is-done-in-spring,"['spring', 'unit-testing', 'tdd']",109,TRUE,0,1
can&#39;t patch nested values from django rest framework,"<p>I am trying to develop a REST API with django-rest-framework for updating a django model.</p>

<p>I want to unit test it with the following unit test</p>

<pre><code>from rest_framework.test import APITestCase
class PatchInvestmentTest(APITestCase):

    def test_repartition(self):

        investment = Investment.objects.create()
        sponsor1 = Investment.objects.create(InvestmentSponsor, name='A')
        sponsor2 = Investment.objects.create(InvestmentSponsor, name='B')

        url = reverse('investments:investments-detail', args=[investment.id])
        data = {
            'sponsorships': [
                {'sponsor': sponsor1.id, 'percentage': 80},
                {'sponsor': sponsor2.id, 'percentage': 10},
            ]
        }

        print(""&gt; data"", data)

        response = self.client.patch(url, data=data)

        self.assertEqual(response.status_code, status.HTTP_200_OK)

        self.assertEqual(1, Investment.objects.count())
        investment = Investment.objects.all()[0]
        # It fails below : no investments are created
        self.assertEqual(len(investment.sponsorships()), 2) 
</code></pre>

<p>The model can be summed up with</p>

<pre><code>class Investment(models.Model):
    # ... a few fields

    def sponsorships(self):
        return self.investmentsponsorship_set.all().order_by('sponsor__ordering', 'sponsor__name')


class InvestmentSponsor(models.Model):
    name = models.CharField(max_length=200, verbose_name=_('name'))
    ordering = models.IntegerField(default=0)

    class Meta:
        ordering = ('ordering', 'name', )


class InvestmentSponsorship(models.Model):
    sponsor = models.ForeignKey(InvestmentSponsor)
    investment = models.ForeignKey(Investment)
    percentage = models.DecimalField(max_digits=5, decimal_places=2)
</code></pre>

<p>The api is using rest-framework base classes</p>

<pre><code>class InvestmentViewSet(viewsets.ModelViewSet):
    model = Investment

    def get_serializer_class(self):
        serializers_class_map = {
            'default': InvestmentSerializer,
            'partial_update': PartialUpdateInvestmentSerializer,
        }
        return serializers_class_map.get(self.action, serializers_class_map['default'])

    def perform_update(self, serializer):
         serializer.save()
</code></pre>

<p>Then I expect to get and handle the ""sponsorhips"" data in the serializers</p>

<pre><code>class InvestmentSponsorshipSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.InvestmentSponsorship
        fields = ('sponsor', 'percentage', )


class PartialUpdateInvestmentSerializer(serializers.ModelSerializer):
    sponsorships = InvestmentSponsorshipSerializer(many=True)

    class Meta:
        model = models.Investment
        fields = (
            'id', '... others', 'sponsorships',
        )

    def validate_sponsorships(self, value):
        print(""validate_sponsorships"", value)
        return value

    def update(self, instance, validated_data):
        """"""update only fields in data""""""

        data = validated_data.copy()

        print(""*** DATA"", validated_data)

        instance.save()

        return instance
</code></pre>

<p>The problem is that the data I received from the serializer is empty</p>

<pre><code> &gt; data {'sponsorships': [{'sponsor': 1, 'percentage': 80}, {'sponsor': 2, 'percentage': 10}]}
 validate_sponsorships []
 *** DATA {'sponsorships': []}
</code></pre>

<p><strong>This seems to occur only when unit testing</strong>. It seems to work from the dango-rest-framework admin.</p>

<p>I've tried to investigate why I don't received the data as validated_data in the update with no success yet.</p>

<p>Any idea? </p>
",https://stackoverflow.com/questions/48307041/cant-patch-nested-values-from-django-rest-framework,"['python', 'django', 'unit-testing', 'django-rest-framework']",898,TRUE,0,2
how can i test a computed property in vuejs using jest?,"<p>im still new with unit testing and i want to test if the a linked button is displayed when the <code>isLinkPresent</code> computed property return the link of the image and is not empty of this component :</p>

<pre><code>    &lt;template lang=""pug""&gt;
    .merchandising_image_title
  .image(:style=""`background-image: url('${imageTitle.image}');`"" )
  .panel
    .top
      h2 {{imageTitle.top_title}}
      .line
    .center
      h1 {{imageTitle.center_title}}
    .bottom(v-if=""isLinkPresent"")
      a.btn.round( target='_blank' :href='imageTitle.link') Notify Me By Email
    &lt;/template&gt;
    &lt;script&gt;
    export default {
      name: 'MerchandisingImageTitle',
      props: {
        imageTitle: Object
      },
      computed:{
        isLinkPresent(){
          return this.imageTitle.link &amp;&amp; this.imageTitle.link !== ''
        }
      }
    }
    &lt;/script&gt;
</code></pre>

<p>i have tried to test it like this by overwriting the computed property :</p>

<pre><code>    it(""renders linked button when image title has a link and is not empty"", () =&gt; {
  const wrapper = mount(ImageTitle, {
    propsData: {
      imageTitle: Object
    },
    computed: {
      isLinkPresent() {
        return this.imageTitle.link &amp;&amp; this.imageTitle.link !== """";
      }
    }
  });
  expect(wrapper.find(""a"").isVisible()).toBe(true);
});
</code></pre>

<p>but it gave me this error:</p>

<pre><code>[vue-test-utils]: find did not return a, cannot call isVisible() on empty Wrapper

  13 |     }
  14 |   });
&gt; 15 |   expect(wrapper.find(""a"").isVisible()).toBe(true);
     |                            ^
  16 | });
</code></pre>

<p>im not sure what am i doing wrong, any help would be appreciated</p>

<p>edit : okay so i realised i didnt pass the propsData correctly so i changed it to <code>propsData: { imageTitle: { imageTitleData: { image: """", top_title: """", center_title: """", link: """"}}}</code> and do <code>expect(wrapper.find("".bottom"").exists()).toBe(true)</code> as that isVisible() is used mostly in v-show but still getting this error : `
    renders linked button when image title has a link and is not empty</p>

<pre><code>    expect(received).toBe(expected) // Object.is equality

    Expected: true
    Received: false

      20 |     }
      21 |   });
    &gt; 22 |   expect(wrapper.find("".bottom"").exists()).toBe(true);
         |                                            ^
      23 | });
      24 |`
</code></pre>
",https://stackoverflow.com/questions/53763440/how-can-i-test-a-computed-property-in-vuejs-using-jest,"['javascript', 'unit-testing', 'vue.js', 'jestjs']",13258,TRUE,4,2
How to watch mocha-webpack tests results in mocha-test-explorer VS Code Extension?,"<p>I'm working on a just created Vue cli project with TypeScript and unit testing.</p>

<p>I Know that Vue cli tests uses <a href=""https://zinserjan.github.io/mocha-webpack/"" rel=""nofollow noreferrer"">mocha-webpack</a> to runt tests. And when I Type <code>mocha-webpack</code> on terminal, the tests runs ok.</p>

<p>But I would like to use an <a href=""https://marketplace.visualstudio.com/items?itemName=hbenl.vscode-mocha-test-adapter"" rel=""nofollow noreferrer"">mocha-test-explorer, a VS Code extension for mocha testing</a>. For a better programming experience.</p>

<p>I Installed the extension and configured like this:</p>

<pre><code>""mochaExplorer.files"": ""tests/**/*.ts"",
""mochaExplorer.require"": ""ts-node/register""
</code></pre>

<p>But I'm still not able to see the tests. test-explorer shows the fallowing output:</p>

<pre><code>(function (exports, require, module, __filename, __dirname) { import { expect } from 'chai'
                                                              ^^^^^^
SyntaxError: Unexpected token import
</code></pre>

<p>I know that is because mocha is not loading files through webpack.</p>

<p><strong>What should I do to see <a href=""https://zinserjan.github.io/mocha-webpack/"" rel=""nofollow noreferrer"">mocha-webpack</a> tests in the <a href=""https://marketplace.visualstudio.com/items?itemName=hbenl.vscode-mocha-test-adapter"" rel=""nofollow noreferrer"">mocha-test-explorer</a> extension (or any other gui extension) for VSCode?</strong></p>
",https://stackoverflow.com/questions/53415341/how-to-watch-mocha-webpack-tests-results-in-mocha-test-explorer-vs-code-extensio,"['visual-studio-code', 'mocha.js', 'vue-cli', 'test-explorer', 'mocha-webpack']",524,FALSE,4,0
Using Interfaces with UserManager on Moq,"<p>So, I'm trying to do some unit testing with xunit, and I need to mock an interface where it's repository uses UserManager. I think what is happening here is that the UserManager is not getting initialized when I'm doing the unit tests, because if I run the App it works fine.</p>

<p>IUserRepository interface:</p>

<pre><code>public interface IUserRepository : IDisposable
    {
        Task&lt;List&lt;ApplicationUser&gt;&gt; ToListAsync();
        Task&lt;ApplicationUser&gt; FindByIDAsync(string userId);
        Task&lt;ApplicationUser&gt; FindByNameAsync(string userName);
        Task&lt;IList&lt;string&gt;&gt; GetRolesAsync(ApplicationUser user);
        Task AddToRoleAsync(ApplicationUser user, string roleName);
        Task RemoveFromRoleAsync(ApplicationUser user, string roleName);
        Task&lt;bool&gt; AnyAsync(string userId);
        Task AddAsync(ApplicationUser user);
        Task DeleteAsync(string userId);
        void Update(ApplicationUser user);
        Task SaveChangesAsync();
    }
</code></pre>

<p>UserRepository:</p>

<pre><code>public class UserRepository : IUserRepository
    {
        private readonly ApplicationDbContext _context;
        private readonly UserManager&lt;ApplicationUser&gt; _userManager;

        public UserRepository(ApplicationDbContext context, UserManager&lt;ApplicationUser&gt; userManager)
        {
            _context = context;
            _userManager = userManager;
        }

        public Task&lt;ApplicationUser&gt; FindByIDAsync(string userId)
        {
            return _context.ApplicationUser.FindAsync(userId);
        }

        public Task&lt;ApplicationUser&gt; FindByNameAsync(string userName)
        {
            return _context.ApplicationUser.SingleOrDefaultAsync(m =&gt; m.UserName == userName);
        }

        public Task&lt;List&lt;ApplicationUser&gt;&gt; ToListAsync()
        {
            return _context.ApplicationUser.ToListAsync();
        }

        public Task AddAsync(ApplicationUser user)
        {
            _context.ApplicationUser.AddAsync(user);
            return _context.SaveChangesAsync();
        }

        public void Update(ApplicationUser user)
        {
            _context.Entry(user).State = EntityState.Modified;
        }

        public Task DeleteAsync(string userId)
        {
            ApplicationUser user = _context.ApplicationUser.Find(userId);
            _context.ApplicationUser.Remove(user);
            return _context.SaveChangesAsync();
        }

        public Task&lt;IList&lt;string&gt;&gt; GetRolesAsync(ApplicationUser user)
        {
            return _userManager.GetRolesAsync(user);
        }

        public Task AddToRoleAsync(ApplicationUser user, string roleName)
        {
            _userManager.AddToRoleAsync(user, roleName);
            return _context.SaveChangesAsync();
        }

        public Task RemoveFromRoleAsync(ApplicationUser user, string roleName)
        {
            _userManager.RemoveFromRoleAsync(user, roleName);
            return _context.SaveChangesAsync();
        }

        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);
        }

        public Task&lt;bool&gt; AnyAsync(string userId)
        {
            return _context.ApplicationUser.AnyAsync(e =&gt; e.Id == userId);
        }

        public Task SaveChangesAsync()
        {
            return _context.SaveChangesAsync();
        }
    }
</code></pre>

<p>UserController (Just the Index):</p>

<pre><code>public class UserController : CustomBaseController
    {
        private readonly IUserRepository _userRepository;
        private readonly IRoleRepository _roleRepository;

        public UserController(IUserRepository userRepository,IRoleRepository roleRepository)
        {
            _userRepository = userRepository;
            _roleRepository = roleRepository;
        }

        // GET: User
        public async Task&lt;IActionResult&gt; Index()
        {
            List&lt;ApplicationUser&gt; ListaUsers = new List&lt;ApplicationUser&gt;();
            List&lt;DadosIndexViewModel&gt; ListaUsersModel = new List&lt;DadosIndexViewModel&gt;();
            List&lt;Tuple&lt;ApplicationUser, string&gt;&gt; ListaUserComRoles = new List&lt;Tuple&lt;ApplicationUser, string&gt;&gt;();
            var modelView = await base.CreateModel&lt;IndexViewModel&gt;(_userRepository);

            ListaUsers = await _userRepository.ToListAsync();

            foreach(var item in ListaUsers)
            {
                //Por cada User que existir na ListaUsers criar um objecto novo?
                DadosIndexViewModel modelFor = new DadosIndexViewModel();

                //Lista complementar para igualar a modelFor.Roles -&gt; estava a dar null.
                var tempList = new List&lt;string&gt;();

                //Inserir no Objeto novo o user.
                modelFor.Nome = item.Nome;
                modelFor.Email = item.Email;
                modelFor.Id = item.Id;
                modelFor.Telemovel = item.PhoneNumber;

                //Buscar a lista completa de roles por cada user(item).
                var listaRolesByUser = await _userRepository.GetRolesAsync(item);

                //Por cada role que existir na lista comp
                foreach (var item2 in listaRolesByUser)
                    {
                        //Não é preciso isto mas funciona. Array associativo.
                        ListaUserComRoles.Add(new Tuple&lt;ApplicationUser, string&gt;(item, item2));
                        //Adicionar cada role à lista
                        tempList.Add(item2);
                    }
                modelFor.Roles = tempList;
                //Preencher um objeto IndexViewModel e adiciona-lo a uma lista até ter todos os users.
                ListaUsersModel.Add(modelFor);
            }
        //Atribuir a lista de utilizadores à lista do modelo (DadosUsers)
        modelView.DadosUsers = ListaUsersModel;
        //return View(ListaUsersModel);
        return View(modelView);
    }
</code></pre>

<p>And the Test:</p>

<pre><code>public class UserControllerTest
    {
        [Fact]
        public async Task Index_Test()
        {

            // Arrange
            var mockUserRepo = new Mock&lt;IUserRepository&gt;();
            mockUserRepo.Setup(repo =&gt; repo.ToListAsync()).Returns(Task.FromResult(getTestUsers()));
            var mockRoleRepo = new Mock&lt;IRoleRepository&gt;();
            mockRoleRepo.Setup(repo =&gt; repo.ToListAsync()).Returns(Task.FromResult(getTestRoles()));

            var controller = new UserController(mockUserRepo.Object, mockRoleRepo.Object);

            controller.ControllerContext = new ControllerContext
            {
                HttpContext = new DefaultHttpContext
                {
                    User = new ClaimsPrincipal(new ClaimsIdentity())
                }
            };
            // Act
            var result = await controller.Index();

            // Assert
            var viewResult = Assert.IsType&lt;ViewResult&gt;(result);
            var model = Assert.IsAssignableFrom&lt;IndexViewModel&gt;(viewResult.ViewData.Model);
            Assert.Equal(2,model.DadosUsers.Count);
        }

        private List&lt;ApplicationUser&gt; getTestUsers()
        {
            var Users = new List&lt;ApplicationUser&gt;();

            Users.Add(new ApplicationUser()
            {
                Nome = ""Leonardo"",
                UserName = ""leonardo@teste.com"",
                Email = ""leonardo@teste.com"",
                PhoneNumber= ""911938567""
            });

            Users.Add(new ApplicationUser()
            {
                Nome = ""José"",
                UserName = ""José@teste.com"",
                Email = ""José@teste.com"",
                PhoneNumber = ""993746738""
            });

            return Users;
        }

        private List&lt;IdentityRole&gt; getTestRoles()
        {
            var roles = new List&lt;IdentityRole&gt;();

            roles.Add(new IdentityRole()
            {
                Name = ""Admin"",
                NormalizedName = ""ADMIN""
            });
            roles.Add(new IdentityRole()
            {
                Name = ""Guest"",
                NormalizedName = ""GUEST""
            });

            return roles;
        }
    }
</code></pre>

<p>So the problem is: On UserController I have <code>var listaRolesByUser = await _userRepository.GetRolesAsync(item);</code> and when the app it works fine, but when I'm running the test the <code>GetRolesAsync()</code> method returns null, or the <code>listaRolesByUser</code> doesn't get initialized.</p>

<p>Sorry if this looks a bit confusing, I don't know if this is the correct way of doing this but this is what I learned so far.</p>
",https://stackoverflow.com/questions/49136871/using-interfaces-with-usermanager-on-moq,"['c#', 'asp.net-mvc', 'entity-framework', 'unit-testing', 'asp.net-identity']",1098,TRUE,4,1
Xcode 9.4.1 Code Coverage on &#39;guard&#39; statement,"<p>Having a bit of trouble getting 100% code coverage after implementing Unit Tests in my Swift 4 project in Xcode 9.4.1.</p>

<p>For some reason, when I have a <code>guard</code> statement in a failable initializer, my code coverage always seems to say <code>0</code> for it, even though I <em>do</em> test for it.</p>

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

<p><a href=""https://gitlab.com/dansinclair25/guard-test-example"" rel=""nofollow noreferrer"">I've created a demo project so you can see for yourselves.</a></p>

<p>How do I get Xcode to show that this code is covered with unit tests?</p>

<p>I'm relatively new to the whole Unit Testing side of things, so if there's any advice you can give, or any other places to check out to read up on it, I would be grateful.</p>

<p>Thanks in advance.</p>

<p>/Dan</p>
",https://stackoverflow.com/questions/51596895/xcode-9-4-1-code-coverage-on-guard-statement,"['swift', 'xcode', 'unit-testing', 'code-coverage']",470,TRUE,4,1
Test ionic app with real http requests - Integration Test,"<p>I want to test my app and I am not sure which kind of test to use for which purpose.</p>

<p>I have an app that loads a page with the given data, then starts a http request (with a provider) to load and update the data in the view. If you click on some piece of data, the next page gets the data already there and then loads the rest and updates and so on. I want to test the update functions and the http requests.</p>

<p>I want to test my app from end to end, so I tried using e2e testing (with pretractor). But I found no way to check the data in the background, e.g. the data comming back from the server or the data held in my data model. Besides, my information is that the e2e test should be used for UI testing rather than function testing.</p>

<p>So I tried unit-testing (with Jasmine and Karma). I can access the right functions and variables, but I found no way to use the real http requests (not mockups) for my tests. Furthermore I need the result from the last page to send the right http request for the current page and I understand that this is not what unit testing is supposed to do.</p>

<p>I think I need some kind of integration test, but I have no idea how to implement this with ionic 3. 
So: Which test should I use and how to use it to to what I need?</p>
",https://stackoverflow.com/questions/49193878/test-ionic-app-with-real-http-requests-integration-test,"['angular', 'testing', 'ionic-framework', 'jasmine', 'protractor']",458,TRUE,0,1
Automapper in xUnit testing and .NET Core 2.0,"<p>I have .NET Core 2.0 Project which contains Repository pattern and xUnit testing.</p>

<p>Now, here is some of it's code.</p>

<p><strong>Controller:</strong></p>

<pre><code>public class SchedulesController : Controller
{
    private readonly IScheduleRepository repository;
    private readonly IMapper mapper;

    public SchedulesController(IScheduleRepository repository, IMapper mapper)
    {
        this.repository = repository;
        this.mapper = mapper;
    }

    [HttpGet]
    public IActionResult Get()
    {
        var result = mapper.Map&lt;IEnumerable&lt;Schedule&gt;, IEnumerable&lt;ScheduleDto&gt;&gt;(source: repository.items);
        return new OkObjectResult(result);
    }
}
</code></pre>

<p><strong>My Test Class:</strong></p>

<pre><code>public class SchedulesControllerTests
{
    [Fact]
    public void CanGet()
    {
        try
        {
            //Arrange
            Mock&lt;IScheduleRepository&gt; mockRepo = new Mock&lt;IScheduleRepository&gt;();
            mockRepo.Setup(m =&gt; m.items).Returns(new Schedule[]
            {
                new Schedule() { Id=1, Title = ""Schedule1"" },
                new Schedule() { Id=2, Title = ""Schedule2"" },
                new Schedule() { Id=3, Title = ""Schedule3"" }
            });

            var mockMapper = new Mock&lt;IMapper&gt;();
            mockMapper.Setup(x =&gt; x.Map&lt;Schedule&gt;(It.IsAny&lt;ScheduleDto&gt;()))
                .Returns((ScheduleDto source) =&gt; new Schedule() { Title = source.Title });

            SchedulesController controller = new SchedulesController(repository: mockRepo.Object, mapper: mockMapper.Object);

            //Act
            var result = controller.Get();

            //Assert
            var okResult = result as OkObjectResult;
            Assert.NotNull(okResult);

            var model = okResult.Value as IEnumerable&lt;ScheduleDto&gt;;
            Assert.NotNull(model);

        }
        catch (Exception ex)
        {
            //Assert
            Assert.False(false, ex.Message);
        }
    }
}
</code></pre>

<p><strong>Issue I Am facing.</strong></p>

<p>My Issue is that when I run this code with database context and execute <code>Get()</code> method, it works fine, it gives me all results.</p>

<p>But when I tries to run test case, it's not returning any data of Dto object.
When I debugged I found that</p>

<ol>
<li><p>I am getting my test object in controller using <code>mockRepo</code>.</p></li>
<li><p>But it looks like Auto mapper is not initialized correctly, because while mapping it's not returning anything in</p>

<p><code>var result = mapper.Map&lt;IEnumerable&lt;Schedule&gt;, IEnumerable&lt;ScheduleDto&gt;&gt;(source: repository.items);</code></p></li>
</ol>

<p><strong>What I tried So Far?</strong></p>

<p>I followed all this answers but still it's not working.</p>

<p><a href=""https://stackoverflow.com/questions/22984530/mocking-mapper-map-in-unit-testing"">Mocking Mapper.Map() in Unit Testing</a></p>

<p><a href=""https://stackoverflow.com/questions/29605470/how-to-mock-a-list-transformation-using-automapper"">How to Mock a list transformation using AutoMapper</a></p>

<p>So, I need help from someone who is good in xUnit and automapper, and need guidance on how to initialize mock Mapper correctly.</p>
",https://stackoverflow.com/questions/49934707/automapper-in-xunit-testing-and-net-core-2-0,"['c#', 'unit-testing', 'automapper', 'asp.net-core-2.0', 'xunit']",29399,TRUE,23,2
How to list all component properties,"<p>I want to list all the component properties (both private and public) in angular.</p>

<p>I have tried the following</p>

<pre><code>ngOnInit() {
    console.log(this.constructor.prototype);
}
</code></pre>

<p>But this is printing only the properties that have <code>getter</code> methods defined. It is not printing the properties which do not have <code>getters</code> or <code>setters</code>. It also prints component <code>methods</code> which I am not bothered.</p>

<p>Strange part is, it is not even displaying the public properties (which do not have getters).</p>

<p>Even I tried doing </p>

<pre><code>console.log(this.constructor.prototype.hasOwnProperty('_queryState'));
</code></pre>

<p>But it returns me <code>false</code>, which means it was not able to identify the property.</p>

<p>This <a href=""https://stackoverflow.com/questions/684672/how-do-i-loop-through-or-enumerate-a-javascript-object"">question</a> does not help me though.</p>

<p>How do I list all the properties?</p>

<p>If anyone is asking me why do I need to do this, it is for unit testing.</p>
",https://stackoverflow.com/questions/50700607/how-to-list-all-component-properties,"['angular', 'unit-testing', 'typescript', 'properties']",1035,FALSE,3,1
"In YamlDotNet, how can I deserialize a getter-only property?","<p>I would like to serialize/deserialize objects that have readonly private fields with public getter-only properties, whose readonly fields are set in the objects' constructor. However, the following code fails in unit testing:</p>

<pre><code>using System.ComponentModel;
using FluentAssertions;
using Xunit;
using YamlDotNet.Serialization;

namespace Utilities.ComputerInventory {

    public class CPU {
        readonly CPUMaker cPUMaker;
        public CPU() : this(CPUMaker.Generic) { }
        public CPU(CPUMaker cPUMaker) {
            this.cPUMaker = cPUMaker;
        }
        public CPUMaker CPUMaker =&gt; cPUMaker;
    }

    public enum CPUMaker {
        [Description(""Generic"")]
        Generic,
        [Description(""Intel"")]
        Intel,
        [Description(""AMD"")]
        AMD
    }
}

namespace Utilities.ComputerInventory.UnitTests {

    public class ComputerInventoryUnitTests001 {

        [Fact]
        public void CPUDeserializeFromYAMLSO() {
            Serializer serializer = new SerializerBuilder().Build();
            Deserializer deserializer = new DeserializerBuilder().Build();
            CPU cPU = new CPU(CPUMaker.Intel);
            CPU cPUAfterRoundTrip = deserializer.Deserialize&lt;CPU&gt;(serializer.Serialize(cPU));
            cPUAfterRoundTrip.Should().Be(cPU);
        }
    }
}
</code></pre>

<p>This fails with the message ""Test Failed""</p>

<pre><code>Message: YamlDotNet.Core.YamlException : (Line: 1, Col: 1, Idx: 0) - (Line: 1, Col: 1, Idx: 0): Exception during deserialization
---- System.Runtime.Serialization.SerializationException : Property 'CPUMaker' not found on type 'Utilities.ComputerInventory.CPU'.
</code></pre>

<p>And  stack trace showing
</p>

<pre><code>Test Name:  CPUDeserializeFromYAMLSO
Test FullName:  Utilities.ComputerInventory.UnitTests.ComputerInventoryUnitTests001.CPUDeserializeFromYAMLSO
Test Source:    &lt;obfuscated&gt;\test1.cs
Test Outcome:   Failed
Test Duration:  0:00:00.11

Result StackTrace:  
at YamlDotNet.Serialization.ValueDeserializers.NodeValueDeserializer.DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer)
   at YamlDotNet.Serialization.ValueDeserializers.AliasValueDeserializer.DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer)
   at YamlDotNet.Serialization.Deserializer.Deserialize(IParser parser, Type type)
   at YamlDotNet.Serialization.Deserializer.Deserialize(TextReader input, Type type)
   at YamlDotNet.Serialization.Deserializer.Deserialize[T](String input)
   at Utilities.ComputerInventory.UnitTests.ComputerInventoryUnitTests001.CPUDeserializeFromYAMLSO() in &lt;obfuscated&gt;\test1.cs:line 43
----- Inner Stack Trace -----
   at YamlDotNet.Serialization.TypeInspectors.TypeInspectorSkeleton.GetProperty(Type type, Object container, String name, Boolean ignoreUnmatched)
   at YamlDotNet.Serialization.NodeDeserializers.ObjectNodeDeserializer.YamlDotNet.Serialization.INodeDeserializer.Deserialize(IParser parser, Type expectedType, Func`3 nestedObjectDeserializer, Object&amp; value)
   at YamlDotNet.Serialization.ValueDeserializers.NodeValueDeserializer.DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer)
Result Message: 
YamlDotNet.Core.YamlException : (Line: 1, Col: 1, Idx: 0) - (Line: 1, Col: 1, Idx: 0): Exception during deserialization
---- System.Runtime.Serialization.SerializationException : Property 'CPUMaker' not found on type 'Utilities.ComputerInventory.CPU'.
</code></pre>

<p>Simply serializing the cPU instance of the CPU object produces YAML that looks like this: <code>""CPUMaker: Intel\r\n""</code></p>

<p>There appears to be a similar SO question (<a href=""https://stackoverflow.com/questions/41300528/yamldotnet-can-not-find-property"">YamlDotNet can not find property</a>), asked 12/23/16 (13 months ago), but no one has answered or commented.</p>

<p>Summary: Using YamlDotNet, what is the proper way to serialize/deserialize objects with getter-only properties backed by a readonly field?</p>

<p>TIA for any help!</p>
",https://stackoverflow.com/questions/48677081/in-yamldotnet-how-can-i-deserialize-a-getter-only-property,"['c#', 'deserialization', 'getter', 'yamldotnet']",1135,FALSE,3,0
SoapServer::SoapServer() - SSL3_GET_SERVER_CERTIFICATE:certificate verify failed,"<p>Is there any way to create PHP SoapServer with local secure WSDL URL using self-signed SSL certificate? Following code:</p>

<pre><code>$soapServer = new SoapServer(""https://mysite.local/my-document?wsdl"");
</code></pre>

<p>throws always exception:</p>

<blockquote>
  <p>SoapServer::SoapServer(): SSL operation failed with code 1. OpenSSL
  Error messages:  error:14090086:SSL
  routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
  (/var/www/app/modules/generators/components/WsSoap.php:110)</p>
</blockquote>

<p>I could not find anything on how to turn off SSL validation for SoapServer. 
Most of issues are related to SoapClient, which is not the case. 
I also want to avoid installing any ca.pem local files with valid certificates, because it would be difficult on many servers, just need to create SoapServer for one-time unit testing, don't care about valid/invalid local domain. Using PHP 7.0.19. Thank you.</p>
",https://stackoverflow.com/questions/51133940/soapserversoapserver-ssl3-get-server-certificatecertificate-verify-failed,"['php', 'soap', 'soapserver']",263,FALSE,2,0
Rails + RSpec - Integration Testing (Recommendations),"<p>I have a Vue app with a rails backend and I want to do some front-end/integration testing. I'm currently using <code>vue-router</code> and <code>turbolinks</code> on the front-end and <code>RSpec</code> for unit testing. </p>

<p>I tried using <code>Capybara</code> but <code>puma</code> always give me a routing error when a link is clicked and trying to get a route instead of having the vue router handle rendering the component. With the help of others, we suspect it's either that vue router is not loaded properly or turbolinks is interfering in some way. Does anyone have any suggestions on how to configure Capybara for this situation?</p>

<p>Or does anyone have recommendations on other tools/libraries that I can use for testing?</p>
",https://stackoverflow.com/questions/50437557/rails-rspec-integration-testing-recommendations,"['ruby-on-rails', 'vue.js', 'rspec', 'capybara', 'vue-router']",210,FALSE,2,0
I&#39;m falling in overtesting feature,"<p>I'm fresh in the world of unit testing / integration testing. And I have read that, to write good unit tests for methods and classes, you must put yourself in the context that you don't know much about the method implementation, and focus on the method interface and logic</p>

<blockquote>
  <p>for example methode <code>add</code> take 2 params and return the sum of its</p>
</blockquote>

<p>So here is a real life example of a method that I had to write tests for:</p>

<pre><code>  matchLeague(summoner: SummonerTeammate): boolean {

    // check that maximum difference between summoners tiers is one tier
    if(Math.abs(this.summoner_league_info.tier - summoner.summoner_league_info.tier) &gt; 1) {
      return false
    }

    return true;
  }
</code></pre>

<p>And here are the tests that I have written:</p>

<pre><code>describe('match league algorithme', () =&gt; {

    function matchingHelper(tier1, tier2, excp) {
      let sum1: SummonerTeammate = new SummonerTeammate({
        summoner_league_info: {
          tier: tier1,
        }
      })

      let sum2: SummonerTeammate = new SummonerTeammate({
        summoner_league_info: {
          tier: tier2,
        }
      });

      expect(sum1.matchLeague(sum2)).toBe(excp)
    }

    test('should return true if players are in same tier', () =&gt; {
      matchingHelper(1, 1, true)
    })

    test('should return true if player1 is 1 tier below player 2 tier', () =&gt; {
      matchingHelper(1, 2, true)
    })

    test('should return true if player1 is 1 tier above player 2 tier', () =&gt; {
      matchingHelper(2, 1, true)
    })

    test('should return false if player 1 is more than 1 tier above player 2', () =&gt; {
      matchingHelper(3, 1, false)
      matchingHelper(7, 1, false)
      matchingHelper(6, 1, false)
    })

    test('should return false if player 1 is more than 1 tier below player 2', () =&gt; {
      matchingHelper(4, 6, false)
      matchingHelper(2, 6, false)
      matchingHelper(1, 6, false)
    })
  })
</code></pre>

<p>So, what I want to know, is that if my test suite is good for this methode, or I'm testing too much or too little case.</p>
",https://stackoverflow.com/questions/50204072/im-falling-in-overtesting-feature,"['javascript', 'unit-testing', 'typescript']",45,FALSE,2,0
Swift dependency injection by passing class as a function parameter to call a class method,"<p>I may be approaching this the wrong way, but I would like to introduce dependency injection for unit testing purposes, and in order to do so I would need to pass a class as a parameter. In somewhat of a pseudo code it should look like this:</p>

<pre><code>protocol LocalSavingProtocol {
    static func saveDataLocally()
}

class ProductionClass: LocalSavingProtocol {
    static func saveDataLocally() {
        print(""actually save data"")
    }
}

class TestClass: LocalSavingProtocol {
    static func saveDataLocally() {
        print(""test saving data"")
    }
}

func saveEverywhere(injecting localSavingClass: LocalSavingProtocol = ProductionClass) {
    localSavingClass.saveDataLocally()
}

//production code
saveEverywhere()

//test
saveEverywhere(injecting: TestClass)
</code></pre>

<p>Obviously this does not work, and as much as I tried playing around with passing <code>.Type</code> or <code>.self</code>, changing the <code>saveEverywhere</code> function to</p>

<pre><code>saveEverywhere&lt;T: LocalSavingProtocol&gt;(injecting localSavingClass: T)
</code></pre>

<p>and so on, nothing has worked.</p>

<p>The goal is to have a system such that:</p>

<ol>
<li>I can inject a class when testing the code</li>
<li>I don't have to inject the class in production code (i.e. there is a default)</li>
<li>I can call a class method on the injected class</li>
</ol>
",https://stackoverflow.com/questions/49603504/swift-dependency-injection-by-passing-class-as-a-function-parameter-to-call-a-cl,"['swift', 'class', 'types', 'dependency-injection']",777,TRUE,2,2
Angular 6.0 and Karma Jasmine - browser closes after test finish,"<p>I'm currently looking at unit testing with Angular 6.0. I'm using Karma and Jasmine that come bundled with a new Angular project to run the tests. The tests run fine and all, however the browsers close automatically after each test run, which means any failing tests become pretty much impossible to debug. </p>

<p>I've tried playing around with the configuration, to no success. I'm quite sure that nothing is overriding the configuration and I know that this configuration is used (e.g. after modifying the browsers array, I now have multiple browsers launch).</p>

<p>I execute tests by running the 'ng test' command. Attempting to execute 'karma start' does not seem to work - not sure if that is relevant.</p>

<p>Here's karma.conf.js:</p>

<pre><code>module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-edge-launcher'),
      require('karma-firefox-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma')
    ],
    client: {
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    coverageIstanbulReporter: {
      dir: require('path').join(__dirname, '../coverage'),
      reports: ['html', 'lcovonly'],
      fixWebpackSourcePaths: true
    },
    reporters: ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome', 'Firefox', 'Edge'],
    singleRun: false
  });
};
</code></pre>

<p>'singleRun' seems to have no effect either way same as autoWatch.</p>
",https://stackoverflow.com/questions/50265743/angular-6-0-and-karma-jasmine-browser-closes-after-test-finish,"['angular', 'unit-testing', 'karma-runner', 'karma-jasmine']",9275,TRUE,11,1
Xamarin.UITesting NU1201 Error: Android 8.1 Is incompatible with .NETFramework 4.6.1,"<p>Have been having a little issue for the last couple of days now where I will create a new Xamarin Forms project on Visual Studio 2017 and add a Xamarin.UITest Cross-Platform Test Project for unit testing I recieve a series of NU1201 Errors when I reference the .Android App in the UITest Project. </p>

<p>Here is the exact error i get:</p>

<pre><code>Error NU1201    Project App1.Android is not compatible with net461 (.NETFramework,Version=v4.6.1) / win-x64. Project App1.Android supports: monoandroid81 (MonoAndroid,Version=v8.1)    
</code></pre>

<p>I have played around with the Android version numbers to see if the UITesting package doesnt support the latest android but no matter what version of android i target the problem remains the same. </p>

<p>Here is a screenshot of the project.
<a href=""https://i.stack.imgur.com/VO4Be.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/VO4Be.png"" alt=""enter image description here""></a>
All the code is unchanged from the default project and runs in the simulator fine but only produces these errors when the Android app is referenced to the UITest project.</p>
",https://stackoverflow.com/questions/51296837/xamarin-uitesting-nu1201-error-android-8-1-is-incompatible-with-netframework-4,"['c#', 'android', 'visual-studio', 'xamarin.forms', 'ui-testing']",3541,TRUE,11,2
Access flask app endpoints in another python file?,"<p>I have a python file which defines some endpoints using flask each doing some computation and return a JSON (POST method). I want to do unit testing on this in order to do this I want to be able to access the app I created in one python file in another file so I can test my endpoints.</p>

<p>I see a lot of this on the internet :</p>

<pre><code>from source.api import app
from unittest import TestCase

class TestIntegrations(TestCase):
    def setUp(self):
        self.app = app.test_client()

    def test_thing(self):
        response = self.app.get('/')
        assert &lt;make your assertion here&gt;
</code></pre>

<p>It doesn't explain how I can define and access my app in another file. This might be a stupid question but I really don't see how.</p>

<p>My app is defined as follows:</p>

<pre><code>from flasgger import Swagger 
from flask import Flask, jsonify, request 
from flask_cors import CORS 
import os

def init_deserializer_restful_api():

# Initiate the Flask app
app = Flask(__name__)
Swagger(app)
CORS(app)

# Handler for deserializer
@app.route(""/deserialize"", methods=['POST'])
def handle_deserialization_request():
    pass
</code></pre>

<p>I have many other end points in this fashion. Should i just do:</p>

<pre><code>import my_file_name
</code></pre>

<p>Thanks!!</p>
",https://stackoverflow.com/questions/48624306/access-flask-app-endpoints-in-another-python-file,"['python', 'unit-testing', 'flask']",1054,TRUE,1,1
Why only part of the content being written to a file in python?,"<p>I am new to python and have been using unit testing to test methods in my program. I have been using <a href=""https://docs.python.org/3/tutorial/inputoutput.html"" rel=""nofollow noreferrer"">https://docs.python.org/3/tutorial/inputoutput.html</a> as a reference to read and write to files. I am not understanding why only some of the content is being written to the file in my unit test.</p>

<p>My current unit test file:</p>

<pre><code>class Test_test_States(unittest.TestCase):

    def setUp(self):
        self.test_case_number = 1
        self.file = open('Test_States_Results.txt', 'w')
        self.file.write('---Test States Results---\n')
        self.file.write('Test Case\tInput\t\tExpected Output\t\tResult\n')
        self.file.write('----------------------------------------------------------------\n')

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

    #Unit testing the States Display method
    def test_States_Display_States(self):
        current_states = States()
        file_path = 'pda.def'
        # Write the test case number
        self.file.write(' ' + str(self.test_case_number) + '\t')

        current_states.load(file_path)

        # Write the Input
        self.file.write(str(current_states.states) + '\t\t')

        # Write the Expected Output
        self.file.write('STATES: s0 s1 s2\t\t')

        display = current_states.display_states()
        try:
            self.assertEqual(display, 'STATES: s0 s1 s2')
            # Write the pass results
            self.file.write('Passed\n')
        except AssertionError:
            # Write the fail results
            self.file.write('Failed\n')
        # Increment test case number
        self.test_case_number += 1
</code></pre>

<p>The content that I am writing in my <code>setUp</code> is written to the file; however, the content I am trying to write to the file in my <code>test_States_Display_States</code> method is not being written to the file. I am not understanding why the content is not being written to the file.</p>

<p>How would I correctly write to the file in my <code>test_States_Display_States</code> method?</p>
",https://stackoverflow.com/questions/52912906/why-only-part-of-the-content-being-written-to-a-file-in-python,"['python', 'unit-testing', 'file-io', 'python-unittest']",48,TRUE,1,1
How can I unit test a 64-bit .NET 4.7 project?,"<p>I first got a BadImageFormatException in my test project and after some research it seemed that it was caused because the test project had a AnyCPU build, while the project I want to test had a 64-bit build. After changing my test project to 64 bit the tests stopped working all together. Their icons stays the blue circle with exclamation point after I select run all and when I select one it just show the source file and line number of the test.</p>

<p>I'm using Microsoft.VisualStudio.TestTools.UnitTesting for unit testing.</p>

<p>How can I get my test project to work?</p>

<p>I even threw it away and made a completely new test project and that still got the same error.</p>
",https://stackoverflow.com/questions/52989064/how-can-i-unit-test-a-64-bit-net-4-7-project,"['c#', 'visual-studio', 'unit-testing', 'visual-studio-test-runner', 'visualstudio.testtools']",448,TRUE,1,1
How to un-categoricalize a column in pandas,"<p>I have a Dataframe in Pandas. For sorting purposes, one of the columns is created with:</p>

<pre><code> df['segVar'] = df['segVar'].astype('category', categories=segVars, ordered=True)
</code></pre>

<p>in normal operation, it's saved to a csv with <code>to_csv</code> and then read in in a later stage. In this mode, once it's read in, <code>segVar</code> is not a category. this is fine, and the functionality I want.</p>

<p>For unit testing purposes, however, I'm doing all of this without saving it to a file, and so the <code>segVar</code> column is still a category. This breaks the code, because I do things like <code>df['segVar'].unique()</code> which doesn't work on categoricals. </p>

<p>Basically, I want to not change the column, except that instead of being a categorical, I want it to be the original values. </p>
",https://stackoverflow.com/questions/48411341/how-to-un-categoricalize-a-column-in-pandas,"['python', 'pandas', 'dataframe']",143,TRUE,1,1
Using unittest in python with docker and psycopg2,"<p><strong>BRIEF DESCRIPTION OF THE PROBLEM:</strong> Psycopg2 won't connect to a test DB within docker from unittest, but connects fine from console.</p>

<p><strong>ERROR MESSAGE:</strong> 
<em>psycopg2.OperationalError: server closed the connection unexpectedly
This probably means the server terminated abnormally before or while processing the request.</em></p>

<p><strong>DETAILS:</strong>
I'm trying to set up a testing database in docker, that will be created and populated before testing and then removed after.</p>

<p>Here's the fuction to set up database:</p>

<pre><code>def set_up_empty_test_db():
    client = docker.from_env()
    try:
        testdb = client.containers.get(""TestDB"")
        testdb.stop()
        testdb.remove()
        testdb = client.containers.run(
            ""postgres"",
            ports={5432: 5433},
            detach=True,
            name=""TestDB"",
            environment=[""POSTGRES_PASSWORD=yourPassword""],
        )
    except NotFound:
        testdb = client.containers.run(
            ""postgres"",
            ports={5432: 5433},
            detach=True,
            name=""TestDB"",
            environment=[""POSTGRES_PASSWORD=yourPassword""],
        )

    while testdb.status != ""running"":
        testdb = client.containers.get(""TestDB"")
    return 
</code></pre>

<p>If I launch this function from console it works without an error and I can see TestDB container running. I can successfully initiate connection:</p>

<pre><code>conn = psycopg2.connect(""host='localhost' user='postgres' password='yourPassword' port='5433'"")
</code></pre>

<p>But it doesn't work when unit testing. Here's the testing code:</p>

<pre><code>class TestCreateCity(unittest.TestCase):
    def setUp(self):
        set_up_empty_test_db()
        con = psycopg2.connect(""host='localhost' user='postgres' password='yourPassword' port='5433'"")

        self.assertIsNone(con.isolation_level)

        cur = con.cursor()
        sql_file = open(os.path.join(ROOT_DIR + ""/ddl/creates/schema_y.sql""), ""r"")
        cur.execute(sql_file.readline())
        con.commit()
        con.close()
        self.session = Session(creator=con)

    def test_create_city(self):
        cs.create_city(""Test_CITY"", ""US"")
        q = self.session.query(City).filter(City.city_name == ""Test_CITY"").one()
        self.assertIs(q)
        self.assertEqual(q.city_name, ""Test_CITY"")
        self.assertEqual(q.country_code, ""US"")
</code></pre>

<p>It breaks when trying to initiate connection. Please advise.</p>
",https://stackoverflow.com/questions/51222513/using-unittest-in-python-with-docker-and-psycopg2,"['python', 'unit-testing', 'docker', 'psycopg2']",2351,TRUE,1,1
How do I unit test my reportcontroller by mocking IUserService,"<p>I have a controller:</p>

<pre><code>private readonly IUserService _userService;

    public ReportController ( IOptions&lt;AppSettings&gt; appSettings,
                              UserManager&lt;ApplicationUser&gt; userManager,
                              IUserService userService ) : base( appSettings, userManager ) {
        _userService = userService;
    }

    public async Task&lt;ActionResult&gt; Report ( string path ) {
        var currentUser = await GetCurrentUserAsync();
        var excludedItems = _userService.GetUserExcludedReportsById( currentUser.Id ).Select( er =&gt; er.Path );

        if ( string.IsNullOrEmpty( path ) || excludedItems.Any( path.Contains ) ) {
            return RedirectToAction( nameof(HomeController.Index), ""Home"" );
        }

        var customItems = _userService.GetUserCustomReportsById( currentUser.Id ).Select( er =&gt; er.Path );

        if ( path.Contains( AppSettings.CustomReportsFolderName ) &amp;&amp; !customItems.Any( path.Contains ) ) {
            return RedirectToAction( nameof(HomeController.Index), ""Home"" );
        }


        var model = GetReportViewerModel( Request );
        model.Parameters.Clear();
        var dbname = _userService.GetDefaultDbName( (await GetCurrentUserAsync()).Id );
        model.Parameters.Add( ""connectionStr"", new[] {
            dbname
        } );
        model.ReportPath = path;
        model.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Ntlm;

        return View( ""Report"", model );
    }
}
</code></pre>

<p>Can you tell me how I approach unit testing this? My main issues are:</p>

<p>It has 3 dependencies in the constructor, I have managed to Mock them apart from the UserManager requirement, which seems to have a large amount of dependencies in itself. I have tried a suggestion from this site, as per below, but the UserManager object complains about missing parameters. I keep getting told It should be simple, but surely I need these to instantiate an instance of the controller?</p>

<p>In terms of what to test on the Report method, my thoughts are: The two IF statements return a redirect. Also the expected return is valid.</p>

<p>So far I have:</p>

<pre><code>var mockUserService = new Mock&lt;IUserService&gt;();
        AppSettings appSettings = new AppSettings() { };
        IOptions&lt;AppSettings&gt; options = Options.Create(appSettings);
        var mockUserStore = new Mock&lt;IUserStore&lt;ApplicationUser&gt;&gt;(MockBehavior.Strict);
        var userManager = new UserManager&lt;ApplicationUser&gt;(mockUserStore.Object);
        var mockDependancyResolver = new Mock&lt;IDependencyResolver&gt;();

        var sut = new ReportController(options, userManager.Object, mockUserService.Object);
</code></pre>
",https://stackoverflow.com/questions/48796337/how-do-i-unit-test-my-reportcontroller-by-mocking-iuserservice,"['asp.net-mvc', 'unit-testing', 'asp.net-core', 'moq']",81,TRUE,1,1
Long living service with coroutines,"<p>I want to create a long living service that can handle events.
It receives events via <code>postEvent</code>, stores it in repository (with underlying database) and send batch of them api when there are enough events.</p>

<p>Also I'd like to shut it down on demand.
Furthermore I would like to test this service.</p>

<p>This is what I came up so far. Currently I'm struggling with unit testing it.
Either database is shut down prematurely after events are sent to service via <code>fixture.postEvent()</code> or test itself gets in some sort of deadlock (was experimenting with various context + job configurations).   </p>

<p>What am I doing wrong here?</p>

<pre><code>class EventSenderService(
        private val repository: EventRepository,
        private val api: Api,
        private val serializer: GsonSerializer,
        private val requestBodyBuilder: EventRequestBodyBuilder,
) : EventSender, CoroutineScope {

    private val eventBatchSize = 25

    val job = Job()
    private val channel = Channel&lt;Unit&gt;()

    init {
        job.start()

        launch {
            for (event in channel) {
                val trackingEventCount = repository.getTrackingEventCount()

                if (trackingEventCount &lt; eventBatchSize) continue

                readSendDelete()
            }
        }
    }

    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Default + job

    override fun postEvent(event: Event) {
        launch(Dispatchers.IO) {
            writeEventToDatabase(event)
        }
    }

    override fun close() {
        channel.close()
        job.cancel()
    }

    private fun readSendDelete() {
        try {
            val events = repository.getTrackingEvents(eventBatchSize)

            val request = requestBodyBuilder.buildFor(events).blockingGet()

            api.postEvents(request).blockingGet()

            repository.deleteTrackingEvents(events)
        } catch (throwable: Throwable) {
            Log.e(throwable)
        }
    }

    private suspend fun writeEventToDatabase(event: Event) {
        try {
            val trackingEvent = TrackingEvent(eventData = serializer.toJson(event))
            repository.insert(trackingEvent)
            channel.send(Unit)
        } catch (throwable: Throwable) {
            throwable.printStackTrace()
            Log.e(throwable)
        }
    }
}
</code></pre>

<p>Test</p>

<pre><code>@RunWith(RobolectricTestRunner::class)
class EventSenderServiceTest : CoroutineScope {

    @Rule
    @JvmField
    val instantExecutorRule = InstantTaskExecutorRule()

    private val api: Api = mock {
        on { postEvents(any()) } doReturn Single.just(BaseResponse())
    }
    private val serializer: GsonSerializer = mock {
        on { toJson&lt;Any&gt;(any()) } doReturn ""event_data""
    }
    private val bodyBuilder: EventRequestBodyBuilder = mock {
        on { buildFor(any()) } doReturn Single.just(TypedJsonString.buildRequestBody(""[ { event } ]""))
    }
    val event = Event(EventName.OPEN_APP)

    private val database by lazy {
        Room.inMemoryDatabaseBuilder(
                RuntimeEnvironment.systemContext,
                Database::class.java
        ).allowMainThreadQueries().build()
    }

    private val repository by lazy { database.getRepo() }

    val fixture by lazy {
        EventSenderService(
                repository = repository,
                api = api,
                serializer = serializer,
                requestBodyBuilder = bodyBuilder,
        )
    }

    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Default + fixture.job

    @Test
    fun eventBundling_success() = runBlocking {

        (1..40).map { Event(EventName.OPEN_APP) }.forEach { fixture.postEvent(it) }

        fixture.job.children.forEach { it.join() }

        verify(api).postEvents(any())
        assertEquals(15, eventDao.getTrackingEventCount())
    }
}
</code></pre>

<p>After updating code as @Marko Topolnik suggested - adding <code>fixture.job.children.forEach { it.join() }</code> test never finishes. </p>
",https://stackoverflow.com/questions/53765072/long-living-service-with-coroutines,['kotlinx.coroutines'],138,TRUE,1,1
Can a holding register in the middle of readable holding registers be an &quot;IllegalDataAddress&quot;?,"<p>While unit testing a Modbus driver I'm writing I experienced the following:</p>

<ol>
<li>I can read holding registers 0 to 1022.</li>
<li>I <strong>can't</strong> read holding registers 1022 to 13000. I get an <code>illegal data address</code> error code.</li>
<li>I can read holding registers 13000 to 25000.</li>
</ol>

<p>I would have expected devices supporting Modbus to behave in one of the following two ways:</p>

<ol>
<li>Every device supports the full range of addresses from 0x0000 to 0xFFFF.</li>
<li>Every device supports a range of addresses from 0x0000 to N, where N &lt; 0xFFFF.</li>
</ol>

<p>Do any of you more experienced people know:</p>

<ol>
<li>Is Assumption 1 or 2 about the expected behavior of Modbus devices correct?</li>
<li>Are there other reasons beside being out of bounds for an address to be an <code>illegal data address</code>?</li>
</ol>
",https://stackoverflow.com/questions/51437617/can-a-holding-register-in-the-middle-of-readable-holding-registers-be-an-illega,['modbus'],309,TRUE,1,1
"How to mark a method as not needing to be tested? (ASP.NET, ReSharper)","<p>I have an ASP.NET project and I'm using ReSharper to do my unit testing along with dotCover. I'm looking for a way to mark a method as <em>not needing to be tested</em>. I For example, I have some simple one-liner methods that send work elsewhere and return the result. The methods that do the actual work are covered by unit tests, but these ""intermediate"" methods don't need to be.</p>

<p>These methods will show as <em>uncovered</em> by ReSharper. I'd like to be able to flag them so they don't show as covered or uncovered. This would let me explicitly state when I have code that, for whatever reason, will be excluded from my unit tests and does not need to be concerned about being covered.</p>
",https://stackoverflow.com/questions/49455831/how-to-mark-a-method-as-not-needing-to-be-tested-asp-net-resharper,"['c#', 'unit-testing', 'visual-studio-2015', 'resharper', 'dotcover']",1563,TRUE,5,1
Combining testable code with static method dispatch in swift,"<p>I've been reading a lot about Swift's runtime lately, and became more and more interested in optimising my code using static method dispatch. This happens with the following methods:</p>

<ul>
<li>struct methods</li>
<li>final class methods, i.e. declared with the final keyword, as private or in a final class</li>
<li>protocol methods that are defined in a protocol extension, without being declared in the protocol itself.</li>
</ul>

<p>Problem is, non of these situations enables me to write testable code, at least not the way I do it now: injecting protocol entities that are replaced by mocks in unit testing.</p>

<p>So, is it possible to write testable code without giving up static method dispatch, and if so how does one go about it?</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/53180010/combining-testable-code-with-static-method-dispatch-in-swift,"['swift', 'function', 'dispatch', 'testability']",204,TRUE,1,1
Pass a context from one flux/mono to another,"<p>Interesting things happen inside the webflux package. However, my journey in the source didn't solve the following question. </p>

<p>Let's say I have the following mono (or flux):</p>

<pre><code>Mono hello = Mono.empty()
            .subscriberContext(ctx -&gt; ctx.put(""message"", ""hello""));
</code></pre>

<p>I use similar construct within a webfilter to enrich the pipeline with tenant and user data. Then in a controller a construct like this is used:</p>

<pre><code>Mono world = Mono.subscriberContext()
            .map(ctx -&gt; (String)ctx.get(""message""));
</code></pre>

<p>The context of the hello mono is filled in the world mono. I tried to figure out how this is done, also for unit testing purposes. </p>

<p>In the end it remains a riddle. I tried to do this with the regular methods available on both mono/flux objects but I don't succeed in making the hello context available to the world mono. How can you fuse fluxes and monos and passing the context along the way to the upstream operators?</p>
",https://stackoverflow.com/questions/51185133/pass-a-context-from-one-flux-mono-to-another,"['java', 'spring-webflux', 'project-reactor']",15592,TRUE,10,2
Class is implmented in both... One of the two will be used. Which one is defined,"<p>I have tried to find a solution to this problem, however either the solutions people have given have not worked, or they are not explained well enough for me to understand. </p>

<p>In this thread: <a href=""https://stackoverflow.com/questions/46932341/class-is-implemented-in-both-one-of-the-two-will-be-used-which-one-is-undefine"">Class is implemented in both, One of the two will be used. Which one is undefined</a>
The answer is that there may be duplicate frameworks however my Pods-[AppName].debug.xcconfig file only lists it once.</p>

<p>In this thread: <a href=""https://stackoverflow.com/questions/33127896/ios-unit-testing-class-is-implemented-in-both"">iOS Unit Testing: Class is implemented in both</a> I am confused on how to do it. If someone can explain to me more in-depth what the solution is, that would be great!</p>

<p>Any other information regarding a solution to this problem would be greatly appreciated, thanks. </p>
",https://stackoverflow.com/questions/50223576/class-is-implmented-in-both-one-of-the-two-will-be-used-which-one-is-defined,"['swift', 'xcode', 'cocoapods']",127,FALSE,0,1
How to unit test express middleware function that calls res.cookie,"<p>I am trying to unit test my own express middleware function, using mocha, chai and sinon.</p>

<p>Basically this function checks for a <code>token</code> paramter on <code>req.query</code>, and if it exists, adds a cookie with the value of <code>token</code>.</p>

<pre><code>function tokenRedirect(req, res, next) {
    const qs = require('querystring');

    if (req.query &amp;&amp; req.query.token) {
        res.cookie('token', req.query.token);
    } else {
        next();
        return;
    }

    res.redirect('/');
}
</code></pre>

<p>I know I could do something like:</p>

<pre><code>res = { cookie: sinon.spy() };
</code></pre>

<p>and then</p>

<pre><code>assert(res.cookie.calledWith('token', expectedToken));
</code></pre>

<p>But what I want to do is check that <code>req.cookies</code> actually has the cookie im expecting it to have, like so:</p>

<pre><code>assert.equal(req.cookies.token, expectedToken);
</code></pre>

<p>The problem is that <code>res</code>, <code>req</code>, and all their properties are just mocks I create for the test, so the <code>res.cookie</code> is not the actual express function that really adds cookies to the <code>req</code> object.</p>

<p>How can I pass a real express <code>res</code> object to my function? Is it even possible?</p>

<p>I hope I was clear enough, unit testing is a new concept for me.</p>
",https://stackoverflow.com/questions/48888413/how-to-unit-test-express-middleware-function-that-calls-res-cookie,"['unit-testing', 'express', 'mocha.js', 'sinon', 'chai']",6262,TRUE,5,1
How to run django-pytest on a project which imports settings from environment variables defined in manage.py,"<p>I'm working on a Django project in which settings such as <code>SECRET_KEY</code> are defined in a <code>.env</code> file, and <code>manage.py</code> sets the environment variable using <a href=""https://github.com/theskumar/python-dotenv"" rel=""noreferrer"">python-dotenv</a> as follows:</p>

<pre><code>from dotenv import load_dotenv, find_dotenv

if __name__ == ""__main__"":
    load_dotenv(find_dotenv())
    # usual manage.py code
</code></pre>

<p>Then <code>settings.py</code> simply defines module-level settings from environment variables, for example,</p>

<pre><code>SECRET_KEY = os.environ['SECRET_KEY']
</code></pre>

<p>I'm now in the process of switching to <a href=""https://pytest-django.readthedocs.io/en/latest/"" rel=""noreferrer"">pytest-django</a> for unit testing. The problem, however, is that without running <code>python manage.py</code> first, the environment variables don't get set, so I end up with</p>

<pre><code>E   KeyError: 'SECRET_KEY'
</code></pre>

<p>The way I'm now thinking of working around this is to define a custom action to register with <code>manage.py</code> to run <code>pytest</code> (following <a href=""https://docs.djangoproject.com/en/2.0/howto/custom-management-commands/"" rel=""noreferrer"">https://docs.djangoproject.com/en/2.0/howto/custom-management-commands/</a>). This seems a bit like using a sledgehammer to crack a nut, though. Any suggestions of more elegant ways to go about this problem?</p>
",https://stackoverflow.com/questions/48178204/how-to-run-django-pytest-on-a-project-which-imports-settings-from-environment-va,"['python', 'django', 'pytest', 'pytest-django']",1384,TRUE,5,2
Why is this not compiling,"<p>I have a library I need and it is written in c# from:</p>

<p><a href=""https://github.com/KarlPan/jsxbin-to-jsx-converter"" rel=""nofollow noreferrer"">https://github.com/KarlPan/jsxbin-to-jsx-converter</a></p>

<p>I have read some of the basic c# documentation how to compile and the main terms from Microsoft website.</p>

<p>I have installed the following visual studio and the following build tools:</p>

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

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

<p>I have downloaded the source code and have run the command from commandline:</p>

<pre><code>MSBuild.exe [mydirectory]/jsxbin_to_jsx.sln
</code></pre>

<p>But I get the following errors:</p>

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

<p>Or in text:</p>

<pre><code>""C:\Program Files (x86)\MSBuild\14.0\Bin\jsxbin-to-jsx-converter-master\jsxbin_to_jsx.sln"" (default target) (1) -&gt;
""C:\Program Files (x86)\MSBuild\14.0\Bin\jsxbin-to-jsx-converter-master\jsxbin_to_jsx.Tests\jsxbin_to_jsx.Tests.csproj"" (default target) (3) -&gt;
(CoreCompile target) -&gt;
  JsxbinToJsxTests.cs(2,17): error CS0234: The type or namespace name 'VisualStudio' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?) [C:\Program Files (x86)\MSBui
ld\14.0\Bin\jsxbin-to-jsx-converter-master\jsxbin_to_jsx.Tests\jsxbin_to_jsx.Tests.csproj]
  JsxbinToJsxTests.cs(6,6): error CS0246: The type or namespace name 'TestClassAttribute' could not be found (are you missing a using directive or an assembly reference?) [C:\Program Files (x86)\MSBu
ild\14.0\Bin\jsxbin-to-jsx-converter-master\jsxbin_to_jsx.Tests\jsxbin_to_jsx.Tests.csproj]
  JsxbinToJsxTests.cs(6,6): error CS0246: The type or namespace name 'TestClass' could not be found (are you missing a using directive or an assembly reference?) [C:\Program Files (x86)\MSBuild\14.0\
Bin\jsxbin-to-jsx-converter-master\jsxbin_to_jsx.Tests\jsxbin_to_jsx.Tests.csproj]
  JsxbinToJsxTests.cs(9,10): error CS0246: The type or namespace name 'TestMethodAttribute' could not be found (are you missing a using directive or an assembly reference?) [C:\Program Files (x86)\MS
Build\14.0\Bin\jsxbin-to-jsx-converter-master\jsxbin_to_jsx.Tests\jsxbin_to_jsx.Tests.csproj]
  JsxbinToJsxTests.cs(9,10): error CS0246: The type or namespace name 'TestMethod' could not be found (are you missing a using directive or an assembly reference?) [C:\Program Files (x86)\MSBuild\14.
0\Bin\jsxbin-to-jsx-converter-master\jsxbin_to_jsx.Tests\jsxbin_to_jsx.Tests.csproj]
  JsxbinToJsxTests.cs(15,10): error CS0246: The type or namespace name 'TestMethodAttribute' could not be found (are you missing a using directive or an assembly reference?) [C:\Program Files (x86)\M
SBuild\14.0\Bin\jsxbin-to-jsx-converter-master\jsxbin_to_jsx.Tests\jsxbin_to_jsx.Tests.csproj]
  JsxbinToJsxTests.cs(15,10): error CS0246: The type or namespace name 'TestMethod' could not be found (are you missing a using directive or an assembly reference?) [C:\Program Files (x86)\MSBuild\14
.0\Bin\jsxbin-to-jsx-converter-master\jsxbin_to_jsx.Tests\jsxbin_to_jsx.Tests.csproj]
</code></pre>

<p>Googling the error I have tried to add the unit testing libraries using the <code>using</code> keyword inside of the project.cs file, but it still did not work. I have tried some other things but have been unable to get it to work. </p>
",https://stackoverflow.com/questions/50821959/why-is-this-not-compiling,['c#'],896,FALSE,-3,3
Mock HttpFileColletion in Web API,"<p>In one of our classes I defined a .<code>Files</code> property that exposes
an instance of the <code>HttpFileCollection</code> class. At runtime this instance
will be retrieved from <code>HttpContext.Current.Request.Files</code>.</p>

<p>However, in the unit-testing context, there is no <code>HttpContext</code> to refer
to.
Usually, I'd allow the unit test to set up the instance of the
<code>HttpFileCollection</code> class to be returned by the tested class when
needed. However, <code>HttpFileCollection</code> does not seem to expose a
public .ctor, and it is sealed, so, in my unit tests I can't
instantiate one of them at all /tear.</p>

<p>Any suggestions on how to get around this problem ?</p>

<p>Thanks in advance,</p>

<p>I have to mock below method, This method is called from a controller. This method exist under different class:</p>

<pre><code>public bool ValidateFiles(HttpFileCollection files)
  {
    if (files != null &amp;&amp; files.Count &gt; 0)
    {
        // Some code
        if (files[0].ContentLength &gt; Constants.MaxFileSize)
        {
            //Some Code
        }
    }
    else
    {
        // Some code
    }
 }
</code></pre>
",https://stackoverflow.com/questions/49301302/mock-httpfilecolletion-in-web-api,"['c#', 'unit-testing', 'asp.net-web-api2', 'nunit', 'moq']",344,FALSE,0,0
How to test IPython magic with nosetests,"<p>I use nosetests for unit testing so as team, developing IPython. There are tests for built-in magic functions <a href=""https://github.com/ipython/ipython/blob/master/IPython/core/tests/test_magic.py"" rel=""nofollow noreferrer"">https://github.com/ipython/ipython/blob/master/IPython/core/tests/test_magic.py</a></p>

<p>The problem is that writing tests as usual, when I try to initiate IPython with something like</p>

<pre><code>from IPython import get_ipython
ip = get_ipython()
ip.register_magics(MyMagic)
</code></pre>

<p>nosetests fail with error that <code>'NoneType' object has no attribute 'register_magics'</code>. This is because <code>get_ipython()</code> returns <code>None</code>.</p>

<p>In IPython tests some custom plugins solve the problem. Command <code>iptest</code> runs IPython tests, including magics. The problem is I don't understand how exactly should I run test, or where the plugin is located and how to modify it for custom magic testing. Any help will be appreciated</p>

<p>P.S.: I also tried to use <code>InteractiveShellEmbed()</code>, but it does not work as expected.</p>
",https://stackoverflow.com/questions/52988891/how-to-test-ipython-magic-with-nosetests,"['python', 'ipython', 'nose']",128,FALSE,0,1
"Compile and run test with junit-4.12.jar and hamcrest-core-1.3.jar on command line? Error: is abstract, can not be instantiated, can not find symbol","<p>I am trying to do java unit testing and this is what i have done so far:</p>

<p>in file Test.java:</p>

<pre><code>import java.util.*;

public class Test{
    public String getString(int n){
        return String.valueOf(n);
    }

    public int max(int a, int b){
        if(a&gt;b) return a;
        return b;
    }

    public int maxOf(int []a){
        int max = Integer.MIN_VALUE;
        for (int i=0; i&lt;a.length; i++){
            if (a[i]&gt;max) max=a[i];
        }

        return max;
    }

    public String BMI(int weight, int height){
        double BMI = weight/(height*height);
        if(BMI &lt; 18.5) return ""Insufficient"";
        else if (BMI&gt;=18.5 &amp;&amp; BMI&lt;=22.99) return ""Normal"";
        else if (BMI&gt;=23 &amp;&amp; BMI&lt;=24.99) return ""Overweight"";
        return ""Fat"";
    }
}
</code></pre>

<p>And then i wrote another file called Testtest.java in the same directory:</p>

<pre><code>import static org.junit.Assert.*;
import org.junit.Test;

public class Testtest{
    @Test
    void testString(){
        Test case1 = new Test();
        String result = case1.getString(1);
        // System.out.println(result);
        assertEquals(""1"", result);
    }
    @Test
    public void testMax(){
        Test newTest = new Test();
        int max = newTest.max(2, 4);
        assertEquals(4, max);
    }

    @Test 
    public void testMaxOf(){
        Test newTest = new Test();
        int[] anArray = { 
            10,4,55,66,8,2,33,102
        };
        int max = newTest.maxOf(anArray);
        assertEquals(102, max);
    }

    @Test
    public void testBMI(){
        Test newTest = new Test();
        String result = newTest.BMI(60, 1.65);
        assertEquals(""Normal"", result);
    }
}
</code></pre>

<p>This directory now has the following files:</p>

<pre><code>junit-4.12.jar
hamcrest-core-1.3.jar
Test.java
Testtest.java
</code></pre>

<p>Then i cd into the directory in the command line:
First i compiled the Test.java with javac as usual, then i compiled the Testtest.java with this: </p>

<blockquote>
  <p>javac -cp junit-4.12.jar;. Testtest.java</p>
</blockquote>

<p>and it show me this
<a href=""https://i.stack.imgur.com/efbNj.png"" rel=""nofollow noreferrer"">Error as mentioned in the title</a></p>

<p>i have tried it many time, i know it would be easier if i use IDE but for a number of reasons, i really want to do it using just text editor and command line. </p>
",https://stackoverflow.com/questions/52618282/compile-and-run-test-with-junit-4-12-jar-and-hamcrest-core-1-3-jar-on-command-li,"['java', 'junit4']",501,TRUE,-1,1
Controller undefined in Karma-Jasmine test,"<p>So, I have been stumbling in this strange error for a couple of days by now. Hope you guys could help shedding some light in this tunnel. I'm really sorry to bother you with this, but the error log is not helping. Moreover a similar file (I can provide it if needed) has the same tests, written in the same way, and they works flawlessly.</p>

<p>I have been unit testing in karma-jasmine my project. Everything goes smoothly except for this file:</p>

<pre><code>'use strict';

angular.module('myApp.parkinput', ['ngRoute', 'Parklot', 'City','ngFileUpload'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/parkinput', {
    templateUrl: 'parkinput/parkinput.html',
    controller: 'parkinputCtrl'
  });
}])

.controller('parkinputCtrl', ['$scope', 'NgMap', 'Parklot', 'City', '$location','Upload','$window', function($scope, NgMap, Parklot, City, $location,Upload,$window) {

  $scope.googleMapsUrl=""https://maps.googleapis.com/maps/api/js?key=MYKEY"";

  var map;

  $scope.newParkZone = {};
  $scope.newPicture = {};
  $scope.marker = {id:'newParkZone', name: 'newParkZone', position:null};

  $scope.cities = City.getCities().then(
    function(response){
       $scope.cities = response.data;
    },
    function(error){
       console.log(error);
    });

  NgMap.getMap().then(
    function(evtMap) {
       map = evtMap;
    },
    function(error){
      //console.log(error);
    });

  $scope.setCenter = function(event, city) {
    if(city)
    {
       //preparing the latlen obj to change the map center
       var coords = $scope.newParkZone.City.GPS_Coordinates_Center.split("","");
      map.setCenter({
         lat : coords[0]*1,
         lng : coords[1]*1
      });
      return;
     }
     map.setCenter(event.latLng);
     $scope.marker.position = event.latLng;
     $scope.newParkZone.coords = event.latLng.lat() + "","" + event.latLng.lng();
  };

  $scope.submit = function () {
    $scope.newParkZone.picture = """";
    var newParklot = Parklot.create($scope.newParkZone);
    if ($scope.upload_form.file.$valid &amp;&amp; $scope.file) { 
      $scope.upload($scope.file, newParklot); //call upload function
    }
  }

  $scope.upload = function (file, parklot) {
    Upload.upload({
      url: 'http://localhost:3000/image', 
      data:{file:file, parklot:parklot} 
    }).then(
      function (resp) {
        if(resp.data.error_code === 0){ 
          $window.alert('Success ' + resp.config.data.file.name + 'uploaded. Response: ');
        } else {
          $window.alert('an error occured');
        }
      },
      function (resp) { 
        $window.alert('Error status: ' + resp.status);
      });
  };

}]);
</code></pre>

<p>that should be tested like follows:</p>

<pre><code>describe('Park Input Module', function() {

    beforeEach(module('myApp.parkinput'));

    describe('Route Configuration', function() {
        var $scope = null;
        var ctrl = null;

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

            inject(function($route, $location, $rootScope, $httpBackend) {

                expect($route.current).toBeUndefined();

                $httpBackend.expectGET('parkinput/parkinput.html').respond(200);
                $location.path('/parkinput');
                $rootScope.$digest();

                expect($route.current.templateUrl).toBe('parkinput/parkinput.html');
                expect($route.current.controller).toBe('parkinputCtrl');

            });
        }); 
    });

    describe('controller', function(){
        var $controller;

        beforeEach(inject(function(_$controller_, $rootScope){
            $controller = _$controller_;
        }));

        it('should be defined', function(){
            var $scope = {};
            var controller = $controller('parkinputCtrl', { $scope: $scope});
            expect(controller).toBeDefined()
        });
    })

});
</code></pre>

<p>Here goes the errors:</p>

<p>`</p>

<pre><code>Firefox 59.0.0 (Windows 10 0.0.0) Park Input Module Route Configuration should be correct FAILED
        minErr/&lt;@node_modules/angular/angular.js:116:12
        loadModules/&lt;@node_modules/angular/angular.js:5023:15
        forEach@node_modules/angular/angular.js:408:11
        loadModules@node_modules/angular/angular.js:4983:5
        createInjector@node_modules/angular/angular.js:4900:19
        WorkFn@node_modules/angular-mocks/angular-mocks.js:3173:44
        angular.mock.inject@node_modules/angular-mocks/angular-mocks.js:3153:35
        @app/parkinput/parkinput.spec.js:11:13
        &lt;Jasmine&gt;
Firefox 59.0.0 (Windows 10 0.0.0) Park Input Module controller should be defined FAILED
        minErr/&lt;@node_modules/angular/angular.js:116:12
        loadModules/&lt;@node_modules/angular/angular.js:5023:15
        forEach@node_modules/angular/angular.js:408:11
        loadModules@node_modules/angular/angular.js:4983:5
        createInjector@node_modules/angular/angular.js:4900:19
        WorkFn@node_modules/angular-mocks/angular-mocks.js:3173:44
        &lt;Jasmine&gt;
        TypeError: $controller is not a function in app/parkinput/parkinput.spec.js (line 35)
        @app/parkinput/parkinput.spec.js:35:30
        &lt;Jasmine&gt;
</code></pre>

<p>`</p>

<p>Again, forgive me for the WoT, but I am clueless. I can provide karma configuration file if needed. Thank you in advance for the assistance.</p>
",https://stackoverflow.com/questions/50117899/controller-undefined-in-karma-jasmine-test,"['angularjs', 'karma-jasmine']",284,FALSE,0,0
Confused about Classical TDD and Mockist,"<p>Here is an article: <a href=""https://martinfowler.com/articles/mocksArentStubs.html#ClassicalAndMockistTesting"" rel=""nofollow noreferrer"">https://martinfowler.com/articles/mocksArentStubs.html#ClassicalAndMockistTesting</a></p>

<p>It's in relation to Classical TDD and Mockist. My understanding was that classes should be tested in isolation therefore ALL dependencies should be stubbed / mocked. However it seems there's a large group of people the Classical TDDers who use real objects according to the article. There are various articles on the internet that emphasize that unit tests should not use real classes other than the SUT of course. For example take a look at this from Microsoft's website on stubs:  <a href=""https://learn.microsoft.com/en-us/visualstudio/test/using-stubs-to-isolate-parts-of-your-application-from-each-other-for-unit-testing"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/visualstudio/test/using-stubs-to-isolate-parts-of-your-application-from-each-other-for-unit-testing</a></p>

<pre><code>public int GetContosoPrice()
{
    var stockFeed = new StockFeed(); // NOT RECOMMENDED
    return stockFeed.GetSharePrice(""COOO"");
}
</code></pre>

<p>Can someone clear up my confusion? </p>
",https://stackoverflow.com/questions/49454453/confused-about-classical-tdd-and-mockist,"['unit-testing', 'mocking', 'tdd', 'bdd']",360,TRUE,-1,1
"How to suppress parsing, preprocessing of code with the signature &quot;__ASM volatile rbit(x)&quot;","<p>I am unit testing embedded code on a host environment (vectorcast).</p>

<p>The code is devloped using an arm-eabi compiler on the target hardware. We are testing it on desktop without any simulator or hardware interface.</p>

<p>I am using mingw - 4.5 gcc compiler.
Often there is are lot of assembly code in header files like:</p>

<pre><code>__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __RBIT(uint32_t value)
{  uint32_t result;   

__ASM volatile (""rbit %0, %1"" : ""=r"" (result) : ""r"" (value) );

return(result);}
</code></pre>

<p>While testing my source unit say x1.c, it calls a function like defined above in an included header file. When I try compiling this, I get the following error:</p>

<p>Error: no such instruction: `rbit %ebx,%eax'</p>

<p>Is there any gcc switch that when used for options, ignores code prefixed with __asm?</p>

<p>Any other solution is also welcome.</p>
",https://stackoverflow.com/questions/50740321/how-to-suppress-parsing-preprocessing-of-code-with-the-signature-asm-volatil,"['c', 'white-box-testing']",557,FALSE,0,0
UITextFieldDelegate not called in XCTestCase,"<p>I'm just starting to get familiar with writing tests using <code>XCTestCase</code> and am exploring its capabilities. I have a simple (if contrived) app that loads a screen with a button and a textfield. When the textfield is selected the view controller populates the textfield:</p>

<pre><code>public func textFieldDidBeginEditing(_ textField: UITextField) {
    textField.text = ""abcd""
}
</code></pre>

<p>I also have functionality that selects the field when the button is pressed:</p>

<pre><code>@IBAction public func selectField(_ sender: Any?) {
    print(""button press"")
    textfield.becomeFirstResponder()
}
</code></pre>

<p>The code in my test case, programatically taps the button using <code>vc.button.sendActions(for: .touchUpInside)</code></p>

<p>However, it doesn't appear that the textfield ever becomes first responder and thus the delegate methods are not called. Below is the full test case class:</p>

<pre><code>var vc: ViewController!

override func setUp() {
    let sb = UIStoryboard(name: ""Main"", bundle: nil)
    vc = sb.instantiateInitialViewController() as? ViewController
    _ = vc.view
}

override func tearDown() {

}

func test_textfieldPopulatesOnSelection() {

    vc.button.sendActions(for: .touchUpInside)

    let expectation = XCTestExpectation(description: ""waiting for textfield to become first responder"")
    DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
        print(""textfield.text: \(self.vc.textfield.text ?? """")"")
        expectation.fulfill()
    }

    wait(for: [expectation], timeout: 13.0)
}
</code></pre>

<p>While I realize that I'm probably conflating the concepts of UI testing and unit testing, I'm still curious why my delegate methods are not being called.</p>
",https://stackoverflow.com/questions/53380233/uitextfielddelegate-not-called-in-xctestcase,"['swift', 'cocoa-touch', 'xctest', 'xctestcase']",1080,TRUE,0,2
Configure unit tests so that log4j configuration is not required,"<p>I want to build spring-boot application with external log4j2 configuration. I created project where log4j config is bundled with spring-boot application jar file, but it is stored outside jar file. Application loads configuration file that is defined in application.properties eg. logging.config=file:config/log4j2.xml. The app structure looks like this:</p>

<pre><code>app.jar 
config:
    -&gt;application.properties
    -&gt;log4j2.xml
</code></pre>

<p>App starts correctly and sees both configuration files. However tests can't locate log4j2.xml that is defined in application.properties.</p>

<p>I've created test.properties file as follows:</p>

<pre><code>logging.level.com.mypackage=TRACE

# This sets the global logging level and specifies the appenders
log4j.rootLogger=TRACE, theConsoleAppender

# settings for the console appender
log4j.appender.theConsoleAppender=org.apache.log4j.ConsoleAppender
log4j.appender.theConsoleAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.theConsoleAppender.layout.ConversionPattern=%d %p %c{10} [%t] %m%n
</code></pre>

<p>and annotated my test class with:</p>

<pre><code>@TestPropertySource(locations=""classpath:test.properties"")
</code></pre>

<p>But test runner still looks for file defined in logging.config.</p>

<p>What properties should I override in application.properties file so that log4j2.xml is not required during unit testing?</p>

<p>Thanks for any help.</p>
",https://stackoverflow.com/questions/51349824/configure-unit-tests-so-that-log4j-configuration-is-not-required,"['unit-testing', 'spring-boot', 'log4j2']",1054,TRUE,0,1
Loop to generate and execute commands doesn&#39;t work,"<p>I have following code for my pyspark script. I am trying to generate a query and run it every time with different values of <code>i</code>. The query should select nested JSON elements and calculate the size (i.e. number of occurrences). I am calculating this to help me with unit testing the final table which I am creating separately with ""explode"" functionality</p>

<pre><code>for i in range(1,10) : 
onerowDF = spark.sql(""""""SELECT items['responses'][i]['id'] as items_response_id, items['responses'][i]['name'] as responses_name FROM responses"""""")
onerowDf.select(size(""items_response_id""), size(""responses_name"")).show()
</code></pre>

<p>I am getting error when I run this:</p>

<pre><code>AnalysisException: u""cannot resolve '`i`' given input columns: [hasMore, items, total]; line 1 pos 74;\n'Project [items#1.id AS items_id#149, items#1.responseTime AS items.responseTime#154, items#1.responses['i][id] AS items_response_id#150, items#1.responses['i][name] AS responses_name#151, items#1.responses['i][type] AS responses_type#152, items#1.responses['i][answers] AS responses_answers#153]\n+- SubqueryAlias responses\n   +- Relation[hasMore#0,items#1,total#2L] json\n""
</code></pre>

<p>I have knowingly removed some elements from the code above to make it simpler which is why the error lists more element than my code here.</p>

<p>So why can't I replace the value of I in each query and run the 2 statements and get results?</p>
",https://stackoverflow.com/questions/51681457/loop-to-generate-and-execute-commands-doesnt-work,"['python', 'loops', 'pyspark', 'apache-spark-sql', 'code-generation']",427,TRUE,-4,2
doReturn doesn&#39;t act as proxy but calls my method,"<p>I'm implementing some Unit testing in my app and I have a dependency that relies in the <code>Application</code> context. That dependency returns a list of <code>Item</code> but I want to mock that logic to return whatever I want.</p>

<p>I already know the difference between:</p>

<p>a) <code>when(foo.method1()).return(bar)</code></p>

<p>b)  <code>doReturn(bar).when(foo).method1()</code> </p>

<p><strong>(b)</strong> shouldn't invoke the method.</p>

<p>Now I have a method called in <code>ItemHelper.kt</code> :</p>

<pre><code>fun retrieveItems(): MutableList&lt;Item&gt; {
    val boxStore = BoxStore.getInstance().getBoxFor(Item::class.java)
    return boxStore.all
}
</code></pre>

<p>and that <code>.getInstance()</code> relies on the <code>Application</code>.</p>

<p>Since I want to mock it, this is my test:</p>

<pre><code>class ItemHelperTests {

    @JvmField
    @Rule
    var mockitoRule = MockitoJUnit.rule()!!

    @Mock
    private lateinit var itemHelper: ItemHelper

    @Test
    fun itemsNumber_Test() {
        Mockito.doReturn(ArrayList&lt;Item&gt;()).`when`(itemHelper).retrieveItems()

        System.out.println(""this line is unreachable"")
    }
}
</code></pre>

<p>but that ends calling my code:</p>

<pre><code>java.lang.Exception: Please init BoxStore.boxStore in the MainApplication

    at com.example.dependencies.coreData.BoxStore$Companion.throwBoxStoreNotInitialized(BoxStore.kt:33)
    at com.example.dependencies.coreData.BoxStore$Companion.getInstance(BoxStore.kt:26)
    at com.example.helpers.coreData.Item.ItemHelper.retrieveItems(ItemHelper.kt:20)
    at com.example.helpers.ItemHelperTests.itemsNumber_Test(ItemHelperTests.kt:27)
</code></pre>

<p>so that method is called, I just want to retrieve an empty <code>ArrayList()</code> when that method is called from JVM.</p>

<hr>

<p><strong>EDIT</strong></p>

<p>When using <code>@RunWith(MockitoJUnitRunner::class)</code></p>

<p>I get the same error, but I get one more line of Mockito error:</p>

<pre><code>java.lang.Exception: Please init BoxStore.boxStore in the MainApplication

    at com.example.dependencies.coreData.BoxStore$Companion.throwBoxStoreNotInitialized(BoxStore.kt:33)
    at com.example.dependencies.coreData.BoxStore$Companion.getInstance(BoxStore.kt:26)
    at com.example.helpers.coreData.Item.ItemHelper.retrieveItems(ItemHelper.kt:20)
    at com.example.helpers.ItemHelperTests.itemsNumber_Test(ItemHelperTests.kt:27)

org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here:
-&gt; at com.example.helpers.ItemHelperTests.itemsNumber_Test(ItemHelperTests.kt:27)

E.g. thenReturn() may be missing.
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, which is not supported
 3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed


    at org.mockito.internal.runners.DefaultInternalRunner$1$1.testFinished(DefaultInternalRunner.java:69)
    at org.junit.runner.notification.SynchronizedRunListener.testFinished(SynchronizedRunListener.java:56)
    at org.junit.runner.notification.RunNotifier$7.notifyListener(RunNotifier.java:190)
    at org.junit.runner.notification.RunNotifier$SafeNotifier.run(RunNotifier.java:72)
    at org.junit.runner.notification.RunNotifier.fireTestFinished(RunNotifier.java:187)
    at org.junit.internal.runners.model.EachTestNotifier.fireTestFinished(EachTestNotifier.java:38)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:331)
    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.DefaultInternalRunner$1.run(DefaultInternalRunner.java:78)
    at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:84)
    at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
    at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:161)
    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 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.AppMainV2.main(AppMainV2.java:131)
</code></pre>
",https://stackoverflow.com/questions/48341433/doreturn-doesnt-act-as-proxy-but-calls-my-method,"['android', 'unit-testing', 'kotlin', 'mockito']",147,TRUE,0,1
Have a Go function accept different structs as input with methods,"<p>I'm rather new to Go and I can't seem to wrap my head around it's struct/interface system while trying to create a mock object for an AWS s3manager uploader's unit testing.</p>

<p>In my package file I have:</p>

<pre><code>package uploader

import (
        ""fmt""
        ""github.com/aws/aws-sdk-go/aws""
        ""github.com/aws/aws-sdk-go/aws/session""
        ""github.com/aws/aws-sdk-go/service/s3/s3manager""
        ""os""
)

func GetS3Uploader() *s3manager.Uploader {
    conf := aws.Config{Region: aws.String(""eu-west-1"")}
    sess := session.New(&amp;conf)
    uploader := s3manager.NewUploader(sess)
    return uploader
}

func uploadFile(uploader interface{}) {

    uploader.Upload(&amp;s3manager.UploadInput{
       Bucket: aws.String(""A""),
       Key:    aws.String(""B""),
       Body:   bytes.NewReader([]byte(""C"")),
    })

}
</code></pre>

<p>and in the matching uploader_test.go there is the following code, containing the mock objects:</p>

<pre><code>package uploader_test

import (
    . ""github.com/onsi/ginkgo""
    . ""github.com/something/reponame/uploader""
    ""github.com/aws/aws-sdk-go/service/s3/s3manager""
)

type mockUploadOutput struct {
    Location  string
    VersionID *string
    UploadID  string
}

type mockUploader struct {
}

func (*mockUploader) Upload(input *s3manager.UploadInput) (mockUploadOutput, error) {
    versionID := ""TESTVERSION""
    mockUploadResponse := mockUploadOutput{
        Location:  ""TESTLOCATION"",
        VersionID: &amp;versionID,
        UploadID:  ""TESTUPLOADID"",
    }
    return mockUploadResponse, nil
}

var _ = Describe(""Reportuploader"", func() {

    var (
        mockUp mockUploader
    )

    Describe(""Upload()"", func() {
        Context(""With mocked uploader object"", func() {
            It(""should return the predefined mockUploadResponse"", func() {

                uploadFile(mockUp)

            })
        })
    })
})
</code></pre>

<p>But when I try to run it, I get the following error:</p>

<pre><code>uploader.Upload undefined (type interface {} is interface with no methods)
</code></pre>

<p>My aim is to have the uploadFile function accept both the *s3manager.Uploader object and the mocked mockUploader as valid arguments, and recognize both their Upload methods. I tried asserting the type before calling the Upload method, but that only gave a different error. Can anyone help, and tell me what am I doing wrong?</p>
",https://stackoverflow.com/questions/49742700/have-a-go-function-accept-different-structs-as-input-with-methods,"['unit-testing', 'go', 'types', 'mocking', 'assertions']",595,TRUE,0,2
What does an http service spec actually test in Angular?,"<p>A bit of a theoretical question here.</p>

<p>I'm following the official <a href=""https://angular.io/guide/http#testing-http-requests"" rel=""nofollow noreferrer"">angular.io documentation</a> to test a service that is doing http requests, and I successfuly implemented my spec, fine so far.</p>

<p>What I don't understand is what we are really testing here, providing that I specify the mock data that I should receive back from the request. </p>

<p>Differently put, how would I go about making this test fail?</p>

<p>What is <code>HttpClientModule</code> doing on the insides that makes this test worth implementing? </p>

<p>Don't get me wrong, I'm the first one to advocate for unit testing, I just don't understand what is the value that we are getting from this specific kind of spec.</p>

<p>Thank you very much for your time.</p>

<p>Cheers.</p>
",https://stackoverflow.com/questions/53814719/what-does-an-http-service-spec-actually-test-in-angular,"['angular', 'unit-testing', 'angular-httpclient']",82,FALSE,0,1
CRTP static polymorphism: is it possible to replace the base class with a mock?,"<p>I use CRTP static polymorphism in a websocket server to decouple networking code from business logic. The base class calls methods on the derived to process messages, the derived in turn calls the base to send/receive. It works like charm, looks something like this:</p>

<pre><code>template&lt;typename Derived&gt;
class WebsocketSessionBase {
    // basic websocket send/receive stuff

    void someBaseMethod() {
        static_cast&lt;Derived*&gt;(this)-&gt;otherDerivedMethod();
    }
};

class WebsocketSession : public WebsocketSessionBase&lt;WebsocketSession&gt; {
    // specific business logic

    void someDerivedMethod() {
        otherBaseMethod();
    }
};
</code></pre>

<p>Now comes unit testing. Since the code is decoupled I would like the test functionality in the classes separately. </p>

<p>Testing the base class is simple:</p>

<pre><code>class TestSession : public WebsocketSessionBase&lt;TestSession&gt; {
    // same interface as WebsocketSession, but test code, cool!
};
</code></pre>

<p>But how do I test derived class? Adding a Base template parameter came to my mind, which makes test code ok (Base is a mock class). But I end up having 2 template classes referring to each other in the production version... :(</p>

<pre><code>template&lt;typename Base&gt;
class TestableWebsocketSession : public Base {
};

using TestedWebsocketSession = TestableWebsocketSession&lt;MockBase&gt;;
using ProdWebSocketSession = TestableWebsocketSession&lt;WebsocketSessionBase&lt;... // infinite loop - now what!?
</code></pre>

<p>Is it possible to come over this?</p>
",https://stackoverflow.com/questions/48152743/crtp-static-polymorphism-is-it-possible-to-replace-the-base-class-with-a-mock,"['c++', 'unit-testing', 'crtp', 'static-polymorphism']",352,TRUE,0,1
How to keep shared data without using singleton in Xamarin.forms,"<p>I have a <code>ContentPage</code> with a <code>ListView</code>. I'm navigating to this content page using another content page's button. This button shows the list item count. I have <code>ViewModel</code> connected to each content page. I can update the count when add items to my <code>ObservableCollection</code> since field is adding not from the list page. But when I delete an item from the list view, I want to update the count in that time as well. How can I keep this <code>ObservableCollection</code> as a shared one between these 2 <code>ContentPAges</code>? I know using a<code>Singleton</code> class we can do this. But since my code should support for unit testing it seems I cannot do this. </p>

<p>What is the best way to make this <code>ObservableCollection</code> shared among these content pages?</p>
",https://stackoverflow.com/questions/50756214/how-to-keep-shared-data-without-using-singleton-in-xamarin-forms,"['xamarin.forms', 'singleton']",448,TRUE,0,2
Unit test a class that uses Firebase Auth,"<p>I'm unit testing a class - <em>AuthenticationService</em> - responsible for authenticating the user with Firebase Auth. I'm using JUnit, Mockito and PowerMock for this purpose.</p>

<p>I'm mocking completely Firebase Auth, as my main target is the logic contained within the class. My problem resides in this method:</p>

<pre><code>public void loginWithEmailAndPassword(String email, String password, OnCompletedListener listener) {
    if (Strings.isNullOrEmpty(email) || !Pattern.compile(EMAIL_PATTERN).matcher(email).matches()) {
        throw new IllegalArgumentException(""email field is empty or bad formatted"");
    }
    if (Strings.isNullOrEmpty(password)) {
        throw new IllegalArgumentException(""password field must be not empty"");
    }

    mFirebaseAuth.signInWithEmailAndPassword(email, password)
            .addOnCompleteListener(task -&gt; {
                if (task.isSuccessful()) {
                    if (listener != null)
                        listener.onComplete(new AuthResult(true, null));
                } else {
                    Exception exception = (FirebaseAuthException)task.getException();
                    Log.e(TAG, exception.getMessage());
                    if (listener != null) {
                        AuthResult result = new AuthResult(false, createStatusFromFirebaseException(exception));
                        listener.onComplete(result);
                    }
                }
            });
}
</code></pre>

<p>I want to test the lambda method passed in addOnCompleteListener.
I know i need to somehow call this lambda method, because Firebase itself will never call it, i'm mocking Firebase after all.</p>

<p>The problem is: i don't have any idea of how to call this lambda method in my unit test code.
I need to test if the onComplete method is being called in the listener, and it's arguments.</p>

<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/49340743/unit-test-a-class-that-uses-firebase-auth,"['android', 'unit-testing', 'firebase', 'mockito', 'powermock']",4701,TRUE,0,1
heroku pipeline CI fails on rails application with mysql db,"<p>I have a pipeline on Heroku that connected to a rails application and each ENV(development, staging, production, test) connected to its own DB schema.
the problem is when I test a couple branches parallelly at the same time the test fails because all of those tested connected to a single schema. One test result is affecting another one and causes test goes fail.
this is one of example I got on running 2 tests at the same time but it's fine when they run one by one so I believe one test result is affecting to another one.
My question is what is the best practice of doing parallel unit testing without crashing? </p>

<pre><code>Failures:
  1) User is valid with valid attributes
     Failure/Error: let(:user) { create :user }
     ActiveRecord::StatementInvalid:
       Mysql2::Error: SAVEPOINT active_record_1 does not exist: ROLLBACK TO SAVEPOINT active_record_1
     # ./spec/models/user_spec.rb:5:in `block (2 levels) in &lt;main&gt;'
     # ./spec/models/user_spec.rb:9:in `block (2 levels) in &lt;main&gt;'
     # ./spec/rails_helper.rb:79:in `block (3 levels) in &lt;top (required)&gt;'
     # ./spec/rails_helper.rb:78:in `block (2 levels) in &lt;top (required)&gt;'
     # ------------------
     # --- Caused by: ---
     # Mysql2::Error:
     #   Deadlock found when trying to get lock; try restarting transaction
     #   ./spec/models/user_spec.rb:5:in `block (2 levels) in &lt;main&gt;'
</code></pre>
",https://stackoverflow.com/questions/53839218/heroku-pipeline-ci-fails-on-rails-application-with-mysql-db,"['ruby-on-rails', 'unit-testing', 'heroku']",80,FALSE,0,0
"Class has to create new object internally, which can&#39;t be accessed from unit test","<p>We have a class whose purpose is to change the values in some fields of a received object and keep the values of its other fields</p>

<pre><code>public void process(SomeType someObject) {
  SomeType modifiedObject = modifyObject(someObject);
  nextClass.process(modifiedObject);
}

private SomeType modifyObject(SomeType someObject) {
  String someValueFromServiceCall = someService.getSomeValue(...);
  SomeType modifiedObject = new SomeType.Builder()
                                        .withSomeFieldValuesFromSomeObjectItself(...)
                                        .withSomeFieldValuesFromServiceCall(someValueFromServiceCall)
                                        .build();
  return modifiedObject;
}
</code></pre>

<p><code>SomeType</code> is a legacy class which we can create using only its builder class and it has no setter methods. This means we cannot modify the received <code>someObject</code> itself, but have to build and return a new <code>SomeType</code> object from <code>modifyObject()</code>, which the main method then can pass on for processing to the next class</p>

<p>However this seems to raise problems during unit testing. We don't seem to be able to access the internal <code>modifiedObject</code> from the unit test class and such as we don't seem to be able to do expects/asserts on it</p>

<pre><code>SomeType someObject = createSomeObjectForTest();
expect(someServiceMock.getSomeValue(...)).andReturn(SOME_VALUE);
expect(nextClassMock.process(someObject)).andReturn(...); //this is not someObject, but the new internal modifiedObject created within underTest
underTest.process(someObject);
assertEquals(someObject.getSomeField(), SOME_VALUE); //this is not someObject, but the new internal modifiedObject created within underTest
</code></pre>
",https://stackoverflow.com/questions/53172440/class-has-to-create-new-object-internally-which-cant-be-accessed-from-unit-tes,"['java', 'unit-testing', 'junit', 'junit4', 'junit5']",470,TRUE,0,1
is it possible to overwrite strdup from &lt;string.h&gt; with my own?,"<p>I need to do so because I am supposed to stub this function for unit testing.</p>

<p>I am using gcc version 5.4.0.</p>

<p>for a lot of other functions that exist in glibc like memcpy I simply wrote the implementation in my  .c file and then this implementation was the one used instead of the original, but in case of strdup and some other function I get a compilation error like this one:</p>

<pre><code>error: expected identifier or ‘(’ before ‘__extension__’
 char* strdup (const char *__s)
</code></pre>

<p>I know this is because I am trying to use a function name that already exist in string.h although it works with some other functions in their as well. I wish to know if it is possible to bypass this somehow.</p>
",https://stackoverflow.com/questions/51233563/is-it-possible-to-overwrite-strdup-from-string-h-with-my-own,"['c', 'gcc', 'googletest', 'glibc']",273,TRUE,0,1
Run As JUnit - ClassNotFoundException - BuildCommand Fix causes class resolution problems,"<p>Here's my Setup:</p>

<p>Eclipse Oxygen</p>

<p>Building and Deploying with Maven 3.3 which includes these specific dependencies for Unit Testing:</p>

<ul>
<li>JUnit 4.4  </li>
<li>Mockito 1.9.5</li>
</ul>

<p>I've created a JUnit test class and added it to ($project/src/test/java).<br>
I added this folder as a source folder and then did a Run As JUnit.</p>

<p>I recieve the following error:</p>

<pre><code>Class not found 
java.lang.ClassNotFoundException: 
    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)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.loadClass(RemoteTestRunner.java:770)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.loadClasses(RemoteTestRunner.java:499)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:522)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
</code></pre>

<p>I can fix this by adding the following to the .project file Build Spec:</p>

<pre><code>   &lt;buildCommand&gt;
        &lt;name&gt;org.eclipse.jdt.core.javabuilder&lt;/name&gt;
        &lt;arguments&gt;
        &lt;/arguments&gt;
    &lt;/buildCommand&gt;
</code></pre>

<p>Unfortunately this seems to cause multiple errors to show up under markers for Java Server Faces, etc.  </p>

<p>Is this really my fix or could I be missing something else?  It's especialloy frustrating when you have a clean workspace before making this change to fix the ""Junit"" issue.  </p>
",https://stackoverflow.com/questions/51314058/run-as-junit-classnotfoundexception-buildcommand-fix-causes-class-resolution,"['java', 'eclipse', 'junit']",36,TRUE,0,1
"Can&#39;t resolve all parameters for ObservableDataSource: ([object Object], ?)","<p>I am currently using the <a href=""https://material.angular.io/cdk/table/overview"" rel=""nofollow noreferrer"">angular material data-table cdk</a>. In order to hook up my ngrx/store into the data-table CDK, I am extending the connect method for the DataSource CDK, to allow for an observable to be injected. The following is the relevant code for this question</p>

<pre><code>export class ObservableDataSource extends DataSource&lt;any&gt; {
  private value: any[];
  private key: string;
  constructor(value: any[], key) {
    super();
    this.value = value;
    this.key = key;
  }

  connect() {
    return combineLatest(this.value, (data) =&gt; {
      return data[this.key];
    });
  }

  disconnect() {} 
}
</code></pre>

<p>When unit testing this component(which for curious minds has a <code>@Component</code> decorator, just not shown), I receive the following error: 
<code>Failed: Can't resolve all parameters for ObservableDataSource: ([object Object], ?).</code></p>

<p>I then proceeded to provide values for both value and key: </p>

<pre><code>beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ ObservableDataSource ],
      providers:[
        {provide: 'value', useValue: []},
        {provide: 'key', useValue: ''},
      ]
    })
    .compileComponents();
  }));
</code></pre>

<p>However, the error <code>Failed: Can't resolve all parameters..</code> still shows up. Any suggestions as to how I can properly provide for constructor values, so that Jasmine/Karma can properly resolve parameters is more than appreciated. Thank you. </p>
",https://stackoverflow.com/questions/49018290/cant-resolve-all-parameters-for-observabledatasource-object-object,"['angular', 'unit-testing', 'jasmine', 'karma-runner']",853,TRUE,0,1
Testing a DSL / Grammar Written With Xtext,"<p>I've been set a task of writing a grammar / DSL with XText. It seems reasonably simple. I've been asked to incrementally add rules to the grammar as per a specification. I want to be able to test each new rule that I create.</p>

<p>I have Spring Tool Suite Version: 3.9.2.RELEASE, Build Id: 201712210947, Platform: Eclipse Oxygen.2 (4.7.2).</p>

<p>I've seen textboxes in web browsers that show syntax highlighting based on the validity of the input as per the grammar rules. Also, I'm aware that unit testing is a possibility.</p>

<p>What's the simplest way, minimal fuss, of verifying that the grammar works as expected?</p>

<p>Your help is greatly appreciated.</p>

<p>Thanks in advance,</p>

<p>Ryan</p>
",https://stackoverflow.com/questions/48051514/testing-a-dsl-grammar-written-with-xtext,"['spring', 'eclipse', 'parsing', 'dsl', 'xtext']",470,FALSE,0,2
Unit test run configuration,"<p>I need to get up and running with Cmocka unit testing framework. My setup is:</p>

<p><strong>src/math/addition/add.c (+add.h)</strong></p>

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

<p><strong>src/math/subtraction/sub.c (+sub.h)</strong></p>

<pre><code>int sub(int a, int b) {return a - b;}
</code></pre>

<p><strong>Makefile</strong></p>

<pre><code>VPATH := src src/math src/math/addition
CFLAGS += -Isrc -Isrc/math -Isrc/math/addition
all: libMath clean

libMath: add.o sub.o
    ar rcs bin/libMath add.o sub.o

clean:
    rm -rf *.o

%.o: %.c %.h
</code></pre>

<p><strong>Unit Tests</strong></p>

<p><strong>test/math/addition/add_test.c</strong></p>

<pre><code>#include ""../src/math/addition/add.h""

void test_add() {
     assert(add(4, 5), 9);
}
</code></pre>

<p><strong>test/math/subtraction/sub_test.c</strong></p>

<pre><code>#include ""../src/math/subtraction/sub.h""

void test_sub() {
    assert(sub(9, 5), 4);
}
</code></pre>

<p><strong>test/math/addition/add_test.c</strong> (from <a href=""https://api.cmocka.org/#main-test"" rel=""nofollow noreferrer"">cmocka.org</a>)</p>

<pre><code>#include &lt;stdarg.h&gt;
#include &lt;stddef.h&gt;
#include &lt;setjmp.h&gt;
#include &lt;cmocka.h&gt;

/* A test case that does nothing and succeeds. */
static void null_test_success(void **state) {
    (void) state; /* unused */
}

int main(void) {
    const struct CMUnitTest tests[] = {
        cmocka_unit_test(null_test_success),
    };
    return cmocka_run_group_tests(tests, NULL, NULL);
}
</code></pre>

<p>I'm new to unit testing in C and basically can't get my head around to setup the unit tests including linking the Cmocka library etc.</p>

<p>My idea is to have several unit test files instead of putting all unit tests in one file. </p>

<h2>Edit based on Clearer's answer</h2>

<p><em>Scaling up</em></p>

<p>Going from 1 test file to 2 and 3 and it will be at least 10+ files. Looking for some optimizations and articulations to scale up nicely and for easy management. Here's what I've so far.</p>

<pre><code>VPATH := src/math/add  src/math/sub  src/math/mul # split src/test path
VPATH += test/math/add test/math/sub test/math/mul

all: libMath clean

libMath: add.o sub.o mul.o
    ar rcs bin/libMath add.o sub.o mul.o # suggestion? $^

test: add_test sub_test mul_test clean
    ./add_test
    ./sub_test
    ./mul_test

add_test: add_test.o add.o
    $(CC) -o $@ $^

sub_test: sub_test.o sub.o
    $(CC) -o $@ $^

mul_test: mul_test.o mul.o
    $(CC) -o $@ $^

clean:
    $(RM) *.o

%.o: %.c %.h
</code></pre>

<p>Here's the observation so far.</p>

<ol>
<li>The pattern seems to be like adding a new target for each couple of
test and src files.</li>
<li>Adding the .o object to the libMath both in the prerequisites and the command</li>
<li>adding the test executable under <code>test:</code> target in the prerequisites and the command</li>
</ol>

<p>While scaling up, Is it better this way or there could be better approaches?</p>

<p><strong>P.S.</strong> I've removed CFLAGS line, it's working fine without it, helped me to clean up and reduce some clutter. is it ok? My IDE (clion) shows red wiggly lines if the path isn't right to .h files so I'm using full paths in the test files to include src files.</p>

<p><strong>P.P.S</strong> It creates test executables on the root of the project, how to have all the binaries created in the bin folder and then delete all at the end of the project.</p>
",https://stackoverflow.com/questions/48412862/unit-test-run-configuration,"['c', 'unit-testing', 'cmocka']",394,TRUE,0,1
Is it more pythonic to import inside tests instead of at the start of the module?,"<p>""PyCharm knew that in testing you do the import inside the unit test not at module start"" is a quote from the <a href=""https://www.youtube.com/watch?v=-VzJvNLooj4&amp;index=8&amp;list=PLQ176FUIyIUZ1mwB-uImQE-gmkwzjNLjP"" rel=""nofollow noreferrer"">""Getting Started with PyCharm 7/8: Testing""</a> video about testing capabilities provided by <a href=""https://www.jetbrains.com/pycharm/"" rel=""nofollow noreferrer"">PyCharm</a>.</p>

<p>From <a href=""https://www.python.org/dev/peps/pep-0008/#imports"" rel=""nofollow noreferrer"">PEP8</a>:</p>

<blockquote>
  <p>Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.</p>
</blockquote>

<p><a href=""https://stackoverflow.com/questions/128478"">In this other SO question</a>, the concept of where to import in python has already been addressed as a broder concept. However, there's no mention of the special case when unit testing.</p>

<p>What advantages would we get from importing inside tests instead of at the start of the module?</p>

<p>If different tests use the same modules, does the module have to be imported each time?</p>
",https://stackoverflow.com/questions/50018700/is-it-more-pythonic-to-import-inside-tests-instead-of-at-the-start-of-the-module,"['python', 'unit-testing', 'pycharm']",703,FALSE,3,1
Quantum V gate 1/sqrt(5) ( I + 2iZ),"<p>By definition, the gate 1/sqrt(5) (I + 2iZ) should act on a qubit <code>a|0&gt; + b|1&gt;</code> to transform it into <code>1/sqrt(5) ((1+2i)a|0&gt; + (1-2i)b|1&gt;)</code> but transformations of each RUS step does the following-
The ancillas are in |+> state at first</p>

<ol>
<li>Starting form:  <code>1/sqrt(2) (a,b,a,b,a,b,a,b)</code></li>
<li>CCNOT(ancillas, input): <code>1/sqrt(2) (a,b,a,b,a,b,b,a)</code></li>
<li>S(input): <code>1/sqrt(2) (a,ib,a,ib,a,ib,b,ia)</code></li>
<li>CCNOT(ancillas, input): <code>1/sqrt(2) (a,ib,a,ib,a,ib,ia,b)</code></li>
<li>Z(input) : <code>1/sqrt(2) (a,-ib,a,-ib,a,-ib,ia,-b)</code></li>
</ol>

<p>Now measuring the ancillas in PauliX basis is equivalent to PauliZ measurement after applying H() to the state. Now I have 2 confusions, should I apply <code>H x H x I</code>  or <code>H x H x H</code> to the combined state. Also neither of these transformations turn out to be equivalent to the V-gate defined in the first paragraph when both measurements are Zero. Where did I go wrong?</p>

<p>Reference: <a href=""https://github.com/microsoft/Quantum/blob/master/samples/diagnostics/unit-testing/RepeatUntilSuccessCircuits.qs"" rel=""nofollow noreferrer"">https://github.com/microsoft/Quantum/blob/master/samples/diagnostics/unit-testing/RepeatUntilSuccessCircuits.qs</a> (1st sample code)</p>
",https://stackoverflow.com/questions/51172128/quantum-v-gate-1-sqrt5-i-2iz,"['quantum-computing', 'q#', 'qubit']",163,TRUE,3,1
Testing android app. Trying to mock getSystemService.,"<p>Have been struggling with this for quite some time now, enough to make a user here on stack overflow actually. 
We're developing an android application, and I want to test a method inside an activity class. I have done some unit testing before, but never for an android project, and I've never tried mocking before. </p>

<p>The method I'm trying to test:</p>

<pre><code>public boolean isGPSEnabled()
{
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    GPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    return GPSEnabled;
}
</code></pre>

<p>This method checks if the android device got the GPS enabled and returns true if it is, false if not. 
I'm trying to mock the LocationManager and the Context, and this is what I have so far:</p>

<pre><code>@RunWith(MockitoJUnitRunner.class)

public class IsGPSEnabledTest
{

    @Mock
    LocationManager locationManagerMock = mock(LocationManager.class);
    MockContext contextMock = mock(MockContext.class);

    @Test
    public void testGPSEnabledTrue() throws Exception
    {
        when(contextMock.getSystemService(Context.LOCATION_SERVICE)).thenReturn(locationManagerMock);
        when(locationManagerMock.isProviderEnabled(LocationManager.GPS_PROVIDER)).thenReturn(true);        

        MapsActivity activity = new MapsActivity();
        assertEquals(true, activity.isGPSEnabled());
    }
}
</code></pre>

<p>When I run this test I get this error:</p>

<p>""java.lang.RuntimeException: Method getSystemService in android.app.Activity not mocked.""</p>

<p>Any help on this would be appreciated.</p>
",https://stackoverflow.com/questions/49007114/testing-android-app-trying-to-mock-getsystemservice,"['java', 'android', 'testing', 'mocking', 'mockito']",3192,TRUE,3,1
How to unit tests an AWS Lambda handler with Dagger2 and Kotlin?,"<p>I have some trouble trying to figure out how to write unit tests for an AWS Lambda handler. Here is an example:</p>

<p><strong>App.kt</strong> is the AWS lambda handler class.</p>

<pre><code>class App : RequestHandler&lt;Any, Any&gt; {
    private val component: AppComponent by lazy {
        DaggerAppComponent.create()
    }
    override fun handleRequest(input: Any, context: Context): Any {
        component.getBusinessLogic().doSomething()
        // code
    }
}
</code></pre>

<p><strong>AppComponent.kt</strong> is the Dagger2 component to get the business logic.</p>

<pre><code>@Singleton
@Component(modules = [AppModule::class])
interface AppComponent {
    fun getBusinessLogic(): BusinessLogic
}
</code></pre>

<p><strong>AppModule.kt</strong> is the Dagger2 module.</p>

<pre><code>@Module
abstract class AppModule {
    @Provides
    @Singleton
    fun provideAmazonECS(): AmazonECS = AmazonECSClient.builder().build()
}
</code></pre>

<p><strong>BusinessLogic.kt</strong> is the business logic for the AWS lambda function</p>

<pre><code>class BusinessLogic @Inject constructor(...) {
    fun doSomething(): Any{
        // code to use AmazonECS
    }
}
</code></pre>

<p>Now, here is how I would like to test <strong><code>App.kt</code></strong> by mocking the BusinessLogic class.</p>

<p><strong>AppTest.kt</strong></p>

<pre><code>class AppTest {
    @Test
    fun `test something`() {
        val mockLogic = mock(BusinessLogic::class.java)
        val app = App()
        `when`(mockLogic.doSomething()).thenReturn(...)

        app.handleRequest(...)
    }
    @Test
    fun `test exception`() {
        val mockLogic = mock(BusinessLogic::class.java)
        val app = App()
        `when`(mockLogic.doSomething()).thenThrow(...)

        assertThrows&lt;...&gt; { app.handleRequest(...) }
    }
}
</code></pre>

<p>So, my trouble is that I'm not sure how to use a mocked <code>BusinessLogic</code> instance. The <strong><code>App</code></strong> class must have an empty constructor for AWS lambda to instantiate. Modifying the code such as creating a secondary constructor just for unit testing does not feel right.</p>

<p>Thanks in advance and I appreciate any help with this issue.</p>
",https://stackoverflow.com/questions/52204679/how-to-unit-tests-an-aws-lambda-handler-with-dagger2-and-kotlin,"['kotlin', 'aws-lambda', 'mockito', 'dagger-2']",1684,TRUE,2,1
How to mock DocumentClient CreateDocumentQuery AsDocumentQuery,"<p>Only seen two questions on here for this, one wasn't answered and one was an unusable answer (maybe I just didn't get it).  I want to mock this:</p>

<pre><code>var eventsFeed = this.documentClient.CreateDocumentQuery(this.collectionUri, 
sqlExpression, feedOptions).AsDocumentQuery();
var events = await eventsFeed.ExecuteNextAsync(cancellationToken); 
</code></pre>

<p>I only seem to be able to get this error:</p>

<blockquote>
  <p>Unable to cast object of type 'System.Linq.EnumerableQuery to type
  'Microsoft.Azure.Documents.Linq.IDocumentQuery</p>
</blockquote>

<p>There is a possible answer here:</p>

<p><a href=""https://stackoverflow.com/questions/43563690/unable-to-cast-object-of-type-system-linq-enumerablequery-to-type-microsoft-az"">Unable to cast object of type &#39;System.Linq.EnumerableQuery to type &#39;Microsoft.Azure.Documents.Linq.IDocumentQuery</a></p>

<p>but I can't find the type JTokenEx used in the example and there is no explanation of how to write the mock code?</p>

<p>Ideally I'd like to return some mock results so that I can test the ExecuteNextAsync.</p>

<p>For reference here's the other question I found relating to it but again it wasn't answered:</p>

<p><a href=""https://stackoverflow.com/questions/48349659/how-to-should-i-mock-documentclient-for-documentdb-unit-testing"">How to (should I) mock DocumentClient for DocumentDb unit testing?</a></p>

<p>Any help would be greatly appreciated.
Thanks</p>
",https://stackoverflow.com/questions/48405529/how-to-mock-documentclient-createdocumentquery-asdocumentquery,"['c#', 'linq', 'azure', 'azure-cosmosdb']",1518,FALSE,7,0
Dependency Injection on Customer Facing API,"<p>I am currently designing an API and I have run into a design issue I'm not sure how to approach.</p>

<p>I have a customer facing class that depends on another class from within the model. I need to test the Customer Facing class because it contains business logic.</p>

<p>Normally I would use Dependency Injection to handle this case, like this contrived example:</p>

<pre><code>public interface IRunQuery
{
    ResultObject RunQuery();
}

public class CustomerFacing
{
    public CustomerFacing(IRunQuery needed)
    {
        Needed = needed;
    }

    IRunQuery Needed { get; }

    public void DoSomethingForCustomer()
    {
        // Do some stuff.
        result = Needed.RunQuery();
        // Do some more stuff.
    }
}
</code></pre>

<p>I inject a Stub of the IRunQuery interface when unit testing; it is an expensive operation. This has one enormous glaring issue, though. IRunQuery is not to be known about by the customer. They shouldn't need to know about it and the constructor for CustomerFacing should be:</p>

<pre><code>public CustomerFacing() { }
</code></pre>

<p>How do I Unit Test CustomerFacing without injecting the dependency in the constructor?</p>
",https://stackoverflow.com/questions/51640953/dependency-injection-on-customer-facing-api,"['c#', 'dependency-injection', 'api-design']",58,TRUE,2,2
How to successfully drive a MassTransitStateMachine via the InMemoryTestHarness?,"<p>Following up to: <a href=""https://stackoverflow.com/questions/49763600/how-to-write-masstransitstatemachine-unit-tests"">How to write MassTransitStateMachine unit tests?</a></p>

<p>Here's a simple test class (using MS Test) for a simple state machine called <code>ProcedureStateMachine</code> (note: this is not a real production state machine for us... just an experiment I'd used to play around with <code>MassTransitStateMachine</code> a while back..  it seemed a handy self-contained place to experiment with getting unit testing going too):</p>

<pre><code>[TestClass]
public class ProcedureStateMachineTests
{
    private ProcedureStateMachine _machine;
    private InMemoryTestHarness _harness;
    private StateMachineSagaTestHarness&lt;ProcedureContext, ProcedureStateMachine&gt; _saga;

    [TestInitialize]
    public void SetUp()
    {
        _machine = new ProcedureStateMachine();
        _harness = new InMemoryTestHarness();
        _saga = _harness.StateMachineSaga&lt;ProcedureContext, ProcedureStateMachine&gt;(_machine);

        _harness.Start().Wait();
    }

    [TestCleanup]
    public void TearDown()
    {
        _harness.Stop().Wait();
    }

    [TestMethod]
    public async Task That_Can_Start()
    {
        // Arrange
        // Act
        await _harness.InputQueueSendEndpoint.Send(new BeginProcessing
        {
            ProcedureId = Guid.NewGuid(),
            Steps = new List&lt;string&gt; {""A"", ""B"", ""C"" }
        });

        // Assert
        var sagaContext = _saga.Created.First();
        sagaContext.Saga.RemainingSteps.ShouldHaveCountOf(2);
    }
}
</code></pre>

<p>And here's the state machine class itself:</p>

<pre><code>public class ProcedureStateMachine : MassTransitStateMachine&lt;ProcedureContext&gt;
{
    public State Processing { get; private set; }
    public State Cancelling { get; private set; }
    public State CompleteOk { get; private set; }
    public State CompleteError { get; private set; }
    public State CompleteCancelled { get; private set; }

    public Event&lt;BeginProcessing&gt; Begin { get; private set; }
    public Event&lt;StepCompleted&gt; StepDone { get; private set; }
    public Event&lt;CancelProcessing&gt; Cancel { get; private set; }
    public Event&lt;FinalizeProcessing&gt; Finalize { get; private set; }

    public ProcedureStateMachine()
    {
        InstanceState(x =&gt; x.CurrentState);

        Event(() =&gt; Begin);
        Event(() =&gt; StepDone);
        Event(() =&gt; Cancel);
        Event(() =&gt; Finalize);

        BeforeEnterAny(binder =&gt; binder
            .ThenAsync(context =&gt; Console.Out.WriteLineAsync(
                $""ENTERING STATE [{context.Data.Name}]"")));

        Initially(
            When(Begin)
                .Then(context =&gt;
                {
                    context.Instance.RemainingSteps = new Queue&lt;string&gt;(context.Data.Steps);
                })
                .ThenAsync(context =&gt; Console.Out.WriteLineAsync(
                    $""EVENT [{nameof(Begin)}]: Procedure [{context.Data.ProcedureId}] Steps [{string.Join("","", context.Data.Steps)}]""))
                .Publish(context =&gt; new ExecuteStep
                {
                    ProcedureId = context.Instance.CorrelationId,
                    StepId = context.Instance.RemainingSteps.Dequeue()
                })
                .Publish(context =&gt; new SomeFunMessage
                {
                    CorrelationId = context.Data.CorrelationId,
                    TheMessage = $""Procedure [{context.Data.CorrelationId} has begun...""
                })
                .TransitionTo(Processing)
            );

        During(Processing,
            When(StepDone)
                .Then(context =&gt;
                {
                    if (null == context.Instance.AccumulatedResults)
                    {
                        context.Instance.AccumulatedResults = new List&lt;StepResult&gt;();
                    }
                    context.Instance.AccumulatedResults.Add(
                        new StepResult
                        {
                            CorrelationId = context.Instance.CorrelationId,
                            StepId = context.Data.StepId,
                            WhatHappened = context.Data.WhatHappened
                        });
                })
                .ThenAsync(context =&gt; Console.Out.WriteLineAsync(
                    $""EVENT [{nameof(StepDone)}]: Procedure [{context.Data.ProcedureId}] Step [{context.Data.StepId}] Result [{context.Data.WhatHappened}] RemainingSteps [{string.Join("","", context.Instance.RemainingSteps)}]""))
                .If(context =&gt; !context.Instance.RemainingSteps.Any(),
                    binder =&gt; binder.TransitionTo(CompleteOk))
                .If(context =&gt; context.Instance.RemainingSteps.Any(),
                    binder =&gt; binder.Publish(context =&gt; new ExecuteStep
                    {
                        ProcedureId = context.Instance.CorrelationId,
                        StepId = context.Instance.RemainingSteps.Dequeue()
                    })),
            When(Cancel)
                .Then(context =&gt;
                {
                    context.Instance.RemainingSteps.Clear();
                })
                .ThenAsync(context =&gt; Console.Out.WriteLineAsync(
                    $""EVENT [{nameof(Cancel)}]: Procedure [{context.Data.ProcedureId}] will be cancelled with following steps remaining [{string.Join("","", context.Instance.RemainingSteps)}]""))
                .TransitionTo(Cancelling)
            );

        During(Cancelling,
            When(StepDone)
                .Then(context =&gt;
                {
                    context.Instance.SomeStringValue = ""Booo... we cancelled..."";
                })
                .ThenAsync(context =&gt; Console.Out.WriteLineAsync(
                    $""EVENT [{nameof(StepDone)}]: Procedure [{context.Data.ProcedureId}] Step [{context.Data.StepId}] completed while cancelling.""))
                .TransitionTo(CompleteCancelled));

        During(CompleteOk, When(Finalize).Finalize());
        During(CompleteCancelled, When(Finalize).Finalize());
        During(CompleteError, When(Finalize).Finalize());

        // The ""SetCompleted*"" thing is what triggers purging of the state context info from the store (eg. Redis)...  without that, the 
        // old completed state keys will gradually accumulate and dominate the Redis store.
        SetCompletedWhenFinalized();
    }
}
</code></pre>

<p>When debug this test, the <code>_harness</code> has the <code>BeginProcessing</code> message in its <code>Sent</code> collection, but there's nothing in the <code>_saga.Created</code> collection. It seems like I'm missing some plumbing to cause the harness to actually drive the state machine when the messages are sent?</p>

<p>====</p>

<p>Removing the <code>.Wait()</code> calls from <code>SetUp()</code> and <code>TearDown()</code> and updating the test to the following does NOT change the behavior:</p>

<pre><code>    [TestMethod]
    public async Task That_Can_Start()
    {
        try
        {
            await _harness.Start();
            // Arrange

            // Act
            await _harness.InputQueueSendEndpoint.Send(new BeginProcessing
            {
                ProcedureId = Guid.NewGuid(),
                Steps = new List&lt;string&gt; {""A"", ""B"", ""C""}
            });

            // Assert
            var sagaContext = _saga.Created.First();
            sagaContext.Saga.RemainingSteps.ShouldHaveCountOf(3);
        }
        finally
        {
            await _harness.Stop();
        }
    }
</code></pre>
",https://stackoverflow.com/questions/49765081/how-to-successfully-drive-a-masstransitstatemachine-via-the-inmemorytestharness,"['c#', 'unit-testing', 'state', 'masstransit', 'automatonymous']",1221,TRUE,2,1
Is Android documentation wrong about adding android block to top-level build.gradle,"<p><a href=""https://developer.android.com/training/testing/unit-testing/local-unit-tests"" rel=""nofollow noreferrer"">https://developer.android.com/training/testing/unit-testing/local-unit-tests</a>
clearly states </p>

<blockquote>
  <p>...adding the following configuration in your project's <strong>top-level
   build.gradle file</strong>: </p>
</blockquote>

<pre><code>android {
    ...
    testOptions {
        unitTests.returnDefaultValues = true
    }
}
</code></pre>

<p>But doing so results in an error:</p>

<blockquote>
  <p>Could not find method android() for arguments [...] on root project
  '...' of type org.gradle.api.Project. </p>
  
  <p>Open File</p>
</blockquote>

<p>When researching that error:</p>

<p>I find several existing StackOverflows that indicate it is wrong to add adroid{} to your top-level build.gradle file.</p>

<p><a href=""https://stackoverflow.com/questions/40012866/could-not-find-method-android-for-arguments-in-android-studio-project"">Could not find method android() for arguments in Android Studio project</a></p>

<blockquote>
  <p>In your top-level file, you can't define an android block.</p>
</blockquote>

<p><a href=""https://stackoverflow.com/questions/37250493/could-not-find-method-android-for-arguments"">Could not find method android() for arguments</a></p>

<blockquote>
  <p>In your top-level file you can't define an android block</p>
</blockquote>

<p><strong>Does that mean the Android documentation is wrong?</strong></p>

<p>If not, please help me to understand.</p>
",https://stackoverflow.com/questions/51218028/is-android-documentation-wrong-about-adding-android-block-to-top-level-build-gra,"['android', 'gradle']",176,TRUE,2,1
Reason/Bucklescript + bs-jest: How to compile files with a *.test.re pattern outside of __tests__ folder?,"<p><strong><em>Background:</em></strong></p>

<p>I am currently using bs-jest for unit testing. In addition, I am using the bsb init project, meaning that I am first compiling files using Reason/Bucklescript + then running compiled files using Webpack.</p>

<p>Jest by default will pick up files that have the word test in them, for instance component.test.js, will be picked up by default by Jest.</p>

<p>Bs-jest will work by default, with files being put in the  <code>__tests__</code> directory. However, my spec files following the <code>*.test.re</code> pattern, put in my components folder, i.e. put in a folder other than <code>__tests__</code> will not compile to the appropriate <code>*test.js</code> file.</p>

<p><strong><em>Objective:</em></strong></p>

<p>Compile: </p>

<pre><code>├── Components
|   ├── toolbar
|   |   └── toolbar.re
|   |   └── toolbar.test.re
</code></pre>

<p>To:</p>

<pre><code>├── Components
|   ├── toolbar
|   |   └── toolbar.bs.js
|   |   └── toolbar.test.bs.js
</code></pre>

<p>and then have Jest run and work as it currently does by default. </p>

<p>Any help is more than appreciated. Thank you. </p>
",https://stackoverflow.com/questions/50265161/reason-bucklescript-bs-jest-how-to-compile-files-with-a-test-re-pattern-out,"['jestjs', 'reason', 'bucklescript', 'bs-jest']",219,TRUE,2,3
Flask: Can one create a custom 302 (Redirect) page?,"<p>During unit testing a Flask application I, at first accidentally, omitted the <code>follow_redirects=True</code> parameter, which caused the following test to fail:</p>

<pre><code>from unittest import TestCase
class TestFlask(TestCase):
    def test_settings(self):
        # user not logged in
        r = self.app.get(""/user/settings"", follow_redirects=False)
        data = r.data.decode('utf-8')
        self.assertIn(""Sign In"", data)
</code></pre>

<p>For this page (/user/settings) the user needs to be logged in and would usually be redirected to the login page, which contains the words ""Sign In"". With <code>follow_redirects=False</code> I, of course, get an <code>AssertionError</code> (note the automatically generated HTML):</p>

<pre><code>AssertionError: 'Sign In' not found in '&lt;!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 3.2 Final//EN""&gt;\n&lt;title&gt;Redirecting...&lt;/title&gt;\n&lt;h1&gt;Redirecting...&lt;/h1&gt;\n&lt;p&gt;You should be redirected automatically to target URL: &lt;a href=""/user/login?next=%2Fuser%2Fsettings""&gt;/user/login?next=%2Fuser%2Fsettings&lt;/a&gt;.  If not click the link.'
</code></pre>

<h1>Question</h1>

<p>How can I customize the HTML generated by a 302 redirect that is not being followed?</p>

<h2>What I tried</h2>

<pre><code>from flask import Flask
app = Flask(__name__)
# ...
@app.errorhandler(404)
def page_not_found(e):
    return ""page not found, {}"".format(e)

@app.errorhandler(302)
def redirect(e):
    return ""redirecting... {}"".format(e)
</code></pre>

<p>Taking the same approach as I would for a custom 404 page causes a <code>KeyError: 302</code> upon starting the web server. I am aware that 302 does not indicate an error, thus, trying an <code>errorhandler</code> was destined to fail. I did, however, not find any alternative.</p>
",https://stackoverflow.com/questions/49096101/flask-can-one-create-a-custom-302-redirect-page,"['python', 'unit-testing', 'flask']",928,TRUE,1,1
How to short-circuit invocation of property setter in Moq,"<p>I've recently got a small headache during unit testing one of my property setters. I wanted to setup my property to return a certain value and do not invoke setter logic because it has some heavy operations in there and I don't want that logic to affect my unit test.</p>

<p>I know I can move that logic to a method and then mock that new method instead but that problem made me curious and I've dug a little. 
The results of my research is in FooTests class below, one of them using SetupProperty works, but makes me feel that this is not what this method is written for.</p>

<p>Is there a dedicated way to short-circuit setters in partial mocks in Moq? </p>

<p>Foo.cs:</p>

<pre><code>public class Foo
{
    private int _bar;
    public virtual int Bar
    {
        get =&gt; _bar;
        set
        {
            MagicNumber+=FooBar;
            _bar = value;
        } 
    }

    private int _fooBar;
    public virtual int FooBar
    {
        get =&gt; _fooBar;
        set
        {
            //Complex and heavy logic that makes the magic number -value
            MagicNumber = -value;
            _fooBar = value;
        }
    }

    public int MagicNumber { get; set; }

    public Foo()
    {
        FooBar = 1;
    }
}
</code></pre>

<p>FooTests.cs:</p>

<pre><code>[TestFixture]
public class FooTests
{
    //Using ordinary setup.
    [TestCase(1, 2, 2, TestName = ""BarSetter_BarSetToOneAndFooBarEqualsTwo_MagicNumberEqualsTwo"")]
    public void BarSetterTest(int bar, int fooBar, int expectedMagicNumber)
    {
        var fooPartialMock = new Mock&lt;Foo&gt; {CallBase = true};
        fooPartialMock.Setup(x =&gt; x.FooBar).Returns(fooBar);
        fooPartialMock.Object.Bar = bar;
        Assert.AreEqual(expectedMagicNumber, fooPartialMock.Object.MagicNumber);
    }

    //Using callbacks.
    [TestCase(1, 2, 2, TestName = ""BarSetter_BarSetToOneAndFooBarEqualsTwo_MagicNumberEqualsTwo2"")]
    public void BarSetterTest2(int bar, int fooBar, int expectedMagicNumber)
    {
        var fooPartialMock = new Mock&lt;Foo&gt; { CallBase = true };
        fooPartialMock.SetupSet(x =&gt; x.FooBar = It.IsAny&lt;int&gt;()).Callback&lt;int&gt;(x =&gt; {});
        fooPartialMock.Object.Bar = bar;
        Assert.AreEqual(expectedMagicNumber, fooPartialMock.Object.MagicNumber);
    }

    //Using SetupProperty.
    [TestCase(1, 2, 2, TestName = ""BarSetter_BarSetToOneAndFooBarEqualsTwo_MagicNumberEqualsTwo3"")]
    public void BarSetterTest3(int bar, int fooBar, int expectedMagicNumber)
    {
        var fooPartialMock = new Mock&lt;Foo&gt; { CallBase = true };
        fooPartialMock.SetupProperty(x =&gt; x.FooBar);
        fooPartialMock.Object.FooBar = fooBar;
        fooPartialMock.Object.Bar = bar;
        Assert.AreEqual(expectedMagicNumber, fooPartialMock.Object.MagicNumber);
    }
}
</code></pre>
",https://stackoverflow.com/questions/52371759/how-to-short-circuit-invocation-of-property-setter-in-moq,"['c#', 'unit-testing', 'nunit', 'moq']",1289,TRUE,1,1
DateTimeOffset support for EF Core within In-Memory SqlLite,"<p>I am using Entity Framework Core to make use of an in-memory SQLite database for the purpose of unit testing.</p>

<p>I create the in-memory context as follows:</p>

<pre><code>var connection = new SqliteConnection(""Data Source=:memory:"");
await connection.OpenAsync();

var builder = new DbContextOptionsBuilder&lt;AppDbContext&gt;();
builder.UseSqlite(connection);

var dbContext = new AppDbContext(builder.Options);
</code></pre>

<p>When I have a table that has date/time-related information I store the data as a DateTimeOffset.  The problem is that SQLite does not support date/time datatypes.  I've seen that there are ways to configure EF to treat that data as ticks (or some other datatype like a string) but I have not been able to figure it out in the context of EF Core.</p>

<p>Any solution that doesn't require me to alter the database design would be fantastic.  Of course, ease of implementation would be preferable as well but beggars can't be choosers.  Thank you!</p>
",https://stackoverflow.com/questions/49865173/datetimeoffset-support-for-ef-core-within-in-memory-sqllite,"['c#', 'entity-framework', 'sqlite', 'entity-framework-core', 'datetimeoffset']",1354,FALSE,1,0
Mocking connection pool and test url param using sinon?,"<p>I am doing a RESTful api using node.js, </p>

<p>Unit Testing using mocha, sinon, chai.</p>

<p>DB using ibm DB2.</p>

<p><strong>Problem</strong>:</p>

<p>I am trying to a unit test on the getNews method. </p>

<p>I know the correct way of doing a unit test is not to access the database. So I am trying not to access the database. </p>

<p><strong>Q1:</strong>
However, how do I do a mock on <code>pool.open(connString, function (err, db)</code> to return a fake result, assuming that I created the json result. </p>

<p>Assuming that my newsId that I want to get is 999.</p>

<p><strong>Q2:</strong>
How do it ensure that the newsId i passed in is 999 and not another value?</p>

<p><strong>Codes:</strong></p>

<p>These are files that are already running correctly.</p>

<p>newsRest.js:</p>

<pre><code>module.exports = (app) =&gt; {

    const controller = require('../controller/newsController');

    app.route('news/:newsId').get(controller.getNews);

};
</code></pre>

<p>newsController.js:</p>

<pre><code>'use strict';

//imports
var connectionString = require('../common/ibmdb2Pool').connectionString;
var connString = connectionString();

var initPool = require('../common/ibmdb2Pool').initPool;
var pool = initPool();

const query = require('../db/query');

/*
 * Restful API starts here
 * */

//get news by id

exports.getNews = (req, res) =&gt; {   

    //get from request
    const newsId = req.params.newsId;
    const params = [newsId];

    pool.open(connString, function (err, db) {
        if (err) {
            return console.log(err);
        }

        db.query(query.sqlSelect, params, function (error, result, info) {

            if (error) {
                console.log(error); 
                return false;
            }

            res.status(200).json({
                result: result
            });
        });
    });
};
</code></pre>

<p>ibmdb2Pool.js </p>

<pre><code>'use strict';

//imports
require('dotenv').config();

var Pool = require(""ibm_db"").Pool;

// access the environment variables for this environment
var connString = process.env.CONNSTRING;

//variables
const minPoolSize = 20;
const maxPoolSize = 100;

//return connection string from environment file.
exports.connectionString = function () {
    return connString;
};

//init the db pool with a min and max size
exports.initPool = function () {
    var pool = new Pool();

    var ret = pool.init(minPoolSize, connString);

    if(ret !== true) {

        console.log(""Cannot init pool. "" + ret);
    }

    pool.setMaxPoolSize(maxPoolSize);

    return pool;
};
</code></pre>

<p>Here is my Unit Test class:</p>

<p>newsController.spec.js</p>

<pre><code>process.env.NODE_ENV = 'test';

var initPool = require('../common/ibmdb2Pool').initPool;
var pool = initPool();

const sinon = require('sinon');
const request = require('request');
const chai = require('chai');
const chaiHttp = require('chai-http');
const should = chai.should();
let server = require('../../../main.js');

chai.use(chaiHttp);

describe('news service', () =&gt; {
        beforeEach(() =&gt; {
            this.open = sinon.stub(pool, 'open');

            });
        });

        afterEach(() =&gt; {
            pool.open.restore();
        });

        it('should list a SINGLE news /news/newsId GET', (done) =&gt; {

            chai.request(server) 
                .get('/news/999')
                .end(function(err, res){
                    res.should.have.status(200);
                    res.should.be.json;
                    res.body.should.be.a('object');                                 
                    res.body.result.should.include.keys(
                            'NEWS_ID', 'TITLE', 'NEWS_TYPE', 'DESCRIPTION', 'CREATED_BY', 'CREATED_DATE'
                          );
                   done();
               })
        });
});
</code></pre>
",https://stackoverflow.com/questions/52110673/mocking-connection-pool-and-test-url-param-using-sinon,"['node.js', 'unit-testing', 'mocha.js', 'sinon']",1984,FALSE,1,1
Errors in Unit Test project when including file from main project,"<p>I am currently learning Unit Testing in Visual Studio 2015 but I am finding it hard to find good resources on the topic.</p>

<p>I have set up a C++ Native Unit Test project in the same solution as my main project. I then Set up the main project as a reference in the test project.</p>

<p>My issue is, when I include a file from the main project in the test, almost every single function is giving out compiler errors like these.</p>

<p><a href=""https://i.stack.imgur.com/swR5o.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/swR5o.png"" alt=""Errors""></a></p>

<p>This is the test class</p>

<pre><code>#include ""stdafx.h""
#include ""CppUnitTest.h""

#include &lt;Windows.h&gt;
#include &lt;Util\fileutil.h&gt;

using namespace Microsoft::VisualStudio::CppUnitTestFramework;


namespace EngineTest
{       
using namespace Engine;
TEST_CLASS(EngineTests)
{
public:

    TEST_METHOD(UnitTestTest)
    {
        int i = 1;
        Assert::IsTrue(i == 1);
    }

    TEST_METHOD(FilePathSplit)
    {
        FileUtils testClass;
        std::string examplePath = ""./FolderOne/FolderTwo/File.file"";
        std::string exampleName = ""File.file"";
        std::set&lt;char&gt; delims{ '\\', '/' };
        std::string fileName = testClass.test_splitpath(examplePath, delims).back();
        Assert::AreSame(fileName, exampleName);

    }

};
}
</code></pre>

<p>The build works just fine, so I assume it is an issue with dependencies not being loaded in, I have tried adding all the headers into stdafx but that did not change anything.</p>

<p>Any help is appreciated.</p>
",https://stackoverflow.com/questions/49962253/errors-in-unit-test-project-when-including-file-from-main-project,"['c++', 'visual-studio', 'unit-testing', 'visual-studio-2015', 'compiler-errors']",135,TRUE,1,1
Angular testing for first time a method which returns Observable,"<p><strong>Hello and thank you for your time:</strong></p>

<p>I am trying to learn how to test a service which has a method to return an Observable.</p>

<p>I have done the Tour of heroes tutorial of the Angular page until the routing module, and I would like to unit test the code.</p>

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

<pre><code>    import {Injectable} from '@angular/core';
import {HEROES} from '../mock-heroes';
import {Hero} from '../Hero';
import {Observable} from 'rxjs/Observable';
import {of} from 'rxjs/observable/of';
import {MessageService} from '../message.service';

@Injectable()
export class MyHeroService {

  getHeroes(): Observable&lt;Hero[]&gt; {
    this.messageService.add('HeroService: fetched all your heroes');
    return of(HEROES);
  }

  getHero(id: number): Observable&lt;Hero&gt; {
    // Todo: send the message _after_ fetching the hero
    this.messageService.add(`HeroService: fetched hero id=${id}`);
    return of(HEROES.find(hero =&gt; hero.id === id));
  }

  constructor(private messageService: MessageService) {
  }

}
</code></pre>

<p>And here is the unit test I am currently doing:</p>

<pre><code>    import {MyHeroService} from './my-hero.service';
import {MessageService} from '../message.service';
import {async, inject} from '@angular/core/testing';

describe('heroService', () =&gt; {


  it('should return an Observable of Hero[]', async(() =&gt; {
    const myHeroService = new MyHeroService(new MessageService([]));
    myHeroService.getHero(1).subscribe(result =&gt; expect(result).toBeGreaterThan(0));
  }));
});
</code></pre>

<p>The result which the test gives is:
<a href=""https://i.stack.imgur.com/FFUsM.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/FFUsM.jpg"" alt=""enter image description here""></a></p>

<p>I have also read:
<a href=""https://stackoverflow.com/questions/34607990/unit-testing-an-observable-in-angular-2"">Unit testing an observable in Angular 2</a></p>

<p><a href=""https://stackoverflow.com/questions/45084568/unit-test-success-and-error-observable-response-in-component-for-angular-2"">Unit test &#39;success&#39; and &#39;error&#39; observable response in component for Angular 2</a></p>

<p><a href=""https://stackoverflow.com/questions/42583749/angular-2-observable-service-karma-jasmine-unit-test-not-working"">Angular 2 Observable Service Karma Jasmine Unit Test not working</a></p>

<p>Could you help me please to understand why it gives <strong><em>'Expected undefined to be greater than 0.'</em></strong></p>
",https://stackoverflow.com/questions/48182579/angular-testing-for-first-time-a-method-which-returns-observable,"['javascript', 'angular', 'unit-testing']",997,FALSE,1,1
How do i differentiate unit tests from integration test?,"<p>I have all dependencies mocked, stubbed for the test below.
Is this still considered a unit test or an integration test?
I have read in an article online that you should separate the two, unit tests should be ran as often as possible, and integration tests once in a while.
I don't have a lot of experience with unit testing, and I am having difficulties distinguishing between the two.</p>

<p>For example I have added new functionality and the test below fails, but I have tested the application code and it works as intended. I feel that my tests are too brittle, and I currently need to keep changing the test or adding to it when i am changing my source code, that doesn't seem right to me.</p>

<pre><code>TEST_F(UserInterfaceTest, TransmitCalibrationWithWrongPacket)
    {
        std::vector&lt;std::string&gt; commandpathnames;

        for (int i = 0; i &lt; 9; i++)
        {
            std::string txt(""transmit_calibration"");
            txt += std::to_string(i);
            txt += "".txt"";

            commandpathnames.push_back(txt);
        }

        EXPECT_CALL(*m_View, DisableAndSwitchPanel());
        EXPECT_CALL(*m_View, CheckInstance(_, _));
        EXPECT_CALL(*m_View, GetSerialPortInstance()).WillRepeatedly(ReturnRef(serialport));
        EXPECT_CALL(*m_View, GetSerialPortAddress()).WillOnce(Return(port));
        EXPECT_CALL(*m_View, GetCalibration()).WillRepeatedly(Return(calib));

        EXPECT_CALL(*m_Param, SetFunction(_));
        EXPECT_CALL(*m_Param, GetFunction()).WillOnce(Return(TRANSMIT_CALIBRATION));
        EXPECT_CALL(*m_Param, GetTemperature());
        EXPECT_CALL(*m_Param, GetSurveyDelay()).WillOnce(Return(20));

        EXPECT_CALL(*calib, GetCommandPathNames()).WillRepeatedly(Return(commandpathnames));

        EXPECT_CALL(serialport, Read(_))
            .WillOnce(DoAll(SetArgReferee&lt;0&gt;(poll), Return(0)));

        EXPECT_CALL(serialport, Write(_))
            .WillOnce(DoAll(SetArgReferee&lt;0&gt;(identitycommand), Return(0)));

        EXPECT_CALL(*m_View, CustomEventDisplayData(_)).Times(AtLeast(1));

        EXPECT_EQ(wxTHREAD_NO_ERROR, m_Controller-&gt;TransmitMasCalibration());

        m_Controller-&gt;GetSemaphore()-&gt;Wait();
    }
</code></pre>
",https://stackoverflow.com/questions/51501476/how-do-i-differentiate-unit-tests-from-integration-test,"['unit-testing', 'integration-testing']",72,TRUE,1,1
Should we mock in cucumber testing while testing java code. Till what extent we should use cucumber?,"<p>I am a Java developer. We want to use cucumber testing in our project. We are working mainly on creating APIs. I am good with unit testing and researching about cucumber.
I am thinking about testing persistence methods - CRUD operations as an starter. My questions is that what could be the scenerios in this testing. 
Also should I mock the database by creating tables in the feature file. Should I use mockito with Cucumber to mock call to some other services which connects to database and server. 
What should be the cucumber testing in these scenerios and whats the best way to create framework to use cucumber in our Java API's project.</p>

<p>Also, how to populate models if not using database</p>
",https://stackoverflow.com/questions/52289688/should-we-mock-in-cucumber-testing-while-testing-java-code-till-what-extent-we,"['java', 'unit-testing', 'testing', 'junit', 'cucumber']",1477,TRUE,1,1
Using chai to mock http requests,"<p>I'm testing a nodejs app written using express. For the unit testing I'm using chai and sinon. I have the following route in my API that I would like to test.</p>

<p>In my test, I'm simulating the get request with the following code:</p>

<pre><code> chai.request(app)
            .get('/downloads')
            .send({ wmauth: {
                    _identity: {
                        cn: ""username"",
                    }
                } })
            .end((err, res) =&gt; {
            res.status.should.be.equal(200);
            res.body.should.be.a('object');
            res.body.should.have.property('Items', []);

            AWS.restore('DynamoDB.DocumentClient');
            done();
</code></pre>

<p>However, I'm always getting the error ""Cannot read property '_identity' of undefined"". Because the object ""wmauth"" is not sent in the request, so it is undefined. I have tried to use the send method to try to include it in the request, but no luck. I guess I need to mock it somehow and send it into the request but have no idea how to do it. Could someone help me with this?
Below the method to test: </p>

<pre><code> app.get('/downloads', async (req, res) =&gt; {
    const created_by_cn = req.wmauth['_identity'].cn;
    if(!created_by_cn) {
        return res.status(400).json({
            error: 'Mandatory parameters: created_by_cn',
        });
    }
    try {
        const data = await downloadService.getDownloads(created_by_cn);
        return res.status(200).json(data);
    }
    catch(error){
        res.status(500).json({error: error.message});
    }
});
</code></pre>

<p>THanks</p>
",https://stackoverflow.com/questions/51762653/using-chai-to-mock-http-requests,"['javascript', 'node.js', 'unit-testing', 'sinon', 'chai']",1002,FALSE,1,2
How to export a copy of a database from phpMyAdmin or MySqlWorkbench for use in VS2017 Unit Testing,"<p>I'm the lead programmer for Unit Testing at my business and I would like to be able to create a copy of the database that will be accessed to run Unit Tests. I'm told I can export the database from phpMyAdmin or MySqlWorkbench (the later which I don't see an obvious way to export), but I'm not sure how to connect that copy to the Unit Test to reference when testing. If someone could explain the process of going from exporting all the way to how to make the Unit Tests make use of that exported copy, I would be very appreciative. Even if you only know some of the steps in between, that would still be helpful at this point.</p>
",https://stackoverflow.com/questions/48427436/how-to-export-a-copy-of-a-database-from-phpmyadmin-or-mysqlworkbench-for-use-in,"['unit-testing', 'phpmyadmin', 'visual-studio-2017', 'export', 'mysql-workbench']",70,TRUE,0,1
how to getting the email verification link in Unit Test Laravel,"<p>I am developing a Laravel application. I am doing unit testing to my application. Now I am having a trouble with testing the verification process.</p>

<p>What I am trying to do now is that I am registering a user, then test if the verification email is sent, then I will get the verification link for that registration, then I will do something with that link. </p>

<ol>
<li>The first issue is that the email is not sent. </li>
<li>The second issue is that I do not know how to retrieve the
verification email link? </li>
</ol>

<p>This is my test</p>

<pre><code>public function test_user_can_be_verified_and_redirected_based_on_role()
{
    Notification::fake();
    $user = $this-&gt;registerUser();
    Notification::assertSentTo($user, SendEmailVerificationNotification::class);

}

protected function registerUser()
{
    $user = factory(User::class)-&gt;make();

    $this-&gt;post(route('register'), [
        'name' =&gt; $user-&gt;name,
        'email' =&gt; $user-&gt;email,
        'password' =&gt; 'testing',
        'password_confirmation' =&gt; 'testing',
    ])-&gt;assertRedirect();

    return User::whereEmail($user-&gt;email)-&gt;first();
}
</code></pre>

<p>But the issue is that the notification is not sent even if it is sent when I register from the browser. I also like to retrieve the verification link and do something. How can I do that?</p>
",https://stackoverflow.com/questions/53884854/how-to-getting-the-email-verification-link-in-unit-test-laravel,"['laravel', 'unit-testing', 'phpunit']",3258,TRUE,5,3
jose4j algorithm mismatch between signed JWT and JWK,"<p>During unit testing I noticed some expected behavior regarding the.</p>

<p>I used your code to generate a RsaJsonWebKey keypair.  Once created I set the algorithm to RS512.  I created a public JWK based off of that.  At that point, the keypair and the JWK had the same key-id, algorithm and signature.  Next in the UT, I altered the algorithm of the JWK to RS256.  I expected this to fail but it still matches and validates.
Granted, the key-id and most importantly, the signatures still matched.  Is algorithm really necessary?  Looking into the Jose4J source code, it appears it's never set to match against the JWK.</p>

<p>in method SimpleJwkFilter.filter()</p>

<p>match &amp;= isMatch(alg, jwk.getAlgorithm());  &lt;-- alg is never set and therefore passes isMatch</p>
",https://stackoverflow.com/questions/50532108/jose4j-algorithm-mismatch-between-signed-jwt-and-jwk,['jose4j'],438,TRUE,0,1
What are the benefits to creating adapters around dependencies?,"<p><strong>Specifically dependencies that have very specific implementations.</strong>  </p>

<p>For one example, the Hangfire enqueing library.  This has very specific implementations to enqueue background jobs to be executed asynchronously.</p>

<p>I created a wrapper around this dependency, but it ended up being tightly coupled to the dependency itself.  Then, when I use my adapter in other assemblies, they all end up needing a reference to Hangfire anyway.</p>

<p>Why would I want to wrap the Hangfire dependency (or similar dependency) in an adapter?  </p>

<p>If I ever switch to a different enqueueing system, all of the code will go ""red"" where I need to switch it anyway.  I can see an argument to be made for unit testing and/or late binding, but is there any other reason?</p>
",https://stackoverflow.com/questions/50606869/what-are-the-benefits-to-creating-adapters-around-dependencies,"['c#', 'architecture', 'dependencies', 'adapter', 'software-design']",81,TRUE,0,1
testing my controller function does not move into .then,"<p>I'm still new to unit testing, and i was trying to test a function on my component controller, which use a service for an api call but i notice that when i run the test its not going inside .then of the request return .</p>

<p>here is my component 'arSchoolComponent':</p>

<pre><code>var arSchoolComponent = {
templateUrl: ""ar-school.component.html"",
controller: arSchoolComponentCtrl,
controllerAs: 'schoolCtrl'
};

arSchoolComponentCtrl.$inject = [
    ""$schoolsService"",
    ""$permissionService"",
    ""$stateParams"",
    ""$state"",
    ""$scope"",
    ""arAuthenticationService"",
    ""$mdDialog"",
    ""$notificationService"",
    ""$translate""
];

function arSchoolComponentCtrl($schoolsService,
                               $permissionService,
                               $stateParams,
                               $state,
                               $scope,
                               arAuthenticationService,
                               $mdDialog,
                               $notificationService,
                               $translate) {


// @variables
var vm = this;
vm.loading = false;
vm.selectedSchool = null;

// @methods
vm.getSchool = getSchool;

vm.$onInit = function () {
  //this is equal to getSchool(1)
  getSchool(vm.currentUser.information.staff.schools[0].schoolId);
};

/**
 * Load school data from server
 *
 * @param id
 */
function getSchool(id) {
    preloader.on();

    if (!vm.loading) {
        vm.loading = true;

        var request = $schoolsService.getSchool(id);

        request.then(function (response) {
            vm.selectedSchool = response.data;
            vm.loadCompleted = true;
        }).then(function () {
            vm.loading = false;
            preloader.off();
        });
    }
}


}
</code></pre>

<p>here is my service '$schoolsService' :</p>

<pre><code>var arSchoolsService = [
'UtilityService',
'$q',
function($utility, $q) {

    var _this = this;

    //@variables
    _this.user = null;
    _this.baseUrl = 'api/school'; // Server base url for request
    _this.selectedSchool = null; // Selected School
    _this.schools = []; // Array of schools
    _this.validationError = false;

    var service = {
        getSchool: getSchool

    };

    return service;

    //@methods

    /**
     * Return one school
     *
     * @param schoolId
     */
    function getSchool(schoolId) {
        return $utility.sendRequest('GET', _this.baseUrl + '/' + schoolId);
    }
}
</code></pre>

<p>here is my unit test :</p>

<pre><code>describe('Unit - Component: school', function () {

beforeEach(module('activityRight.module', 'mockedSchoolJSON'));

var ctrl;
var SignInCtrl;

var $componenetController;
var $schoolsService;
var $permissionService;
var $state;
var arAuthenticationService;
var $translate, $scope, $notificationService, $auth;
var deferred;
var CONFIG;
var $httpBackend;
var $defaultJSON;

beforeEach(inject(
    function (_$componentController_, _$schoolsService_, _$permissionService_, _$stateParams_, _$state_, $rootScope, _arAuthenticationService_,
        _$notificationService_, _$translate_, _$auth_, $q, _$httpBackend_, defaultJSON, $injector) {
        $componenetController = _$componentController_;
        $schoolsService = _$schoolsService_;
        $permissionService = _$permissionService_;
        $stateParams = _$stateParams_;
        $state = _$state_;
        $scope = $rootScope.$new();
        arAuthenticationService = _arAuthenticationService_;
        $notificationService = _$notificationService_;
        $translate = _$translate_;
        $auth = _$auth_;
        deferred = $q.defer();
        $httpBackend = _$httpBackend_;
        CONFIG = $injector.get('CONFIG');
        $defaultJSON = defaultJSON

        ctrl = $componenetController('arSchoolComponent', {
            ""$schoolsService"": $schoolsService,
            ""$permissionService"": $permissionService,
            ""$stateParams"": $stateParams,
            ""$state"": $state,
            ""$scope"": $scope,
            ""arAuthenticationService"": arAuthenticationService,
            ""$notificationService"": $notificationService,
            ""$translate"": $translate
        });

        SignInCtrl = $componenetController('arSigninComponent', {
            '$auth': $auth,
            'arAuthenticationService': arAuthenticationService,
            '$state': $state,
        });



        SignInCtrl.email = '';
        SignInCtrl.password = '';

        SignInCtrl.authenticate;

        user = arAuthenticationService.sessionUser();

        $permissionService.setUser(user);

        ctrl.$onInit();

        $httpBackend.whenGET('translations/en-ca.json').respond({});
        $httpBackend.whenGET('fb-partials/sign-up.html?ver=1').respond({});
        $httpBackend.whenGET('fb-partials/main.html?ver=1').respond({});
        $httpBackend.when('GET', CONFIG.origin_url + '/api/school/1').respond($defaultJSON.fakeData[0]);
        $httpBackend.flush();
    }
));

// Check for open http requests
afterEach(function () {
    $httpBackend.verifyNoOutstandingExpectation();
    $httpBackend.verifyNoOutstandingRequest();
});

it('`getSchool` should exist and return data depend on id', function () {
    expect(ctrl.getSchool).toBeDefined();
    ctrl.loading = false;
    ctrl.selectedSchool = null;
    spyOn($schoolsService, 'getSchool').and.returnValue(deferred.promise);
    ctrl.getSchool(2);
    expect($schoolsService.getSchool).toHaveBeenCalledTimes(1);
    //will check this error later, need to move one for now
    //expect(ctrl.selectedSchool.schoolId).toBe(2);
});
</code></pre>

<p>when i call the function getSchool throught ctrl.getSchool(2) , i spy the service method getSchool spyOn($schoolsService, 'getSchool').and.returnValue(deferred.promise); and the expect($schoolsService.getSchool).toHaveBeenCalledTimes(1); is correct its shows it went through the function and called schoolsService.getSchool but the ctrl.selectedSchool is not updated which mean it didnt go inside .then </p>

<p>I know that im missing something here, could please anyone help regarding this issue.</p>
",https://stackoverflow.com/questions/48346711/testing-my-controller-function-does-not-move-into-then,"['angularjs', 'unit-testing', 'jasmine', 'karma-jasmine']",35,TRUE,0,1
Mocha spies returns callCount 0,"<p>I am using mocha, chai and sinon for unit testing in node env. I need to test a scenario where it makes a call to services to fetch the data and return the data.</p>

<p>My controller looks like this:</p>

<pre><code>{
   get model() { return schema},
   async findUser(data) {
      const data = await this.model.find({ id: data.id });
      return data;
   }
}
</code></pre>

<p>In my mocha test I am using the Sinon stub to return the model and find function some like this:</p>

<pre><code>sinon.stub(controller, 'model').get(() =&gt; ({
    find: () =&gt; ({ username: 'asdf' })
}));
</code></pre>

<p>My test is working as expected. Now I want to test see if my find method id called once and the arguments passed to it. To do that, i added following code</p>

<pre><code>const spyFind = sinon.spy(controller.model, 'find');
assert.isTrue(spyFind.calledOnce);
</code></pre>

<p>This should return true because the spyFind is called and it returned the expected mock value. But when i debug, the spyFind object says isCalled 'false'. Can someone help me understand what am i doing wrong?</p>
",https://stackoverflow.com/questions/52323351/mocha-spies-returns-callcount-0,"['node.js', 'mocha.js', 'sinon']",1176,TRUE,0,1
Faking Stream for sealed PngBitmapEncoder,"<p>This is a follow up question to <a href=""https://stackoverflow.com/questions/49923188/unit-testing-with-i-o-dependencies"">Unit testing with I/O dependencies</a>.</p>

<p><strong>How do I make <a href=""https://learn.microsoft.com/en-us/dotnet/api/system.windows.media.imaging.pngbitmapencoder"" rel=""nofollow noreferrer"">PngBitmapEncoder</a> to accept wrapped/mocked FileStream?</strong></p>

<p>In BitmapService.SaveBitmapAsPngImage() I want to assert that bitmap encoder calls stream save:
bitmapEncoder.Save(outStream.StreamInstance);</p>

<p>Rhino mock test which needs ""a valid"" FileStream for the PngBitmapEncoder:</p>

<pre><code>[Test]
public void BitmapService_Should_SaveBitmapAsPngImage_RhinoMocks()
{
    // Arrange
    IFile fileMock = MockRepository.GenerateStrictMock&lt;IFile&gt;();
    IFileStream fileStreamWrapperMock = MockRepository.GenerateStub&lt;IFileStream&gt;();
    fileMock.Expect(x =&gt; x.Open(string.Empty, FileMode.OpenOrCreate))
        .IgnoreArguments().Return(fileStreamWrapperMock);
    var bitmapEncoderFactory = MockRepository.GenerateStub&lt;IBitmapEncoderFactory&gt;();

    PngBitmapEncoder pngBitmapEncoder = new PngBitmapEncoder();
    bitmapEncoderFactory.Expect(x =&gt; x.CreateBitmapEncoder()).Return(pngBitmapEncoder);

    BitmapService sut = new BitmapService(fileMock, new PngBitmapEncoderFactory());
    Size renderSize = new Size(100, 50);
    RenderTargetBitmap renderBitmap = new RenderTargetBitmap(
        (int)renderSize.Width, (int)renderSize.Height, 96d, 96d, PixelFormats.Pbgra32);

    // Act
    sut.SaveBitmapAsPngImage(new Uri(""//A_valid_path""), renderBitmap);

    // Assert
    pngBitmapEncoder.AssertWasCalled(x =&gt; x.Save(fileStreamWrapperMock.FileStreamInstance));
}
</code></pre>

<p>Rhino test result:</p>

<blockquote>
  <p>System.ArgumentNullException : Value cannot be null. 
  Parameter name: stream</p>
  
  <p>at System.Windows.Media.StreamAsIStream.IStreamFrom(Stream stream)</p>
  
  <p>at System.Windows.Media.Imaging.BitmapEncoder.Save(Stream stream)</p>
  
  <p>at BitmapService.SaveBitmapAsPngImage(Uri path, BitmapSource renderBitmap)</p>
</blockquote>

<p>I prefer the Rhino mocks but here is the Moq test by <a href=""https://stackoverflow.com/a/49924817/213848"">@Nkosi</a>. Unfortunately, it is not working either:</p>

<pre><code>[TestMethod]
public void BitmapService_Should_SaveBitmapAsPngImage()
{
    //Arrange
    var mockedStream = Mock.Of&lt;Stream&gt;(_ =&gt; _.CanRead == true &amp;&amp; _.CanWrite == true);
    Mock.Get(mockedStream).SetupAllProperties();
    var fileSystemMock = new Mock&lt;IFileSystem&gt;();
    fileSystemMock
        .Setup(_ =&gt; _.OpenOrCreateFileStream(It.IsAny&lt;string&gt;()))
        .Returns(mockedStream);

    var sut = new BitmapService(fileSystemMock.Object);
    Size renderSize = new Size(100, 50);
    var renderBitmap = new RenderTargetBitmap(
        (int)renderSize.Width, (int)renderSize.Height, 96d, 96d, PixelFormats.Pbgra32);
    var path = new Uri(""//A_valid_path"");

    //Act
    sut.SaveBitmapAsPngImage(path, renderBitmap);

    //Assert
    Mock.Get(mockedStream)
        .Verify(_ =&gt; _.Write(It.IsAny&lt;byte[]&gt;(), It.IsAny&lt;int&gt;(), It.IsAny&lt;int&gt;()));
}
</code></pre>

<p>Moq test result:</p>

<blockquote>
  <p>BitmapServiceTest.BitmapService_Should_SaveBitmapAsPngImage threw
  exception:  System.IO.IOException: Cannot read from the stream. --->
  System.Runtime.InteropServices.COMException: Exception from HRESULT:
  0x88982F72
      at System.Windows.Media.Imaging.BitmapEncoder.Save(Stream stream)</p>
</blockquote>

<p>So the test tries to actually use that Stream.</p>

<hr>

<p>Class under test:</p>

<pre><code>using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using SystemInterface.IO;
using SystemWrapper.IO;

public interface IBitmapService
{
    void SaveBitmapAsPngImage(Uri path, BitmapSource renderBitmap);
}

public interface IBitmapEncoderFactory
{
    BitmapEncoder CreateBitmapEncoder();
}

public class PngBitmapEncoderFactory : IBitmapEncoderFactory
{
    public BitmapEncoder CreateBitmapEncoder()
    {
        return new PngBitmapEncoder();
    }
}

public class BitmapService : IBitmapService
{
    private readonly IFile _fileWrapper;
    private readonly IBitmapEncoderFactory _bitmapEncoderFactory;

    public BitmapService(IFile fileWrapper, IBitmapEncoderFactory bitmapEncoderFactory)
    {
        _fileWrapper = fileWrapper;
        _bitmapEncoderFactory = bitmapEncoderFactory;
    }

    public void SaveBitmapAsPngImage(Uri path, BitmapSource renderBitmap)
    {
        // Create a file stream for saving image
        using (IStream outStream = _fileWrapper
            .Open(path.LocalPath, FileMode.OpenOrCreate))
        {
            // Use bitmap encoder for our data
            BitmapEncoder bitmapEncoder = _bitmapEncoderFactory.CreateBitmapEncoder();
            // push the rendered bitmap to it
            bitmapEncoder.Frames.Add(BitmapFrame.Create(renderBitmap));

            // The problem: Expects real Stream as parameter!!!
            bitmapEncoder.Save(outStream.StreamInstance);
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/50045807/faking-stream-for-sealed-pngbitmapencoder,"['c#', 'unit-testing', 'moq', 'rhino-mocks']",261,TRUE,0,2
Mocking/stubbing JCo library using mockito framework,"<p>I am writing a basic Java program to connect to SAP server and retrieve a BAPI Function. This program is to basically showcase the importance of Unit Testing in development. However, while writing Unit Tests I would not like to really connect to the server and expect JCo return types. Considering this, I went ahead with Mockito framework to mock/stub some of the JCo libraries and it's methods. I would like to mention that I am new to Java and Mockito, however, I have good experience with C and C++. </p>

<p><strong>Main Code:</strong> </p>

<pre><code>package SAPConnection;

import java.util.Properties;

import com.sap.conn.jco.JCoDestination;
import com.sap.conn.jco.JCoDestinationManager;
import com.sap.conn.jco.JCoException;
import com.sap.conn.jco.JCoFunction;
import com.sap.conn.jco.ext.DestinationDataProvider;

public class sapConnection
{    
    public static JCoDestination getDestination() throws JCoException
    {
        JCoDestination destination = JCoDestinationManager.getDestination(DESTINATION_NAME1);
        return destination;
    }

    public static JCoFunction retrieveFunction(String funName, JCoDestination destination) throws JCoException
    {
        return(destination.getRepository().getFunction(funName)); 
    }

    public static void printMetaData(JCoFunction function)
    {
         System.out.println(function.getTableParameterList().getMetaData().toString());
         System.out.println(""MetaData Printed Successfully\n\n"");
    }    

    public static void main(String[] args) throws JCoException
    {
        JCoDestination Finaldestination = getDestination(); 
        JCoFunction function = 
        retrieveFunction(""ZBAPI_GET_DOCUMENTS"",Finaldestination);
        printMetaData(function);
    }
}
</code></pre>

<p><strong>Test Code</strong></p>

<pre><code>package SAPConnection;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

import com.sap.conn.jco.JCoDestination;
import com.sap.conn.jco.JCoDestinationManager;
import com.sap.conn.jco.JCoException;
import com.sap.conn.jco.JCoFunction;

public class testsapConnection {

public JCoDestinationManager destManager = Mockito.mock(JCoDestinationManager.class);
public JCoDestination destination=Mockito.mock(JCoDestination.class);
public JCoFunction function = Mockito.mock(JCoFunction.class);

@Test
public void testgetDestination() throws JCoException {
    when(destManager.getDestination(""ABAP_AS_WITHOUT_POOL"")).thenReturn(destination);
    assertEquals(destination,sapConnection.getDestination());
}
}
</code></pre>

<p>Rather than a straightforward solution, please explain the underlying mistakes and problems in these codes so that I can understand.</p>

<p>While running the test it says, </p>

<pre><code>org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'.
</code></pre>
",https://stackoverflow.com/questions/48852467/mocking-stubbing-jco-library-using-mockito-framework,"['java', 'unit-testing', 'mockito', 'jco']",588,TRUE,0,2
How to write C# unit test for proper code coverage in try catch block,"<p>I have the following code:</p>

<pre><code>public class MyControllerClass : ApiController  
{  
   private readonly IManager _manager;

   public MyControllerClass(IManager manager)
   {
     this._manager = manager;
   }

   pubic async Task&lt;IHttpActionResult&gt; GetRequest()  
   {  
     try  
       {  
         await this._manager.GetRequest();  
         return this.ok();  
       }  
     catch (Exception ex)  
      {  
         this.logger.Error(""Error message"", ex);  
         throw this.HTTPResponseException(""Request failed message"", ex);   
      }   
   }
} 

public class ManagerFake : IManagerFake  
{  
    public Task GetRequest()  
    {  
        return Task.FromResult(true);  
    }  
}     
</code></pre>

<p>I am using NUnit for the unit testing. For the unit tests I have a FakeManager class registered in my IOC container which contains the GetResult() method and simply returns Task.FromResult(true) when executed. This allows the logic in the try block to be executed and thus proper code coverage is met for that section. </p>

<p>The problem I'm having is how do I create a test using the same FakeManager class that will throw an exception so that the catch block logic will be executed and code coverage is satisfied when there is no way to make two unique calls to the GetRequest() method since it doesn't take input parameters which could be used to distinguish the two different calls ?  </p>
",https://stackoverflow.com/questions/50259855/how-to-write-c-unit-test-for-proper-code-coverage-in-try-catch-block,"['c#', 'unit-testing', 'nunit']",1864,TRUE,0,2
Swift how to unit test a function with dependencies,"<p>Hi I am new to mocking and stubbing as these are concepts I have heard about but haven't actually seen an example that explains how this works. I understand basic unit testing but I haven't found a place where I get an explanation with a simple example on mocks and stubs.</p>

<p>In my application I have these two functions which I would like to test but I do not know how to go about it since there is a dependency.</p>

<pre><code>private func setOverviewValues(weeklyData: CDPRewards, formattedTotal: String, displayMode: PointsDescriptionMode) {
    let monthYearString = createSubtitle(from: displayMode, with: weeklyData)
    view.setOverAllPoints(topValue: formattedTotal, bottomValue: monthYearString)
}
</code></pre>

<p>and</p>

<pre><code> private func createSubtitle(from displayMode: PointsDescriptionMode, with weeklyData: CDPRewards) -&gt; String {

    switch displayMode {
    case .weeklyPoints:
        if let monthString = weeklyData.month,
            let yearString = weeklyData.year {
            return displayMode.rawValue + monthString + "" "" + yearString
        }
        return PointsDescriptionMode.weeklyPoints.rawValue
    default:
        return displayMode.rawValue
    }
}
</code></pre>

<p>I would like help to show me how I can achieve testing of these functions or just a simple example that demonstrates mocking and stubbing. It would also be great to be pointed in the right direction in terms of books or blogs I can use.</p>
",https://stackoverflow.com/questions/49869668/swift-how-to-unit-test-a-function-with-dependencies,"['swift', 'unit-testing', 'mocking', 'stubbing']",188,TRUE,0,1
Android Appium performance issue after webelement.click(),"<p>Is there any reason whatsoever for huge performance issues after clicking an item that brings you up to another screen ?</p>

<p>I've successfully done some very nice and fast unit testing with <code>appium</code> in python over an android app. The problem is, everything works fast and fine, until I click an item that shows more products in a new screen. After that, every single call to <code>self.driver.find_element_by_id</code> or by whatever takes like 10 full seconds no matter what, before it was instant.</p>

<p>I did timing and performance testing, and after clicking the item with <code>.click()</code>, everything takes 10 full seconds to complete, which was instant before.</p>

<p>Is there any reason behind this that I'm missing ? Maybe because of switching to the new screen that might be a a different activity ?</p>

<p>Example:</p>

<pre><code>self.driver.find_element_by_id(""sticky"") &lt;= every call before this is pretty much instant
more_item.click()                        &lt;= this click ruins everything
sleep(5)
self.driver.find_element_by_id(""sticky"") &lt;= every call from now on, even if it's the same as above, takes 10 full seconds no matter what
</code></pre>
",https://stackoverflow.com/questions/53500217/android-appium-performance-issue-after-webelement-click,"['appium', 'appium-android', 'python-appium']",162,FALSE,0,1
Mockito : how to mock an autowired variable while testing,"<p>I'm unit testing my web application using JUnit and Mockito. At the moment i'm trying to write testcases for Service layer after completing the DAO level.
This is my test case: </p>

<pre><code>package it.********.testService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import static org.mockito.Mockito.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.assertj.core.api.Assertions.*;

import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;

import it.********.constants.EasycareEnumTypes.ActivityType;
import it.********.dao.interf.AccountDAOInterface;
import it.********.dao.interf.CareTeamDAOInterface;
import it.********.dao.interf.DeviceDAOInterface;
import it.********.dao.interf.ObservationDAOInterface;
import it.********.dto.DeviceDTO;
import it.********.dto.ObservationDTO;
import it.********.exception.ECForbiddenException;
import it.********.mapper.DeviceMapper;
import it.********.mapper.ObservationMapper;
import it.********.model.Account;
import it.********.model.Device;
import it.********.model.Observation;
import it.********.service.DeviceService;
import it.********.service.ObservationService;
import it.********.testConf.MockDAOUtils;
import it.********.testConf.MockDTOUtils;
import it.********.testConf.TestContext;
import it.********.utilities.DatetimeUtils;
import it.********.utilities.SessionVariable;

@ContextConfiguration(classes = {TestContext.class})
@ComponentScan({""it.********.service""})
public class ObservationServiceTest extends AbstractTransactionalJUnit4SpringContextTests {

    @Autowired
    private MockDAOUtils mockDAOUtils;

    @Mock
    SessionVariable sessionVariable;

    @Mock
    private ObservationDAOInterface observationDAOMock;

    @Mock
    private AccountDAOInterface accountDAOMock;

    @Mock
    private CareTeamDAOInterface careTeamDAOMock;

    @Spy
    private ObservationMapper mapper;

    @InjectMocks
    private ObservationService service;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
    }

    /**
     * {getObservationList}
     * 
     * [account]
     * -------------------------------------------------------------------------------------------------------
     * | id   | enabled | locked | account_expired | password_expired | data_handling | role                 |
     * -------------------------------------------------------------------------------------------------------
     * | 1000 | 1       | 0      | 0               | 0                | 1             | patient              |  targetAccount : valid patient account
     * | 1001 | 1       | 0      | 0               | 0                | 1             | general_practitioner |  callerAccount : medic in patient careteam
     * | 1002 | 1       | 0      | 0               | 0                | 0             | patient              |  targetAccount : invalid patient account
     * | 1003 | 1       | 0      | 0               | 0                | 1             | patient              |  callerAccount : patient with ID different from patientID
     * -------------------------------------------------------------------------------------------------------
     * 
     * [Observation]
     * ------------------------------------------------------------------------
     * | id | activity_type | medical_record_id | execution_date      | Note  |
     * ------------------------------------------------------------------------
     * | 1  | act_pressure  | 1                 | 2018-06-01 11:00:00 | Note1 |
     * | 2  | act_oximetry  | 1                 | 2018-06-01 14:00:00 | Note2 |
     * ------------------------------------------------------------------------
     * 
     */
    @Test
    public void test_case_u0048() throws Exception {

        // Taking method name
        String methodName = new Object() {
        }.getClass().getEnclosingMethod().getName();
        // Building test case file path
        String path = mockDAOUtils.getTc_path() + methodName + mockDAOUtils.getXml_ext();

        // Setting the test environment
        List&lt;Account&gt; accountList = mockDAOUtils.mockAccount(path);
        List&lt;Observation&gt; observationList = mockDAOUtils.mockObservation(path);
        List&lt;ActivityType&gt; activityTypeList = new ArrayList&lt;ActivityType&gt;();
        activityTypeList.add(ActivityType.act_pressure);
        activityTypeList.add(ActivityType.act_oximetry);
        Date startDate = mockDAOUtils.getFormat().parse(""2018-06-01 00:00:00"");
        Date endDate = mockDAOUtils.getFormat().parse(""2018-06-01 23:59:59"");


        // [RESULT CASE - VALID TARGET ACCOUNT / MEDIC CALLER ACCOUNT IN PATIENT CARE TEAM]
        Mockito.when(accountDAOMock.findByPersonId(1000L)).thenReturn(accountList.get(0));
        Mockito.when(careTeamDAOMock.isCareTeam(1000L, 1001L)).thenReturn(true);
        Mockito.when(sessionVariable.getTimezone()).thenReturn(""GMT-8:00"");
        System.out.println(""[SV] = "" + sessionVariable.getTimezone());
        Mockito.when(observationDAOMock.getListByMedRecIdAndActivityTypeAndDateRange(1L, activityTypeList, startDate, endDate)).thenReturn(observationList);
        List&lt;ObservationDTO&gt; observationDTOList = service.getObservationList(1000L, accountList.get(1), activityTypeList, startDate, endDate);

    }

}
</code></pre>

<p>Service Layer :</p>

<pre><code>package it.********.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import it.********.constants.EasycareEnumTypes.ActivityType;
import it.********.constants.EasycareEnumTypes.ApplicationRole;
import it.********.dao.interf.AccountDAOInterface;
import it.********.dao.interf.CareTeamDAOInterface;
import it.********.dao.interf.ObservationDAOInterface;
import it.********.dto.ObservationDTO;
import it.********.exception.ECForbiddenException;
import it.********.exception.ECNotFoundException;
import it.********.mapper.ObservationMapper;
import it.********.model.Account;
import it.********.model.Observation;
import it.********.utilities.DatetimeUtils;
import it.********.utilities.SessionVariable;

@ComponentScan({""it.********.mapper"",""it.********.dao.impl""})
@Service
@Transactional
public class ObservationService {

    @Autowired
    ObservationDAOInterface observationDAO;

    @Autowired
    SessionVariable sessionVariable;

    @Autowired
    ObservationMapper observationMapper;

    @Autowired
    AccountDAOInterface accountDAO;

    @Autowired
    CareTeamDAOInterface careTeamDAO;

    /**
     * Provide the list of ObservationDTO of the patient included in the period and matching the list of types
     * 
     * @param patientId id of the patient
     * @param activityTypes list of activity types
     * @param startDate beginning of the period
     * @param endDate end of the period
     * @return the list of observations, eventually empty
     * 
     */

    @Transactional(readOnly=true)
    public List&lt;ObservationDTO&gt; getObservationList(long patientId, Account callerAccount, List&lt;ActivityType&gt; activityTypes, Date startDate, Date endDate){  

        // target permission check      
        Account targetAccount = accountDAO.findByPersonId(patientId);
        if(targetAccount == null) {
            throw new ECNotFoundException();
        } else if (!targetAccount.isValid()){
            throw new ECForbiddenException();
        } else if (targetAccount.getFirstApplicationRole() != ApplicationRole.patient) {
            throw new ECForbiddenException();
        }

        // caller permission check
        switch (callerAccount.getFirstApplicationRole()) {
            case general_practitioner:
            case medical_specialist:
                if(!careTeamDAO.isCareTeam(targetAccount.getId(), callerAccount.getId())) {
                    throw new ECForbiddenException();
                }
                break;
            case patient:
                if(targetAccount.getId() != callerAccount.getId()){
                    throw new ECForbiddenException();
                }
                break;
            default:
                throw new ECForbiddenException();       
        }

        List&lt;Observation&gt; observationList = observationDAO.getListByMedRecIdAndActivityTypeAndDateRange(targetAccount.getMedicalRecord().getId(), activityTypes, startDate, endDate);
        List&lt;ObservationDTO&gt; observationDTOList = new ArrayList&lt;&gt;();

        for(Observation item : observationList){
            observationDTOList.add(observationMapper.convertToDTO(item));
        }

        return observationDTOList;      
    }

}
</code></pre>

<p>Mapper:</p>

<pre><code>package it.********.mapper;

import java.util.Map;
import java.util.TimeZone;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import it.********.constants.EasycareEnumTypes.ObservationExamType;
import it.********.constants.EasycareEnumTypes.ObservationParameterType;
import it.********.dto.ObservationDTO;
import it.********.dto.ScalarObservationDTO;
import it.********.dto.SignalObservationDTO;
import it.********.model.Observation;
import it.********.model.ObservationScalar;
import it.********.model.ObservationSignal;
import it.********.utilities.DatetimeUtils;
import it.********.utilities.SessionVariable;

@Component
public class ObservationMapper extends Mapper&lt;ObservationDTO,Observation&gt; {

    @Autowired
    SessionVariable sessionVariable;

    @Autowired
    ScalarObservationMapper scalarMapper;

    @Override
    public ObservationDTO convertToDTO(Observation entity) {
        ObservationDTO observationDTO = new ObservationDTO();
        observationDTO.setActivityType(entity.getActivityType());
        observationDTO.setActivityLabel(entity.getActivityType().getLabelCode());
        //observationDTO.setScheduleActivityId(entity.getScheduleActivity() != null ? entity.getScheduleActivity().getId() : null);
        observationDTO.setMedicalRecordId(entity.getMedicalRecord().getId());
        System.out.println(""[SV] = "" + sessionVariable.getTimezone());
        observationDTO.setExecutionDate(DatetimeUtils.dateToDatetimeISO8601(entity.getExecutionDate(),TimeZone.getTimeZone(sessionVariable.getTimezone())));
        observationDTO.setId(entity.getId());
        observationDTO.setNote(entity.getNote());

        for(ObservationScalar entityScalarObs : entity.getScalarObservationList()){
            ScalarObservationDTO scalarObsDTO = scalarMapper.convertToDTO(entityScalarObs);         
            observationDTO.getScalarObservationList().put(scalarObsDTO.getParameterType(), scalarObsDTO);
        }

        SignalObservationMapper signalMapper = new SignalObservationMapper();
        for(ObservationSignal entitySignalObs : entity.getSignalObservationList()){
            SignalObservationDTO signalObsDTO = signalMapper.convertToDTO(entitySignalObs);         
            observationDTO.getSignalObservationList().put(signalObsDTO.getType(), signalObsDTO);
        }

//      Hibernate.initialize(observationDTO.getScalarObservationList());
//      Hibernate.initialize(observationDTO.getSignalObservationList());
        return observationDTO;
    }

    @Override
    public Observation convertToEntity(ObservationDTO dto) {
        Observation observation = new Observation();
        observation.setActivityType(dto.getActivityType());
        observation.setExecutionDate(DatetimeUtils.stringToDate(dto.getExecutionDate()));
        observation.setNote(dto.getNote());

        for(Map.Entry&lt;ObservationParameterType,ScalarObservationDTO&gt; scalarObsDTO : dto.getScalarObservationList().entrySet()){
            if (scalarObsDTO.getValue() != null){//empty field
                observation.getScalarObservationList().add(scalarMapper.convertToEntity(scalarObsDTO.getValue()));
            }
        }

        SignalObservationMapper signalMapper = new SignalObservationMapper();
        for(Map.Entry&lt;ObservationExamType,SignalObservationDTO&gt; signalObsDTO : dto.getSignalObservationList().entrySet()){
            if (signalObsDTO.getValue() != null){
                observation.getSignalObservationList().add(signalMapper.convertToEntity(signalObsDTO.getValue()));
            }
        }       

        return observation;
    }

    @Override
    public void updateEntity(ObservationDTO dto, Observation entity) {
        // TODO Auto-generated method stub

    }

}
</code></pre>

<p>My problem comes while trying to test the ""getObservationList"" method of the Service : everything I mocked works good until I go to the mapper, where i got NullPointerException here </p>

<p>observationDTO.setExecutionDate(DatetimeUtils.dateToDatetimeISO8601(entity.getExecutionDate(),TimeZone.getTimeZone(sessionVariable.getTimezone())));</p>

<p>I think that the sessioVariable is null due to the fact that it isn't initialized in my test context, so I'm trying to mock o do some stuff to let me have a valid sessionVariable (the content is not important at this moment) not modifying nothing in Service and Mapper.</p>

<p>Thanks in advance! Bye!</p>
",https://stackoverflow.com/questions/52559794/mockito-how-to-mock-an-autowired-variable-while-testing,"['java', 'testing', 'junit', 'mockito', 'jacoco']",2232,TRUE,0,2
Should ViewModel class contain Android elements?,"<p>Moving from MVP to MVVM and trying to learn from tutorials on web.</p>

<p>Some of the tutorials state that ViewModel classes should not have any reference to Activity or View(android.view.View) classes.</p>

<p>But in some of the tutorials i've seen Views are used in ViewModel class and Activities to start other Activities using ViewModel.
<a href=""https://www.journaldev.com/20292/android-mvvm-design-pattern"" rel=""nofollow noreferrer"">For example:</a></p>

<pre><code>import android.arch.lifecycle.ViewModel;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;

import com.journaldev.androidmvvmbasics.interfaces.LoginResultCallback;
import com.journaldev.androidmvvmbasics.model.User;

public class LoginViewModel extends ViewModel {
    private User user;
    private LoginResultCallback mDataListener;

    LoginViewModel(@NonNull final LoginResultCallback loginDataListener) {
        mDataListener = loginDataListener;
        user = new User("""", """");
    }


    public TextWatcher getEmailTextWatcher() {
        return new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                user.setEmail(editable.toString());
            }
        };
    }

    public TextWatcher getPasswordTextWatcher() {
        return new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                user.setPassword(editable.toString());
            }
        };
    }


    public void onLoginClicked(@NonNull final View view) {
        checkDataValidity();
    }

    private void checkDataValidity() {
        if (user.isInputDataValid())
            mDataListener.onSuccess(""Login was successful"");
        else {
            mDataListener.onError(""Email or Password not valid"");
        }
    }
}
</code></pre>

<p><a href=""https://labs.ribot.co.uk/approaching-android-with-mvvm-8ceec02d5442"" rel=""nofollow noreferrer"">Another one</a> with <code>View.OnClickListener</code></p>

<pre><code>public class PostViewModel extends BaseObservable {

    private Context context;
    private Post post;
    private Boolean isUserPosts;

    public PostViewModel(Context context, Post post, boolean isUserPosts) {
        this.context = context;
        this.post = post;
        this.isUserPosts = isUserPosts;
    }

    public String getPostScore() {
        return String.valueOf(post.score) + context.getString(R.string.story_points);
    }

    public String getPostTitle() {
        return post.title;
    }

    public Spannable getPostAuthor() {
        String author = context.getString(R.string.text_post_author, post.by);
        SpannableString content = new SpannableString(author);
        int index = author.indexOf(post.by);
        if (!isUserPosts) content.setSpan(new UnderlineSpan(), index, post.by.length() + index, 0);
        return content;
    }

    public int getCommentsVisibility() {
        return  post.postType == Post.PostType.STORY &amp;&amp; post.kids == null ? View.GONE : View.VISIBLE;
    }

    public View.OnClickListener onClickPost() {
        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Post.PostType postType = post.postType;
                if (postType == Post.PostType.JOB || postType == Post.PostType.STORY) {
                    launchStoryActivity();
                } else if (postType == Post.PostType.ASK) {
                    launchCommentsActivity();
                }
            }
        };
    }

    public View.OnClickListener onClickAuthor() {
        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                context.startActivity(UserActivity.getStartIntent(context, post.by));
            }
        };
    }

    public View.OnClickListener onClickComments() {
        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                launchCommentsActivity();
            }
        };
    }

    private void launchStoryActivity() {
        context.startActivity(ViewStoryActivity.getStartIntent(context, post));
    }

    private void launchCommentsActivity() {
        context.startActivity(CommentsActivity.getStartIntent(context, post));
    }
}
</code></pre>

<p><a href=""https://medium.com/tech-travelstart/android-data-binding-mvvm-4888eb73a25d"" rel=""nofollow noreferrer"">Another one</a> with Activity Reference</p>

<pre><code>public class UserProfileViewModel {

    /* ------------------------------ Constructor */

    private Activity activity;

    /* ------------------------------ Constructor */

    UserProfileViewModel(@NonNull Activity activity) {
        this.activity = activity;
    }

    /* ------------------------------ Main method */

    /**
     * On profile image clicked
     *
     * @param userName name of user
     */
    public void onProfileImageClicked(@NonNull String userName) {

        Bundle bundle = new Bundle();
        bundle.putString(""USERNAME"", userName);
        Intent intent = new Intent(activity, UserDetailActivity.class);
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

     /**
     * @param editable         editable
     * @param userProfileModel the model of user profile
     */
    public void userNameTextChange(@NonNull Editable editable,
                                   @NonNull UserProfileModel userProfileModel) {

        userProfileModel.setUserName(editable.toString());
        Log.e(""ViewModel"", userProfileModel.getUserName());
    }
}
</code></pre>

<ol>
<li><p>Is it okay for ViewModel class to contain Android and View classes,
isn't this bad for unit testing?</p></li>
<li><p>Which class should a custom view model class extend? <code>ViewModel</code> or
    <code>BaseObservable/Observable</code>?</p></li>
<li>Is there any tutorial link that shows simple usage of MVVM and with
only focus on architecture without any Dagger2, LiveData, or RxJava
extensions? I'm only looking for MVVM tutorials for now.</li>
</ol>
",https://stackoverflow.com/questions/50946050/should-viewmodel-class-contain-android-elements,"['android', 'mvvm']",1217,TRUE,0,1
pytest 3.4.2 test py code has to be written in the respective application code python version only?,"<p>We are using python 2.7.4 in our project application code and planning to use pytest 3.4.2 version for unit testing. In future we might upgrade our application code to latest python 3.6.X.</p>

<p>Given that pytest 3.4.X supports both python 2.7 and > 3.3 versions, the test code files ( Example: test_mymodule.py) has to be written in any python version or it has to be written on the python version used for the application code. </p>

<p>To exactly pin point the question,</p>

<p>Application code with python 2.7.x version --> the corresponding test code with pytest has to be written in 2.7.x compatible code or it can even be written with python 3.4 version compatible code?. Will pytest understand the test code accordingly and run the test files?.</p>
",https://stackoverflow.com/questions/49351165/pytest-3-4-2-test-py-code-has-to-be-written-in-the-respective-application-code-p,"['python', 'python-3.x', 'python-2.7', 'pytest']",61,TRUE,0,1
How to write unit test for DataTable in React Component using Enzyme with Jest?,"<p>I am new to React Unit testing. I had built a React Component that renders a <a href=""http://datatables.net"" rel=""nofollow noreferrer"">DataTable</a>, which takes <code>column names</code> and <code>data</code> as props. I had written unit test for table element using Enzyme with Jest, which is <code>PASSED</code>. Unit Test is </p>

<pre><code>describe('Client Component Testing', () =&gt; {

    let mountedClientComp;
    const clientComp = () =&gt; {
        if (!mountedClientComp) {
            mountedClientComp = mount(
                &lt;ClientsTable/&gt;
            );
        }
        return mountedClientComp;
    };

    it('Client component renders a table', () =&gt; {
        const table = clientComp();
        table.setState({ temp: true });
        table.update();
        expect(table.exists('table')).toEqual(true);
    });
});
</code></pre>

<p>But am not getting, how to write unit test for DataTable Search Field, Pagination buttons, Table Info, Table Length, Sorting elements.</p>

<p>DataTable manipulates DOM by taking <code>table</code> html tag into DataTable object, and since <code>table</code> html tag is written in React component, unit test for table element <code>PASSED</code>.</p>

<p>But for testing DataTable Search input field, am finding <code>input</code> element, which is not written and which will be dynamically appended, so am not getting how to write unit test!? </p>

<p>How to write unit test for dynamically added elements?</p>

<p>Regards [Shashidhar]</p>
",https://stackoverflow.com/questions/52700086/how-to-write-unit-test-for-datatable-in-react-component-using-enzyme-with-jest,"['jquery', 'reactjs', 'datatables', 'jestjs', 'enzyme']",3136,FALSE,0,1
VisualStudio Not Recognized in Using Statement,"<p>I am trying to reference a DLL for unit testing in visual studio.  I added the reference, then added the using statement, but the reference isn't being recognized (See image below).  I get an error stating ""The type or namespace name 'Visual Studio' does not exist in the namespace 'Microsoft' (are you missing and assembly reference?)"".  I searched other posts with similar issues and a common solution was changing the target framework.  I can't tell if I am having that issue or not.  The target framework is currently set to .NET Framework 4.6.1  I tried setting it to framework 4 because I saw that as a solution in a couple posts, but it didn't change anything. Any ideas why the reference is not being recognized?</p>

<p><img src=""https://i.stack.imgur.com/PuCo0.jpg"" alt=""Screen Shot of Ref and Using Statement""></p>
",https://stackoverflow.com/questions/53018720/visualstudio-not-recognized-in-using-statement,"['c#', 'visual-studio', 'reference']",263,FALSE,0,0
Why is my jest async action creator test not working?,"<p>I am very new to unit testing, and am trying to go through my react-redux project to write some tests. </p>

<p>Why is this test not working, and how could I make it pass? </p>

<p>Here is the test. I want to test my fetch posts action creator. This is for a small blog application.:</p>

<pre><code>import configureStore from 'redux-mock-store'; // ES6 modules
import { findSinglePost, sendEdit, changeRedirect, checkBoxChange } from '../client/redux/actions/postActions';
import thunk from 'redux-thunk';
import axios from 'axios';

const middlewares = [thunk];
const mockStore = configureStore(middlewares);
describe('asynchronous action creators', () =&gt; {

  it('should fetch posts', () =&gt; {
    let store = mockStore({})

    //my async action creator. It uses mock data that's in the same folder.
    const fetchPosts = () =&gt; function(dispatch) {
      dispatch({type: 'FETCH_POSTS'});

      return axios.get('./MOCK.json').then((response) =&gt; {
        dispatch({type: 'FETCH_POSTS_FUFILLED', payload: response.data});
      }).catch((err) =&gt; {
        dispatch({type: 'FETCH_POSTS_REJECTED', payload: err});
      });
    };
    //this doesn't equal FETCH_POSTS_FUFILLED, it ends up equaling just ""FETCH_POSTS""
    return store.dispatch(fetchPosts()).then(() =&gt; {
      const actions = store.getActions();
      expect(actions[0]).toEqual({type: 'FETCH_POSTS_FUFILLED'});
    })
  })
});
</code></pre>

<p>Here is jest's feedback. I want it to equal 'FETCH_POSTS_'FUFILLED', but it's returning 'FETCH_POSTS'. :</p>

<pre><code> FAIL  _test_\actions.test.js
  ● asynchronous action creators › should fetch posts

    expect(received).toEqual(expected)

    Expected value to equal:
      {""type"": ""FETCH_POSTS_FUFILLED""}
    Received:
      {""type"": ""FETCH_POSTS""}

    Difference:

    - Expected
    + Received

      Object {
    -   ""type"": ""FETCH_POSTS_FUFILLED"",
    +   ""type"": ""FETCH_POSTS"",
      }

      88 |     return store.dispatch(fetchPosts()).then(() =&gt; {
      89 |       const actions = store.getActions();
    &gt; 90 |       expect(actions[0]).toEqual({type: 'FETCH_POSTS_FUFILLED'});
      91 |     })
      92 |   })
      93 | });

      at _test_/actions.test.js:90:26

 PASS  client\views\LoginPage\LoginPage.test.jsx

Test Suites: 1 failed, 1 passed, 2 total
Tests:       1 failed, 5 passed, 6 total
Snapshots:   0 total
Time:        1.49s
Ran all test suites related to changed files.
</code></pre>

<p>Also, here is the project's github <a href=""https://github.com/capozzic1/react-blog"" rel=""nofollow noreferrer"">repo</a> if you want to try to run it.</p>

<p>Also, if there's a standard way in the industry that's more well known on how to do this, I'd love the advice. </p>

<p>Edit: </p>

<p>When I change actions[0] to <strong>actions[ 1]</strong> I get this error: </p>

<pre><code>Expected value to equal:
  {""type"": ""FETCH_POSTS_FUFILLED""}
Received:
  {""payload"": {Symbol(impl): {""message"": ""The string did not match the expected pattern."", ""name"": ""SyntaxError"", Symbol(wrapper): [Circular]}}, ""type"": ""FETCH_POSTS_REJECTED""}

Difference:

- Expected
+ Received

  Object {
-   ""type"": ""FETCH_POSTS_FUFILLED"",
+   ""payload"": DOMException {
+     Symbol(impl): DOMExceptionImpl {
+       ""message"": ""The string did not match the expected pattern."",
+       ""name"": ""SyntaxError"",
+       Symbol(wrapper): [Circular],
+     },
+   },
+   ""type"": ""FETCH_POSTS_REJECTED"",
</code></pre>

<p>Here is the picture form of jest's feedback:
<a href=""https://i.stack.imgur.com/Lypjg.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Lypjg.png"" alt=""""></a></p>
",https://stackoverflow.com/questions/48636394/why-is-my-jest-async-action-creator-test-not-working,"['unit-testing', 'jestjs', 'redux-mock-store']",1266,TRUE,0,1
RestAssuredMockMvc - Request processing failed; nested exception is java.lang.NullPointerException,"<p>I am trying to mock some of the web services and controllers for the integration tests using RestAssured. I am able to run the tests using real time container i.e. starting spring boot from eclipse and running test on <code>http://localhost:8080/ws/testapi</code></p>

<p>But I am unable to mock it using <code>RestAssuredMockMvc</code> and it says </p>

<pre><code>`org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
    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:160)
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:127)
    at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155)
    at io.restassured.module.mockmvc.internal.MockMvcRequestSenderImpl.performRequest(MockMvcRequestSenderImpl.java:195)
    at io.restassured.module.mockmvc.internal.MockMvcRequestSenderImpl.sendRequest(MockMvcRequestSenderImpl.java:431)
    at io.restassured.module.mockmvc.internal.MockMvcRequestSenderImpl.get(MockMvcRequestSenderImpl.java:609)
    at io.restassured.module.mockmvc.internal.MockMvcRequestSenderImpl.get(MockMvcRequestSenderImpl.java:76)
    at com.ashland.vioc.pos.webservice.webmvc.controller.CarFaxProxyControllerIntegrationTest_RAMock.testGetServicesByVin_success_aroundBody2(CarFaxProxyControllerIntegrationTest_RAMock.java:74)
    at com.ashland.vioc.pos.webservice.webmvc.controller.CarFaxProxyControllerIntegrationTest_RAMock$AjcClosure3.run(CarFaxProxyControllerIntegrationTest_RAMock.java:1)
    at org.springframework.transaction.aspectj.AbstractTransactionAspect.ajc$around$org_springframework_transaction_aspectj_AbstractTransactionAspect$1$2a73e96cproceed(AbstractTransactionAspect.aj:66)
    at org.springframework.transaction.aspectj.AbstractTransactionAspect$AbstractTransactionAspect$1.proceedWithInvocation(AbstractTransactionAspect.aj:72)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
    at org.springframework.transaction.aspectj.AbstractTransactionAspect.ajc$around$org_springframework_transaction_aspectj_AbstractTransactionAspect$1$2a73e96c(AbstractTransactionAspect.aj:70)
    at com.ashland.vioc.pos.webservice.webmvc.controller.CarFaxProxyControllerIntegrationTest_RAMock.testGetServicesByVin_success(CarFaxProxyControllerIntegrationTest_RAMock.java:67)
    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.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.NullPointerException
    at com.ashland.vioc.pos.webservice.webmvc.controller.CarFaxProxyController.getServicesByVin(CarFaxProxyController.java:40)
    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: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)
    ... 49 more

`
</code></pre>

<p>I am new to Spring and only involved with unit testing the application. Not sure if we need to make some configuration changes in order to mock it. I referred <a href=""https://github.com/rest-assured/rest-assured/wiki/Usage#spring-mock-mvc-module"" rel=""nofollow noreferrer"">https://github.com/rest-assured/rest-assured/wiki/Usage#spring-mock-mvc-module</a>
 but unable to find much info or may be I am missing something.</p>

<pre><code>package com.hl.pos.webservice.controller;

import static com.ashland.vioc.pos.webservice.carfax.CarFaxServiceImplIntegrationTest.*;
import static org.hamcrest.Matchers.*;
import static io.restassured.module.mockmvc.RestAssuredMockMvc.*;   
import javax.inject.Inject;    
import org.junit.Before;
import org.junit.Test;
import com.ashland.vioc.pos.webservice.master.domain.StoreDataOnDemand;

@Category(MockControllerIntegrationTest.class)
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles(Profiles.TESTING_MOCK_MVC)
@Transactional
@AutoConfigureMockMvc
public class CarControllerIntegrationTest {

    private static final String REQUEST_MAPPING = ""/ws/v1/car"";
    @Autowired
    protected WebApplicationContext wac;

    @Before
    public void setUp(){
       RestAssuredMockMvc.webAppContextSetup(wac);
       RestAssuredMockMvc.standaloneSetup(new CarController());
    }

    @Test
    public void testGetServices() throws Exception {
        final String cnum= VALID_CNUM;
        final String store = ""1234"";
        given().
                standaloneSetup(new CarController()).
                param(""storeNum"",storeNumber).
       // given().
                //param(""store"",store).
        when().
            get(REQUEST_MAPPING + ""/v/{cnum}/carHistory"",cnum).
        then().
            assertThat().statusCode(200).
            body(""carDetails[0].serviceDate"",notNullValue());
    }

}
</code></pre>

<p>Same test runs fine with <code>Mockmvc</code> in the same file with same configuration and the problem is only with RestAssured.</p>

<pre><code>@Test
        public void testGetServices() throws Exception {
            final String cnum= VALID_CNUM;
            final String store = ""1234"";
            mockMvc.perform(get(REQUEST_MAPPING + ""/v/{cnum}/carHistory"", cnum).with(params().storeNum(storeNumber)))
                .andExpect(200);
        }
</code></pre>
",https://stackoverflow.com/questions/49277529/restassuredmockmvc-request-processing-failed-nested-exception-is-java-lang-nu,"['unit-testing', 'spring-boot', 'mocking', 'rest-assured']",3359,FALSE,0,1
Testing with Jest a method in React that calls another irrelevant method to the test,"<p>Learning unit-testing, I am trying to use Jest to test React components. But i ran into an error while testing a method of a component that calls another method, that resides into another project entirely and then the parent method changes the state of it's component, so everything on the other method that is being called is normally undefined, therefore resulting on this test error. Can anyone guide me how to approach this problem? Supposing that the method being tested is:</p>

<pre><code>methodToBeTested() {
    methodResidingIntoAnotherProject();
    this.setState({someState: true}); // someState is initially false
}
</code></pre>

<p>And the testing:</p>

<pre><code>describe(""testing the component's behaviour""), () =&gt; {
    it(""testing the methodToBeTested"", () =&gt; {
       const {wrapper} = setup();
       wrapper.setState({someState: false});
       wrapper.instance().methodToBeTested();

    expect(wrapper.state().someState).toEqual(true);
    });
});
</code></pre>

<p>The <code>wrapper</code> and the whole <code>setup</code> works, because i have tried some other structural tests, that have passed. The error that is being thrown is: 
""TypeError: Cannot read property 'someVariable' of undefined"". The 'someVariable' is in the nested method.</p>
",https://stackoverflow.com/questions/48401241/testing-with-jest-a-method-in-react-that-calls-another-irrelevant-method-to-the,"['javascript', 'reactjs', 'unit-testing', 'jestjs']",401,FALSE,0,0
Core Data entity name is nil while running a second unit test,"<p>I am trying to add some unit tests for my Core Data code. But I always have this issue, the first test always run correctly, but the second one crashes because entity name is nil.  </p>

<p>I also get this error:</p>

<pre><code>Multiple NSEntityDescriptions claim the NSManagedObject subclass 'Gym.Exercise' so +entity is unable to disambiguate.

Failed to find a unique match for an NSEntityDescription to a managed object subclass
</code></pre>

<p>So my guess is that I am not doing something right in <code>tearDown().</code></p>

<pre><code>override func setUp() {
    super.setUp()

    coreDataStack = CoreDataStack(storeType: .inMemory)
    context = coreDataStack.context
}

override func tearDown() {
    coreDataStack.reset()
    context = nil
    super.tearDown()
}
</code></pre>

<p>Here is my <code>CoreDataStack</code> class:</p>

<pre><code>final class CoreDataStack {
    var storeType: StoreType!
    public init(storeType: StoreType) {
        self.storeType = storeType
    }

    lazy var persistentContainer: NSPersistentContainer = {
        let container = NSPersistentContainer(name: ""Gym"")
        container.loadPersistentStores { description, error in
            if let error = error {
                fatalError(""Unresolved error \(error), \(error.localizedDescription)"")
            } else {
                description.type = self.storeType.type

            }
        }

        return container
    }()

    public var context: NSManagedObjectContext {
        return persistentContainer.viewContext
    }

    public func reset() {
        guard let store = persistentContainer.persistentStoreCoordinator.persistentStores.first else { fatalError(""No store found"")}
        guard let url = store.url else { fatalError(""No store URL found"")}

        try! FileManager.default.removeItem(at: url)
        NSPersistentStoreCoordinator.destroyStoreAtURL(url: url)
    }
}
</code></pre>

<p>And the definition to <code>destroyStoreAtURL</code>:</p>

<pre><code>extension NSPersistentStoreCoordinator {
    public static func destroyStoreAtURL(url: URL) {
        do {
            let psc = self.init(managedObjectModel: NSManagedObjectModel())
            try psc.destroyPersistentStore(at: url, ofType: NSSQLiteStoreType, options: nil)
        } catch let e {
            print(""failed to destroy persistent store at \(url)"", e)
        }
    }
}
</code></pre>

<p>I was using this code in the past for unit testing and it works, the difference is that in the past when I setup the <code>NSManagedObject</code> classes in editor I used the following config:</p>

<pre><code>Module - Global namespace
Codegen - Class Definition
</code></pre>

<p>Now I use:</p>

<pre><code>Module - Current Product Module
Codegen - Manual/None
</code></pre>

<p>Because I want to add my classes manually.  </p>

<p>So does anyone know why the behavior is different now ?</p>

<p>edit - my NSManagedObject extension helper (the error occurs inside the first line of fetch() method when trying to retrieve the entity name):</p>

<pre><code>extension Managed where Self: NSManagedObject {

    public static var entityName: String {
        return entity().name!
    }

    public static func fetch(in context: NSManagedObjectContext, configurationBlock: (NSFetchRequest&lt;Self&gt;) -&gt; () = { _ in }) -&gt; [Self] {
        let request = NSFetchRequest&lt;Self&gt;(entityName: Self.entityName)
        configurationBlock(request)
        return try! context.fetch(request)
    }

    public static func count(in context: NSManagedObjectContext, configure: (NSFetchRequest&lt;Self&gt;) -&gt; () = { _ in }) -&gt; Int {
        let request = NSFetchRequest&lt;Self&gt;(entityName: entityName)
        configure(request)
        return try! context.count(for: request)
    }

    public static func findOrFetch(in context: NSManagedObjectContext, matching predicate: NSPredicate) -&gt; Self? {
        guard let object = materializeObject(in: context, matching: predicate) else {
        return fetch(in: context) { request in
                request.predicate = predicate
                request.returnsObjectsAsFaults = false
                request.fetchLimit = 1
            }.first
        }

        return object
    }

    public static func materializeObject(in context: NSManagedObjectContext, matching predicate: NSPredicate) -&gt; Self? {
        for object in context.registeredObjects where !object.isFault {
           guard let result = object as? Self, predicate.evaluate(with: result) else {
               continue
           }

           return result
        }

        return nil
    }

    public static func findOrCreate(in context: NSManagedObjectContext, matching predicate: NSPredicate, configure: (Self) -&gt; ()) -&gt; Self {
        guard let object = findOrFetch(in: context, matching: predicate) else {
           let newObject: Self = context.insertObject()
           configure(newObject)
           return newObject
        }

        return object
    }
}
</code></pre>
",https://stackoverflow.com/questions/53681686/core-data-entity-name-is-nil-while-running-a-second-unit-test,"['ios', 'swift', 'core-data']",631,TRUE,9,1
Should anyone use unit test library methods and classes in live development environment?,"<p>This questions looks weird or may be pointless at all.
Recently, I was reviewing some code in java language where the developer used one of the methods from a unit testing library ""org.easytesting"".
Example: He was using a method ""Strings.isNullOrEmpty"" of ""Strings"" class from this library to verify the non-nullability of some values and was using other classes/methods at other places in the code.</p>

<p>I know a library is developed to make our life easier(basic principles of Java) and can be used anywhere/everywhere, but is there a recommendation about using a unit test library in live development code ?
I know using it won't led to a compatibility issue because unit test cases are executed always.</p>

<p>I searched at many places may be I'm missing a good word to search.</p>
",https://stackoverflow.com/questions/53058533/should-anyone-use-unit-test-library-methods-and-classes-in-live-development-envi,"['java', 'unit-testing']",692,TRUE,4,3
Error:Cannot find class in classpath: testCases.MyClassName &amp; errors in class after deleting .m2,"<p>I am working on Selenium testNg framework, and I get this error:</p>

<pre><code>Cannot find class in classpath: testCases.MyClassName.
</code></pre>

<p>I am facing this error after I pulled the updated code from <code>git</code> and made changes to the code in my local but did not commit it and trying to perform unit testing in my local. I did project clean, maven clean and install. Updated the project and tried running the code again and received same error message. I checked the classname &amp; package name in <code>testing.xml</code> and they are correct, as suggested by my friend to delete <code>.m2</code> repository, restart eclipse and pull the code. I deleted <code>.m2</code> repository, restarted and saw errors in all the test cases in the package, and could not pull the code. 
Could you please suggest on how to resolve this issue?</p>
",https://stackoverflow.com/questions/50846240/errorcannot-find-class-in-classpath-testcases-myclassname-errors-in-class-af,"['java', 'eclipse', 'git', 'maven']",141,FALSE,0,1
Maximum serialization depth exceeded,"<p>I get the error ""maximum serialization depth exceeded"" when trying to push new data on MongoDB.  When unit testing on localhost with MongoDB Community, it works with no problems.  Any help would be appreciated.  I'm also not seeing a Circular Reference.</p>

<p>This is the function that kicks off the saving of the data.  First to my local cache then to the cloud (MongoDB).</p>

<pre><code>///Calling function
public async Task AddComment(Range item, Comment commentItem)
{
    try
    {
        //Save to local cache
        item.Comments.Add(commentItem);

        //Next save to cloud
        await CloudStorage.AddComment(item.User.ID, item.ID, commentItem);
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex);
    }
}

//--&gt;ERROR HAPPENS LAST LINE HERE&lt;--
public async Task&lt;UpdateResult&gt; AddComment(string ownerID, string rangeID, Comment comment)
{
    var filter = Builders&lt;User&gt;.Filter.Where(u =&gt; u.ID == ownerID &amp;&amp;
                                                  u.Content.Any(i =&gt; i.ID == rangeID));
    var update = Builders&lt;User&gt;.Update.Push(c =&gt; c.Content[-1].Comments, comment);
    return await collection.UpdateOneAsync(filter, update); //&lt;- THIS THROWS ERROR
}
</code></pre>

<p>Here's the unit test that works with localhost.</p>

<pre><code>[TestMethod]
public void TestInsertComment()
{
    //Arrange
    var owner = ""OWNER"";

    var ownerData = collection.Find(u =&gt; u.Username.Equals(owner)).FirstOrDefault();
    var ownerID = ownerData?.ID;
    var range = ownerData?.Content.FirstOrDefault();

    var newComment = new Comment
    {
        User = range?.User,
        Content = ""Some comment"",
        IsLive = true
    };

    //Act
    var results = _cloudStorageService.AddComment(ownerID, range?.ID, newComment);
    results.Wait();

    var insertedID = collection.Find(u =&gt; u.Username.Equals(owner))
                               .FirstOrDefault().Content.FirstOrDefault()?
                               .Comments.FirstOrDefault(c =&gt; c.ID.Equals(newComment.ID))?.ID;

    //Assert
    Assert.AreEqual(newComment.ID, insertedID);
}
</code></pre>

<p><strong>UPDATE:</strong> One thing I noticed is if the same user tries to add a comment to their range, that's the only time this error occurs.  If another user adds a comment, it works just fine.  And the unit test works fine all the time regardless of if it's same user or other user.</p>
",https://stackoverflow.com/questions/50100470/maximum-serialization-depth-exceeded,"['c#', 'mongodb', 'mongodb-atlas']",1566,TRUE,-1,1
Creating public methods in class and not in interface,"<p>I've come across an issue whether it is a good idea to create public methods/properties inside a class </p>

<pre><code>public class MyClass : IMyClass
</code></pre>

<p>but not in the interface </p>

<pre><code>public interface IMyClass
</code></pre>

<p>mainly for the purpose of unit testing implemented methods from <code>IMyClass</code> inside  <code>MyClass</code>. I want to have access from my unit tests to implementation details inside class <code>MyClass</code> to check if some fields meet the expectations. Additionaly, I don't want to expose these details through my interface.</p>

<p>On the other hand, I have a feeling that everything public inside <code>MyClass</code> should be exposed in the interface <code>IMyClass</code>, since this is the case of access modifiers:
 <code>public</code> to expose information, <code>private</code> to hide details.</p>

<p>So, my the question is: Is it good to create public methods/properties inside a class <code>MyClass</code>, but not in the interface <code>IMyClass</code>?</p>
",https://stackoverflow.com/questions/53260961/creating-public-methods-in-class-and-not-in-interface,"['unit-testing', 'oop', 'language-agnostic', 'access-modifiers']",65,TRUE,0,1
How to register a service in ASP.NET Core that is created by a factory?,"<p>I am getting the following error:</p>

<blockquote>
  <p>Unable to resolve service for type 'IMyRepository' while attempting to activate 'MyController'.</p>
</blockquote>

<p>I understand that my application is failing on the dependency injection.</p>

<p>However I'm not sure how to correct this error.</p>

<p>My IMyRepository looks lie this:</p>

<pre><code>public interface IMyRepository
{
  public Delete(Guid Id);
  public Get(Guid Id);
  //etc..
}
</code></pre>

<p>We set the following interface up when we created the unit tests.</p>

<pre><code>public IMyRepositoryFactory
{
  IRepository CreateRepository();
}
</code></pre>

<p>The constructor in my Controller:</p>

<pre><code>private readonly IRepository _repo;

public MyController(IRepository repo)
{
   _repo = repo;
}
</code></pre>

<p>I can pass the factory into the constructor, however that would require me to redo the unit testing modules since they are all passing IRepository to the controller.</p>

<pre><code>Ex. (In Startup ConfigureServices)
services.AddTransient&lt;IMyRepositoryFactory, ConcreteRepositoryFactory&gt;();
</code></pre>

<p>I would prefer to leave the controller constructors and testing classes as is. So is there a way to setup DI in this scenario (Where I am passing the IRepository to the controller)?</p>

<p>EDIT:</p>

<pre><code>public class ConcreteRepositoryFactory : IMyRepositoryFactory
{
    public ConcreteRepositoryFactory(string connString);
    public IMyRepository CreateRepository();
}
</code></pre>
",https://stackoverflow.com/questions/49369195/how-to-register-a-service-in-asp-net-core-that-is-created-by-a-factory,"['c#', 'asp.net-core', 'dependency-injection', 'asp.net-core-mvc']",1753,TRUE,0,2
kGREYNoMatchingElementException is being raised even if element is present in hierarchy,"<p><strong>Code</strong></p>

<pre><code>    let label_interactable_matcher = grey_allOf([grey_accessibilityLabel(""お知らせ""), GREYMatchers.matcherForInteractable()])
    let action = GREYActions.actionForTap()
    EarlGrey.selectElement(with: label_interactable_matcher).atIndex(0).perform(action)
</code></pre>

<p><strong>Exception</strong></p>

<p>Exception Name: NoMatchingElementException
Exception Reason: Cannot find UI element.
Exception with Action: {
  ""Action Name"":  ""Tap"",
  ""Element Matcher"":  ""(((respondsToSelector(isAccessibilityElement) &amp;&amp; isAccessibilityElement) &amp;&amp; accessibilityLabel('お知らせ')) &amp;&amp; interactable)"",
  ""Recovery Suggestion"":  ""Check if the element exists in the UI hierarchy printed below. If it exists, adjust the matcher so that it accurately matches element.""
}</p>

<p>Exception Details: Error Trace: [
  {
    ""Description"":  ""Interaction cannot continue because the desired element was not found."",
    ""Error Domain"":  ""com.google.earlgrey.ElementInteractionErrorDomain"",
    ""Error Code"":  ""0"",
    ""File Name"":  ""GREYElementInteraction.m"",
    ""Function Name"":  ""-[GREYElementInteraction matchedElementsWithTimeout:error:]"",
    ""Line"":  ""124"",
    ""TestCase Class"":  ""MyAppTests.Myunittest"",
    ""TestCase Method"":  ""testExample""
  }
]</p>

<p><strong>View Hierarchy</strong></p>

<p>ECKit_iOS.IconButton:0x7f86af9aea00; AX=Y; AX.label='お知らせ'; AX.frame={{351, 81}, {55, 50}}; AX.activationPoint={378.5, 106}; AX.traits='UIAccessibilityTraitButton'; AX.focused='N'; frame={{0, 0}, {55, 50}}; alpha=1>
-UIButtonLabel:0x7f86aed75130; AX=Y; AX.label='お知らせ'; AX.frame={{362, 115}, {33, 10}}; AX.activationPoint={378.5, 120}; AX.traits='UIAccessibilityTraitStaticText'; AX.focused='N'; frame={{11, 34}, {33, 10}}; alpha=1; UIE=N; text='お知らせ'></p>

<p><strong>Screenshot At Failure</strong></p>

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

<p><strong>Concerns</strong></p>

<ol>
<li>There is a contradiction between view hierarchy &amp; exception being printed</li>
<li>If the exception is ""NoMatchingElementException"" why would Recovery Suggestion says ""Check if the element exists in the UI hierarchy printed below. If it exists, adjust the matcher so that it accurately matches element""</li>
<li>In my existing app after the installation if I add a new XCTestCase in UNIT TESTING TARGET, app show in black background(I was expecting it in white).</li>
<li>For the splash screen suggestion in <a href=""https://github.com/google/EarlGrey/blob/master/docs/faq.md#my-app-shows-a-splash-screen-how-can-i-make-my-test-wait-for-the-main-screen"" rel=""nofollow noreferrer"">FAQ</a>, the swift implementation solution seems difficult to implement(app module should be imported in testing module &amp; rootViewController class </li>
<li>Running the app by play button in unit testing target vs directly launching  the app. Unexpected black background appears instead of white one. <a href=""https://i.stack.imgur.com/huGWn.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/huGWn.png"" alt=""enter image description here""></a></li>
<li>We can't use autogenerated code from UI Testing Target in Unit Test Target &amp; Management of UI tests become difficult if we opt for both Xcode's UI Testing &amp; EarlGrey</li>
<li>Screenshot At Failure(Black screen) is contradicting with View Hierarchy</li>
</ol>
",https://stackoverflow.com/questions/51202584/kgreynomatchingelementexception-is-being-raised-even-if-element-is-present-in-hi,['earlgrey'],349,FALSE,0,1
Live testing ASP.NET custom Role Provider,"<p>Using ASP.NET Webforms + VB/C#</p>

<p>I've been tasked to restrict ASP.NET page access to users not in specific roles.  And I need to be able to live test my solution (versus unit testing where I could use mocks or fakes).  Our site is rather complex so I doubt I'd be able to find all the ""gotchas"" with just unit testing.</p>

<p>I have something on my development computer I'm pretty sure will work in Production:  I have a custom Role Provider hooked into the web.config file.  It's being initialized and called when I debug the website, so I'm reasonably sure it's working OK.  I have a folder (""Administration"") marked only for a specific role.  Our roles are defined in our own database and are not tied to Microsoft or Windows roles/permissions.</p>

<p>The problem is:  I cannot actually login as a user I wish to debug with.  I can ""simulate"" this with a special <strong>development-only</strong> start page. That works OK for our menu/navigation items which are built from the roles database, but of course without restricting pages (with a Role Provider or something similar), you can still manually type in a page and it will be served up.  This devel-only start page sets the username I pass in as a FormsAuthentation auth cookie.</p>

<pre><code>FormsAuthentication.Initialize()
FormsAuthentication.SignOut()
FormsAuthentication.SetAuthCookie(simUserName, True)
</code></pre>

<p>It seems like when I first start debugging (usually after a reboot), the custom Role Provider will get called with the same username I'm simulating, but after a while, that suddenly stops and my local Windows name gets passed instead. (Cookie issue?)  After that, it no longer works.</p>

<p>Anyway -- Is there a way I can test roles locally during development or will we just have to put this on Production and hope for the best.</p>

<p>I didn't know what code or settings would be useful at this time, so let me know what you need.  Thanks!</p>
",https://stackoverflow.com/questions/52572122/live-testing-asp-net-custom-role-provider,"['c#', 'asp.net', 'vb.net', 'webforms', 'roleprovider']",164,TRUE,0,1
Automated UITest strategy for 2 mobile applications - User app/Admin app,"<p>I am on a development team where we have 2 separate mobile apps. One of the apps is for Users. The other app is for Admin of those users. My main objective is to execute a test case in the Admin app, <em>and then</em> run a test case in the Users app to verify its working properly. How can I approach this?</p>

<p>For example, I want to run a test case in the Admin app that revokes some privilege. I then want to run a test case from the Users app to check to confirm that privilege was revoked.</p>

<p>Maybe this is not a good strategy at all -- but it makes sense for my team because we have 2 apps that work together -- and if we do some function in the Admin app -- we want to see the expected result in the Users app</p>

<p>My plan was to mark each test with a Category, for example, ""Privilege""</p>

<p>On Jenkins:</p>

<ol>
<li>Run ""Privilege"" Category on the Admin app where I revoke some privilege</li>
<li>Run  ""Privilege"" Category on the User app where I confirm revoked privilege</li>
</ol>

<p>This seems like an ok test strategy right now. But if I have 20 UITests that means I'll have 20 different Jenkins projects in my dashboard, one for each UITest (per device, per platform). It seems that with 20 UITests I'll end up with over 100 Jenkins projects. Thats not really ideal to me. </p>

<p>Has anybody else come up with a testing strategy where they needed to test 2 separate projects back and forth. I understand that this does not really fall under unit testing - and I may get some vague answers around unit testing and general. But I do believe mobile is a different animal in the UITest world </p>
",https://stackoverflow.com/questions/52651027/automated-uitest-strategy-for-2-mobile-applications-user-app-admin-app,"['jenkins', 'mobile', 'automated-tests', 'xamarin.uitest']",61,TRUE,0,2
Unresolved externals with google test,"<p>I have a project I am trying to add <code>google-test</code> unit testing to. It is structured like so:</p>

<p><strong>VM (project)</strong></p>

<pre><code>some source files

BytecodePrograms.h
</code></pre>

<p><strong>VMTest</strong> (project, made by add project -> google test -> link dynamically, test <code>VM</code>)</p>

<pre><code>pch.h

test.cpp
</code></pre>

<p>I added my <code>VM</code> project as an include directory in <code>VMTest</code> properties -> c/c++ -> general -> additional include directories</p>

<p>contents of <code>test.cpp</code> are:</p>

<pre><code>#include ""pch.h""
#include ""BytecodePrograms.h""

TEST(TestCaseName, TestName) {
  EXPECT_EQ(8, VMFibonacciImp(6));
  EXPECT_TRUE(true);
}
</code></pre>

<p>If I build, I get the following errors</p>

<pre><code>Error   LNK2019 unresolved external symbol ""public: __thiscall WVM::WVM(void)"" (??0WVM@@QAE@XZ) referenced in function ""int __cdecl VMFibonacciImp(int)"" (?VMFibonacciImp@@YAHH@Z)  WVMTest C:\Users\WadeMcCall\source\repos\Virtual Machine Visual Scripting\WVMTest\test.obj  1   
Error   LNK2019 unresolved external symbol ""public: __thiscall WVM::~WVM(void)"" (??1WVM@@QAE@XZ) referenced in function ""int __cdecl VMFibonacciImp(int)"" (?VMFibonacciImp@@YAHH@Z) WVMTest C:\Users\WadeMcCall\source\repos\Virtual Machine Visual Scripting\WVMTest\test.obj  1   
Error   LNK2019 unresolved external symbol ""public: int __thiscall WVM::interpret(class std::vector&lt;int,class std::allocator&lt;int&gt; &gt;)"" (?interpret@WVM@@QAEHV?$vector@HV?$allocator@H@std@@@std@@@Z) referenced in function ""int __cdecl VMFibonacciImp(int)"" (?VMFibonacciImp@@YAHH@Z)  WVMTest C:\Users\WadeMcCall\source\repos\Virtual Machine Visual Scripting\WVMTest\test.obj  1   
</code></pre>

<p>However, my <code>VM</code> project defines my <code>WVM</code> class and uses it and can build and run and <code>BytecodePrograms.h</code> includes <code>VM.h</code> which has the declaration for this class.</p>

<p>I feel like this must just be a problem with the set up of my projects in Visual Studio somehow, but I have no idea. I have been googling for 2 days straight and have found other people with similar problems but their solution never seems to work for me.</p>

<p>Any ideas? Thanks.</p>
",https://stackoverflow.com/questions/52049330/unresolved-externals-with-google-test,"['c++', 'googletest']",3393,TRUE,3,2
Laravel Dusk Test assert the element of selector does not exist,"<p>I am developing a Web application using the Laravel framework. I am running Dus/Browser unit testing on my application. But now I am having problem with asserting if the selected element exist.</p>

<p>I have view file with this code snippet in it.</p>

<pre><code>@if(auth()-&gt;user()-&gt;role == 1)
      &lt;a dusk=""button-create"" href=""/create""&gt;
          Create
      &lt;/a&gt;
@endif
</code></pre>

<p>I am testing if that button exist or not in the Dusk unit test like this.</p>

<pre><code>  $this-&gt;browse(function (Browser $browser) use ($admin) {
        $browser-&gt;loginAs($admin)-&gt;visit(url);
        $textContent = $browser-&gt;text(""@button-create"");
        $this-&gt;assertNotEmpty($textContent);
    });
</code></pre>

<p>Testing if the button exists using the above code is fine. But when I test if the button not exist like this.</p>

<pre><code> $this-&gt;browse(function (Browser $browser) use ($student) {
            $browser-&gt;loginAs($student)-&gt;visit(url);
            $textContent = $browser-&gt;text(""@button-create"");
            $this-&gt;assertEmpty($textContent);
        });
</code></pre>

<p>I am getting this error.</p>

<pre><code>no such element: Unable to locate element: {""method"":""css selector"",""selector"":""body [dusk=""button-create""]""}
</code></pre>

<p>A solution I can think of it that wrapping the html element with another element and setting the selector on it. Something like this.</p>

<pre><code>&lt;span dusk=""button-create""&gt;
@if(auth()-&gt;user()-&gt;role == 1)
          &lt;a href=""/create""&gt;
              Create
          &lt;/a&gt;
    @endif
&lt;/span&gt;
</code></pre>

<p>But I do not want to wrap it with another html tag. Is it possible without wrapping another tag? How?</p>
",https://stackoverflow.com/questions/53190749/laravel-dusk-test-assert-the-element-of-selector-does-not-exist,"['laravel', 'laravel-dusk', 'browser-testing']",2452,TRUE,3,1
How to combine two or more vectors of arbitrary types in C++,"<p>I've got the following code that combines two vectors of arbitrary types into a combinatorial, i.e. <code>std::vector&lt;std::tuple&lt;A, B&gt;&gt;</code>.</p>

<pre><code>template&lt;class A, class B&gt;
std::vector&lt;std::tuple&lt;A, B&gt;&gt; combine(const std::vector&lt;A&gt;&amp; a, const std::vector&lt;B&gt;&amp; b) {

    const auto combine_parts_ = [](const A&amp; x, const B&amp; y) {
        auto result = std::tuple_cat(std::make_tuple(x), std::make_tuple(y));
        return result;
    };

    std::vector&lt;std::tuple&lt;A, B&gt;&gt; results;

    for (const auto&amp; x : a) {
        for (const auto&amp; y : b) {
            results.push_back(combine_parts_(x, y));
        }
    }

    return results;
}
</code></pre>

<p>However, I'm unclear how to extend that to an arbitrary number of types/vectors. I don't care about duplicate types; in fact there may be two or more sets of the same type involved. That's okay.</p>

<p>Some example use cases, for instance:</p>

<pre><code>const auto combinations = combine(
    std::vector&lt;int&gt;({1,2,3})
    , std::vector&lt;int&gt;({1,2,3})
);
const auto combinations2 = combine(
    std::vector&lt;int&gt;({1,2,3})
    , std::vector&lt;int&gt;({1,2,3})
    , std::vector&lt;bool&gt;({true,false})
);
const auto combinations3 = combine(
    std::vector&lt;int&gt;({1,2,3})
    , std::vector&lt;int&gt;({1,2,3})
    , std::vector&lt;bool&gt;({true,false})
    , std::vector&lt;char&gt;({'a','b','c','d','e'})
);
</code></pre>

<p>Chiefly, what I want to do is avoid the ugly nested for loop. At the same time, I want to combine some unit testing combinatorial use cases in order to work with the resulting <code>std::tuple&lt;...&gt;</code> as the test case.</p>

<p>Note, I am not talking about permutations of a homogeneous set here. That's been a point of confusion from prior questions.</p>

<p>I think it might have something to do with templates, variadics, <code>std::tuple_cat</code>, somewhere along the way, but I don't know.</p>

<p>Thoughts? Suggestions?</p>
",https://stackoverflow.com/questions/53216947/how-to-combine-two-or-more-vectors-of-arbitrary-types-in-c,"['c++', 'vector', 'tuples', 'cartesian-product']",327,TRUE,7,2
How to run unittest test cases in the order they are declared,"<p>I fully realize that the order of unit tests should not matter. But these unit tests are as much for instructional use as for actual unit testing, so I would like the test output to match up with the test case source code.</p>

<p>I see that there is a way to set the sort order by setting the <code>sortTestMethodsUsing</code> attribute on the test loader. The default is a simple <code>cmp()</code> call to lexically compare names. So I tried writing a <code>cmp</code>-like function that would take two names, find their declaration line numbers and them return the <code>cmp()</code>-equivalent of them:</p>

<pre><code>import unittest

class TestCaseB(unittest.TestCase):
    def test(self):
        print(""running test case B"")

class TestCaseA(unittest.TestCase):
    def test(self):
        print(""running test case A"")

import inspect
def get_decl_line_no(cls_name):
    cls = globals()[cls_name]
    return inspect.getsourcelines(cls)[1]

def sgn(x):
    return -1 if x &lt; 0 else 1 if x &gt; 0 else 0

def cmp_class_names_by_decl_order(cls_a, cls_b):
    a = get_decl_line_no(cls_a)
    b = get_decl_line_no(cls_b)
    return sgn(a - b)

unittest.defaultTestLoader.sortTestMethodsUsing = cmp_class_names_by_decl_order
unittest.main()
</code></pre>

<p>When I run this, I get this output:</p>

<pre><code>running test case A
.running test case B
.
----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK
</code></pre>

<p>indicating that the test cases are not running in the declaration order.</p>

<p>My sort function is just not being called, so I suspect that main() is building a new test loader, which is wiping out my sort function.</p>
",https://stackoverflow.com/questions/52472091/how-to-run-unittest-test-cases-in-the-order-they-are-declared,"['python', 'python-3.x', 'python-unittest']",3077,TRUE,7,3
Refactor C# entity framework 6 project to use dependancy injection for moqqing,"<p>I'm dealing with adding Dependancy Injection framework to a large project, in order to enlarge the unit testing coverage.
Specially, I want to cover data access method, so I want to be able to Moq the context.</p>

<p>Here is a sample method:</p>

<pre><code>public int GetNumberOfLines(int groupId)
{
    using (var db = new EntitiesMigrate().AutoLocal())
    {
         return db.MergeUserLines.ByGroup(groupId).GroupBy(x =&gt; x.Number).Count();
    }
}
</code></pre>

<p>The method <code>AutoLocal()</code> is an extension I've wrote that allowed us using different connection strings in each env &amp; different dev machines. It is used on each <code>new EntitiesMigrate()</code> (just saying, if it can help in for moqqing).
Currently we are using Microsoft test framework (inside VS/2017), but it is not a must to keep using it, for better test capabilities.</p>

<p>My questions are:</p>

<ol>
<li>What would be the preferred frameworks to combine DI and MOQ in an EF6 asp.net/mvc and asp.net/web-api?</li>
<li>How to convert this method using those frameworks?</li>
</ol>
",https://stackoverflow.com/questions/50130061/refactor-c-entity-framework-6-project-to-use-dependancy-injection-for-moqqing,"['c#', 'asp.net-mvc', 'entity-framework', 'unit-testing', 'moq']",85,TRUE,2,1
vue-test-utils shallowMount: execution time grows each test,"<p><strong>Problem</strong></p>

<p>I'm using Vue 2.4 with Mocha and Chai for unit testing. When executing the component tests, the execution time of each test is longer than of the test before.</p>

<p><strong>Expectation</strong></p>

<p>That each call of <code>shallow</code>/<code>shallowMount</code> takes not more than 200ms.</p>

<p><strong>Files</strong></p>

<p><code>package.json</code></p>

<pre><code>{
  ""name"": ""client"",
  ""version"": ""1.0.0"",
  ""description"": ""client"",
  ""private"": true,
  ""scripts"": {
    ""dev"": ""node build/dev-server.js"",
    ""start"": ""node ./server.js"",
    ""build"": ""node build/build.js"",
    ""test"": ""mocha-webpack --webpack-config build/webpack.dev.conf.js --require test/setup.js src/**/*.spec.js src/*.spec.js --timeout 10000"",
    ""test:watch"": ""mocha-webpack --webpack-config build/webpack.dev.conf.js --require test/setup.js src/**/*.spec.js src/*.spec.js --watch --timeout 10000"",
    ""test:e2e"": ""node test/e2e/runner.js"",
    ""heroku-postbuild"": ""yarn build""
  },
  ""standard"": {
    ""parser"": ""babel-eslint"",
    ""plugins"": [
      ""html""
    ],
    ""ignore"": [
      ""dist""
    ]
  },
  ""engines"": {
    ""node"": ""8.2.1"",
    ""npm"": ""&gt;= 3.0.0""
  },
  ""dependencies"": {
    ""auth0-js"": ""^9.5.1"",
    ""axios"": ""^0.16.2"",
    ""babel-polyfill"": ""^6.26.0"",
    ""execa"": ""^0.8.0"",
    ""express-force-ssl"": ""^0.3.2"",
    ""node-sass"": ""^4.7.2"",
    ""onsenui"": ""^2.6.1"",
    ""query-string"": ""^5.0.0"",
    ""ramda"": ""^0.25.0"",
    ""sass-loader"": ""^6.0.6"",
    ""validator"": ""^9.4.1"",
    ""vue"": ""^2.4.0"",
    ""vue-browserupdate"": ""^1.2.0"",
    ""vue-i18n"": ""^7.3.0"",
    ""vue-mq"": ""^0.1.0"",
    ""vue-onsenui"": ""^2.2.1"",
    ""vue-stash"": ""^2.0.1-beta"",
    ""vue-touch"": ""next"",
    ""vuex"": ""^2.4.1""
  },
  ""devDependencies"": {
    ""@vue/test-utils"": ""^1.0.0-beta.14"",
    ""autoprefixer"": ""^7.1.4"",
    ""babel-core"": ""^6.22.1"",
    ""babel-eslint"": ""7.2.3"",
    ""babel-loader"": ""^7.1.2"",
    ""babel-plugin-transform-runtime"": ""^6.22.0"",
    ""babel-preset-env"": ""^1.3.2"",
    ""babel-preset-es2015"": ""^6.24.1"",
    ""babel-preset-stage-2"": ""^6.22.0"",
    ""babel-register"": ""^6.26.0"",
    ""chai"": ""^4.1.2"",
    ""chai-spies"": ""^1.0.0"",
    ""chalk"": ""^2.1.0"",
    ""chromedriver"": ""^2.27.2"",
    ""compression-webpack-plugin"": ""^1.0.1"",
    ""connect-history-api-fallback"": ""^1.3.0"",
    ""copy-webpack-plugin"": ""^4.0.1"",
    ""cross-env"": ""^5.0.5"",
    ""cross-spawn"": ""^5.0.1"",
    ""css-loader"": ""^0.28.0"",
    ""eslint-plugin-html"": ""^3.2.0"",
    ""eventsource-polyfill"": ""^0.9.6"",
    ""express"": ""^4.16.1"",
    ""extract-text-webpack-plugin"": ""^3.0.1"",
    ""file-loader"": ""^1.1.4"",
    ""friendly-errors-webpack-plugin"": ""^1.1.3"",
    ""html-webpack-plugin"": ""^2.28.0"",
    ""http-proxy-middleware"": ""^0.17.3"",
    ""jsdom"": ""^11.8.0"",
    ""jsdom-global"": ""^3.0.2"",
    ""mocha"": ""^5.1.1"",
    ""mocha-webpack"": ""^1.1.0"",
    ""nightwatch"": ""^0.9.12"",
    ""opn"": ""^5.1.0"",
    ""optimize-css-assets-webpack-plugin"": ""^3.2.0"",
    ""ora"": ""^1.2.0"",
    ""rimraf"": ""^2.6.0"",
    ""selenium-server"": ""^3.0.1"",
    ""semver"": ""^5.3.0"",
    ""shelljs"": ""^0.7.6"",
    ""standard"": ""^11.0.0"",
    ""sw-precache-webpack-plugin"": ""^0.11.4"",
    ""url-loader"": ""^0.5.8"",
    ""vue-loader"": ""^13.0.5"",
    ""vue-style-loader"": ""^4.0.2"",
    ""vue-template-compiler"": ""^2.4.0"",
    ""vueify"": ""^9.4.1"",
    ""webpack"": ""^3.6.0"",
    ""webpack-bundle-analyzer"": ""^2.2.1"",
    ""webpack-dev-middleware"": ""^1.10.0"",
    ""webpack-hot-middleware"": ""^2.18.0"",
    ""webpack-merge"": ""^4.1.0""
  },
  ""browserslist"": [
    ""&gt; 1%"",
    ""last 2 versions"",
    ""not ie &lt;= 8""
  ]
}
</code></pre>

<p>The setup the component tests as easily as possible, we use a fixture class (<code>VueComponentTestFixture</code>):</p>

<pre><code>import Vue from 'vue'
import VueI18n from 'vue-i18n'
import Vuex from 'vuex'
import { shallow, mount, createLocalVue } from '@vue/test-utils'

import chai from 'chai'
import spies from 'chai-spies'
chai.use(spies)

import messages from '../../src/locale/index'

Vue.use(VueI18n)
const i18n = new VueI18n({ locale: 'de', messages, silentTranslationWarn: true })
Vue.use(Vuex)

// Prevent warnings during tests
// https://github.com/vuetifyjs/vuetify/issues/243#issuecomment-288467099
Vue.config.ignoredElements = [
  'v-ons-toolbar',
  'v-ons-toolbar-button',
  'v-ons-search-input',
  'v-touch',
  'v-ons-dialog',
  'v-ons-list',
  'v-ons-list-item',
  'v-ons-page',
  'v-ons-list-header',
  'v-ons-icon',
  'v-ons-modal',
  'ons-list-item',
  'v-ons-select',
  'v-ons-input',
  'v-ons-radio',
  'ons-alert-dialog-button',
  'ons-list',
  'v-ons-button',
  'v-ons-checkbox',
]

const localVue = createLocalVue()

// Prevent a lot of ""[vuex] unknown mutation type .."" logs during tests
const originalConsoleError = console.error
console.error = function(msg) {
  if(msg.startsWith('[vuex] unknown')) return
  originalConsoleError(msg)
}

export default class VueComponentTestFixture {
  state = {}
  actions = {}
  getters = {}
  mutations = {}
  props = {}
  onsen = {
    notification: {
      alert: chai.spy(),
      confirm: chai.spy(),
      toast: chai.spy()
    }
  }
  mq = {}

  constructor(componentInstance) {
    this.component = componentInstance
  }

  buildWrapper() {
    const startTime = Date.now()
    // custom plugin mocks
    Vue.prototype.$mq = this.mq
    Vue.prototype.$ons = this.onsen

    // build test store
    let store = new Vuex.Store({
      state: this.state,
      actions: this.actions,
      getters: this.getters,
      mutations: this.mutations
    })

    // build component wrapper using shallow rendering
    let wrapper = shallow(this.component, { store, localVue, i18n, propsData: this.props })
    console.log(`buildWrapper mount: ${(Date.now() - startTime)}ms`)
    return wrapper
  }
}
</code></pre>

<p>Example of a test file:</p>

<pre><code>import VueComponentTestFixture from '../../test/components/VueComponentTestFixture'
import chai from 'chai'
import spies from 'chai-spies'
chai.use(spies)
const expect = chai.expect

import Input from './Input.vue'

describe('Input.vue spy', () =&gt; {
  let fixture
  let wrapper

  beforeEach(() =&gt; {
    fixture = new VueComponentTestFixture(Input)
    wrapper = fixture.buildWrapper()
  })

  it('correctly emits NUMBER type values', () =&gt; {
    // Arrange
    wrapper.setProps({
      isEditable: true,
      value: undefined,
      number: undefined,
      type: 'NUMBER',
      title: 'test'
    })
    const input = wrapper.find('[data-test-id=""number-input""]')
    const value = 100

    // Act
    input.element.value = value
    input.trigger('input')
    wrapper.find('[data-test-id=""save-button""]').trigger('click')

    // Assert
    expect(wrapper.emitted().change[0][0]).to.equal(value)
  })

  it('correctly emits TEXT type values', () =&gt; {
    // Arrange
    wrapper.setProps({
      isEditable: true,
      value: undefined,
      number: undefined,
      type: 'TEXT',
      title: 'test'
    })
    const input = wrapper.find('[data-test-id=""text-input""]')
    const value = 'test'

    // Act
    input.element.value = value
    input.trigger('input')
    wrapper.find('[data-test-id=""save-button""]').trigger('click')

    // Assert
    expect(wrapper.emitted().change[0][0]).to.equal(value)
  })

  it(""doesn't emit when not editable"", () =&gt; {
    // Arrange
    wrapper.setProps({
      isEditable: false,
      value: undefined,
      number: undefined,
      type: 'NUMBER',
      title: 'test'
    })
    const input = wrapper.find('[data-test-id=""number-input""]')
    const value = 100

    // Act
    input.element.value = value
    input.trigger('input')
    wrapper.find('[data-test-id=""save-button""]').trigger('click')

    // Assert
    expect(wrapper.emitted()).to.be.empty
    expect(input.attributes().disabled).to.equal('disabled')
  })
})
</code></pre>

<p>Here is the output when executing the tests (with the time measurement in the fixture):</p>

<pre><code>  EventEditor.vue basics
    ✓ name present
    ✓ data present

  EventEditor.vue spy
    modulePath module
buildWrapper mount: 110ms
buildWrapper mount: 89ms
      ✓ dispatches ""createEvent"" when clicking on an enabled eventType button (210ms)
buildWrapper mount: 164ms
      ✓ doesn't dispatch ""createEvent"" when clicking on a disabled eventType button (161ms)
buildWrapper mount: 230ms
buildWrapper mount: 262ms
      ✓ emits ""change"" correctly when event is added (515ms)
buildWrapper mount: 310ms
buildWrapper mount: 365ms
      ✓ needs a confirmation for removing an event (720ms)
buildWrapper mount: 409ms
buildWrapper mount: 457ms
      ✓ shows finish timeline button correctly (460ms)
buildWrapper mount: 515ms
      ✓ emits ""request-close-timeline"" correctly when finish timeline button is clicked (504ms)
    modulePath events
buildWrapper mount: 574ms
buildWrapper mount: 682ms
      ✓ dispatches ""createEvent"" when clicking on an enabled eventType button (1325ms)
buildWrapper mount: 682ms
      ✓ doesn't dispatch ""createEvent"" when clicking on a disabled eventType button (678ms)
buildWrapper mount: 728ms
buildWrapper mount: 775ms
      ✓ emits ""change"" correctly when event is added (1546ms)
buildWrapper mount: 843ms
buildWrapper mount: 899ms
      ✓ needs a confirmation for removing an event (1846ms)
buildWrapper mount: 954ms
buildWrapper mount: 1081ms
      ✓ shows finish timeline button correctly (1082ms)
buildWrapper mount: 1220ms
      ✓ emits ""request-close-timeline"" correctly when finish timeline button is clicked (1245ms)

  Home component
    ✓ name present
    ✓ components present

  Input.vue spy
buildWrapper mount: 1137ms
    ✓ correctly emits NUMBER type values (2215ms)
buildWrapper mount: 1181ms
    ✓ correctly emits TEXT type values (2215ms)
buildWrapper mount: 1177ms
    ✓ doesn't emits when not editable

  ObservationDialog.vue spy
buildWrapper mount: 1236ms
    ✓ sets locations correctly
buildWrapper mount: 1278ms
    ✓ enables continue buttons only if valid data is given
buildWrapper mount: 1345ms
    ✓ dispatches action ""createTimeline""
buildWrapper mount: 1404ms
    ✓ resets form values when createTimeline is called
buildWrapper mount: 1443ms
    ✓ contains all eventTypes in ""event selection"" when no module is selected
buildWrapper mount: 1467ms
    ✓ removes eventTypes from ""event selection"" when a module is selected
    method createTimeline
buildWrapper mount: 1547ms
buildWrapper mount: 1581ms
      ✓ dispatches no action when no variant is selected
buildWrapper mount: 1616ms
buildWrapper mount: 1675ms
      ✓ dispatches ""createTimeline"" when module variant is selected
buildWrapper mount: 1758ms
buildWrapper mount: 1836ms
      ✓ dispatches ""loadObservationEvents"" when event variant is selected
buildWrapper mount: 1873ms
buildWrapper mount: 2133ms
      ✓ dispatches ""createTimeline"" and ""loadObservationEvents"" when both variants are selected
buildWrapper mount: 2953ms
buildWrapper mount: 2445ms
      ✓ commits no mutations when no variant is selected
buildWrapper mount: 2349ms
buildWrapper mount: 2099ms
      ✓ commits the expected mutations when module variant is selected
buildWrapper mount: 2835ms
buildWrapper mount: 2654ms
      ✓ commits the expected mutations when event variant is selected
buildWrapper mount: 3052ms
buildWrapper mount: 2722ms
      ✓ commits only resetPageStack when module and events observation is selected
buildWrapper mount: 3129ms
buildWrapper mount: 2988ms
      ✓ commits the expected mutations when both variants are selected

  ObservationMenu.vue basics
    ✓ name present
    ✓ data present
    ✓ computed present

  ObservationMenu.vue spy
buildWrapper mount: 3490ms
    ✓ sets timelines correctly
buildWrapper mount: 3225ms
    ✓ opens dialog correctly (2440ms)
buildWrapper mount: 2658ms
    ✓ triggers activeModule mutation on state when open existing new timeline (2768ms)
buildWrapper mount: 4084ms
    ✓ triggers activeModule mutation on state when open existing finished timeline (3000ms)

  Select.vue
    ✓ name present
    ✓ props present
    ✓ data present

  Select.vue spy
buildWrapper mount: 2724ms
    ✓ shows only prefered options
buildWrapper mount: 2714ms
    ✓ opens modal (2925ms)

  state
    ✓ commit reset action
    ✓ empties the page stack
    mutation navigateToTimeline
      ✓ adds a ""module observation"" page to the beginning of the pageStack array
      ✓ adds an ""event observation"" page to the end of the pageStack array


  50 passing (2m)
</code></pre>

<p>It can be seen how the time consumed by <code>buildWrapper</code> ""stacks up"" each test. I tried it with <code>beta-14</code> of <code>vue-test-utils</code> as also with <code>beta-20</code>, same result.</p>

<p>I think the component(s) itself are not of interest. It happens also when only executing the tests of each component separately. But if it is necessary, let me know.</p>
",https://stackoverflow.com/questions/51446048/vue-test-utils-shallowmount-execution-time-grows-each-test,"['vue.js', 'vue-test-utils']",1236,FALSE,2,1
ASP.Net Web API Controller Unit Test POST,"<p>I am new to Unit Testing and am trying to create some Xunit tests for my Web API Controller's <code>POST</code> method.</p>

<p>Here is my Controller's <code>POST</code> method:</p>

<pre><code>[HttpPost("""")]
public async Task&lt;IActionResult&gt; CreateArea([FromBody] AreaForCreationDto area)
{
    // Check that the 'area' object parameter can be de-serialised to a AreaForCreationDto.
    if (area == null)
    {
        var message = ""Could not de-serialise the request body to an AreaForCreationDto object"";
        _logger.LogError(message);

        // Return an error 400.
        return BadRequest(message);
    }

    /*
     * ModelState.IsValid is determined by the attributes associated with the 
     * Data Annotations on the properties of the ViewModel.
     */
    if (!ModelState.IsValid)
    {
        // Return a response with a Status Code 422.
        return new UnprocessableEntityObjectResult(ModelState);
    };

    // Map a AreaForCreationDto object to a Area entity.
    var areaEntityToAdd = _mapper.Map&lt;Area&gt;(area);

    // Call the repository to add the new Area entity to the DbContext.
    _areaRepository.AddArea(areaEntityToAdd);

    // Save the new Area entity, added to the DbContext, to the SQL database.
    if (await _areaRepository.SaveChangesAsync())
    {
        // Note: AutoMapper maps the values of the properties from the areaEntityToAdd
        // to a new areaToReturn object.
        // This ensures that we don't expose our Area entity to the web browser.
        var areaToReturn = _mapper.Map&lt;AreaDto&gt;(areaEntityToAdd);

        // Return a 201 'created' response along with the location URL in the
        // response Header.
        return CreatedAtRoute(""GetArea"",
            new { id = areaToReturn.Id },
            areaToReturn);
    }
    else {
        // The save failed.
        var message = $""Could not save new Area {areaEntityToAdd.Id} to the database."";
        _logger.LogWarning(message);
        throw new Exception(message);
    };
}
</code></pre>

<p>The first Unit Test I have written is intended to ensure that on sending a POST request, with an object which can be de-serialised into an <code>AreaForCreation</code> object, the function returns a <code>201 CreatedAtRouteResult</code> along with the new Area which has been created.</p>

<p>Here is the Xunit test:</p>

<pre><code>[Fact]
public void ReturnAreaForCreateArea()
{
    //Arrange

    var _mockAreaRepository = new Mock&lt;IAreaRepository&gt;();
    _mockAreaRepository
        .Setup(x =&gt; x.AddArea(testArea));

    var _mockMapper = new Mock&lt;IMapper&gt;();
    _mockMapper
        .Setup(_ =&gt; _.Map&lt;Area&gt;(It.IsAny&lt;AreaForCreationDto&gt;()))
        .Returns(testArea);

    var _mockLogger = new Mock&lt;ILogger&lt;AreasController&gt;&gt;();
    var _sut = new AreasController(_mockAreaRepository.Object, _mockLogger.Object, _mockMapper.Object);

    // Act
    var result = _sut.CreateArea(testAreaForCreationDto);

    // Assert
    Assert.NotNull(result);
    var objectResult = Assert.IsType&lt;CreatedAtRouteResult&gt;(result);
    var model = Assert.IsAssignableFrom&lt;AreaDto&gt;(objectResult.Value);
    var areaDescription = model.Description;
    Assert.Equal(""Test Area For Creation"", areaDescription);
}
</code></pre>

<p>I am getting an exception thrown when the unit test tries to <code>Assert.IsType&lt;CreatedAtRouteResult&gt;(result)</code>. Debugging revealed that the Controller was failing to save to the repository. My <code>AreaRepository</code> has the following AddArea function which does not return a value so I assume that my <code>_mockAreaRepository</code> does not require a <code>Return</code> condition set (could be wrong here).</p>

<p>Do I need to configure my <code>mockAreasRepository</code> for the outcome of calling <code>SaveChangesAsync()</code>?</p>
",https://stackoverflow.com/questions/48426628/asp-net-web-api-controller-unit-test-post,"['asp.net-mvc', 'unit-testing', 'moq', 'xunit']",2761,TRUE,2,1
Any way to avoid memory leaks with shallowMount in vue-test-utils?,"<p>We have a custom unit testing setup for vue that works on Node, Mocha and jsdom package which simulates browser environment (no webpack, karma). We have wrote about 3k specs already (big app with hundreds of components), and now when mocha is running it becomes slower and slower, and eventually the process just hangs. We thought that maybe there is a memory leak in ""jsdom"", so we changed it to a ""domino"" (alternative package), but it still hangs.</p>

<p>We checked the heap memory usage and it just keeps growing (up to 1.5 GB!).</p>

<p>So we think that the problem is with either vue or vue-test-utils. It looks like each time we use <code>mount</code>/<code>shallowMount</code> it needs to be destroyed/unmounted after each test to release memory?</p>

<p>Any ideas? Thanks in advance!</p>
",https://stackoverflow.com/questions/53224101/any-way-to-avoid-memory-leaks-with-shallowmount-in-vue-test-utils,"['vue.js', 'vuejs2', 'vue-test-utils']",1686,TRUE,2,2
how to get &quot;new&quot; and &quot;delete&quot; fully covered and not partially covered with gtest framework. vs 2015,"<p>I'm using google test framework for unit testing my code and i encountered in a very strange issue.</p>

<p>I noticed that any line that contains dynamic allocation(new and delete), does not get full coverage even if the code runs through this lines.</p>

<p>I've made a simple example to demonstrate the problem:
lets say i have the following class:</p>

<pre><code>class DummyClass // fully covered
{
public:
    int x;
    DummyClass() { x = 5; }; // fully covered
    ~DummyClass() { }; // fully covered
};
</code></pre>

<p>Now i have the following function that allocate this class statically and dynamically:</p>

<pre><code>static void CoverageFunctionTest()
{
    // any logic here
    DummyClass staticVar1; // fully covered
    DummyClass* dynamicVar = new DummyClass();  // partially covered
    // any logic here
    DummyClass staticVar2; // fully covered
    delete dynamicVar;  // partially covered
}
</code></pre>

<p>The line with the ""new"" keyword and the line with the ""delete""
 keyword are considered as partially covered and not fully covered.</p>

<p>The coverage for this function is: 88.24% even though we covered every single line in it, and the coverage for the class is 100%.</p>

<p>How can i get 100% code coverage for this function?</p>

<p>Ty!</p>
",https://stackoverflow.com/questions/50115652/how-to-get-new-and-delete-fully-covered-and-not-partially-covered-with-gtest,"['c++', 'code-coverage', 'googletest']",149,FALSE,2,0
RxJava2 delay an observable until another observable emits,"<p>This is for unit testing purposes, as I want to verify correct behavior for a function where two data sources may return in different orders. Currently in my unit test, I'm creating an Observable with dummy data and simply using the delay operator to add a delay of 10 milliseconds for the data source I want to return second. However, this seems a bit ugly and could become problematic as I have more and more tests.</p>

<p>Is there a way to have an Observable wait to emit until another Observable completes?</p>

<p>Edit: Here's an example of a unit test that I have</p>

<pre><code>public void testNetworkReturningBeforeLocal() {
    Item localItem = new Item(""local"");
    Item remoteItem = new Item(""remote"");
    when(mDatabaseMock.getItem(any())).thenReturn(Observable.just(localItem).delay(10, TimeUnit.MILLISECONDS);
    when(mApiMock.getItem(any())).thenReturn(Observable.just(remoteItem));

    TestObserver&lt;Item&gt; observer = new TestObserver&lt;&gt;();
    mRepository.getItem(""blah"").subscribe(observer); // calls getItem from database and API

    observer.awaitTerminalEvent();
    observer.assertResult(remoteItem);
}
</code></pre>

<p>I'm using <code>delay(10, TimeUnit.MILLISECONDS)</code> on the observable returned by the database to simulate the network response arriving first. What I'd like to do is delay the database observable until the network observable completes.</p>
",https://stackoverflow.com/questions/53437873/rxjava2-delay-an-observable-until-another-observable-emits,"['observable', 'delay', 'rx-java2']",374,FALSE,2,0
How to xUnit-Test in Rider? I&#39;m getting error CS0246,"<p>I'm new to C#, and even more to unit testing in C#. Now I wanted to add unit tests to an application, but I can't seem to get it done in JetBrains Rider:</p>

<p>I created a new ""Unit Test Project"" inside my solution, besides my WPF application project. Rider installs <code>xunit</code>, <code>xunit.abstractions</code>, <code>xunit.assert</code>, <code>xunit.core</code>, <code>xunit.extensibility.core</code> and <code>xunit.extensibility.execution</code>. It also creates a <code>Tests.cs</code> class containing a <code>Test1()</code> method with a <code>[Fact]</code> attribute. Problem is: it immediately says <code>'Fact' is not an attribute</code>.</p>

<p>When building, it yields two [CS0246] Errors:</p>

<pre><code>Tests.cs(8, 10): [CS0246] Der Typ- oder Namespacename ""Fact"" wurde nicht gefunden (fehlt eine using-Direktive oder ein Assemblyverweise?)
Tests.cs(8, 10): [CS0246] Der Typ- oder Namespacename ""FactAttribute"" wurde nicht gefunden (fehlt eine using-Direktive oder ein Assemblyverweise?)
</code></pre>

<p>I'm not sure what the exact English translation would be, but I guess you get the idea. What references are missing? Is this a bug in Rider?</p>

<p>I tried it with NUnit as well, with similar results.</p>

<p>Besides that: Do I need to follow any file structure or naming conventions for the tests to be autodetected?</p>
",https://stackoverflow.com/questions/50975326/how-to-xunit-test-in-rider-im-getting-error-cs0246,"['c#', '.net', 'unit-testing', 'xunit', 'rider']",1681,TRUE,2,1
Moq : FileNotFoundException: Could not load file or assembly &#39;System.Runtime&#39;,"<p>I'm trying to learn Moq, and unit testing and i've got an error i don't understand when trying to use Moq.</p>

<p>The code below is pretty much copy-pasted from <a href=""https://github.com/Moq/moq4/wiki/Quickstart"" rel=""noreferrer"">https://github.com/Moq/moq4/wiki/Quickstart</a>. I'm using it because the error also occurs on the main project i am working on and i just want to limit and potential errors i've caused with my newbishness.</p>

<p>System.Runtime has been downloaded, and it's referenced. </p>

<p>Edit: Also i've tried version 4.0.0 and the error is still there.</p>

<pre><code>using System;
using NUnit.Framework;
using Proje.Controllers;
using Proje.Models;
using Proje.DAL;
using Moq;
using System.Web.Mvc;
using System.Runtime;


namespace Proje.UnitTests.Controllers
{
    [TestFixture]
    public class BaseControllerTests
    {
        public interface IFoo
        {
            Bar Bar { get; set; }
            string Name { get; set; }
            int Value { get; set; }
            bool DoSomething(string value);
            bool DoSomething(int number, string value);
            string DoSomethingStringy(string value);
            bool TryParse(string value, out string outputValue);
            bool Submit(ref Bar bar);
            int GetCount();
            bool Add(int value);
        }

        public class Bar
        {
            public virtual Baz Baz { get; set; }
            public virtual bool Submit() { return false; }
        }

        public class Baz
        {
            public virtual string Name { get; set; }
        }

        [Test]
        public void TestTest() {

            var mock = new Mock&lt;IFoo&gt;();
            mock.Setup(foo =&gt; foo.DoSomething(""ping"")).Returns(true);
            //Assert some stuff
        }
</code></pre>

<blockquote>
  <p>FileNotFoundException: Could not load file or assembly
  'System.Runtime, Version=4.1.2.0, Culture=neutral,
  PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The
  system cannot find the file specified.</p>
  
  <p>FileNotFoundException: Could not load file or assembly
  'System.Runtime, Version=4.0.0.0, Culture=neutral,
  PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The
  system cannot find the file specified.</p>
</blockquote>

<pre><code>&lt;?xml version=""1.0"" encoding=""utf-8""?&gt;
&lt;packages&gt;
  &lt;package id=""Castle.Core"" version=""4.3.1"" targetFramework=""net471"" /&gt;
  &lt;package id=""EntityFramework"" version=""6.2.0"" targetFramework=""net471"" /&gt;
  &lt;package id=""Microsoft.AspNet.Mvc"" version=""5.2.6"" targetFramework=""net471"" /&gt;
  &lt;package id=""Microsoft.AspNet.Razor"" version=""3.2.6"" targetFramework=""net471"" /&gt;
  &lt;package id=""Microsoft.AspNet.WebPages"" version=""3.2.6"" targetFramework=""net471"" /&gt;
  &lt;package id=""Microsoft.Web.Infrastructure"" version=""1.0.0.0"" targetFramework=""net471"" /&gt;
  &lt;package id=""Moq"" version=""4.9.0"" targetFramework=""net471"" /&gt;
  &lt;package id=""MSTest.TestAdapter"" version=""1.3.2"" targetFramework=""net471"" /&gt;
  &lt;package id=""MSTest.TestFramework"" version=""1.3.2"" targetFramework=""net471"" /&gt;
  &lt;package id=""NUnit"" version=""3.10.1"" targetFramework=""net471"" /&gt;
  &lt;package id=""NUnit3TestAdapter"" version=""3.10.0"" targetFramework=""net471"" /&gt;
  &lt;package id=""System.Runtime"" version=""4.3.0"" targetFramework=""net471"" /&gt;
  &lt;package id=""System.Threading.Tasks.Extensions"" version=""4.3.0"" targetFramework=""net471"" /&gt;
  &lt;package id=""System.ValueTuple"" version=""4.4.0"" targetFramework=""net471"" /&gt;
&lt;/packages&gt;


&lt;?xml version=""1.0"" encoding=""utf-8""?&gt;
&lt;configuration&gt;
  &lt;configSections&gt;
    &lt;!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --&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;/configSections&gt;
  &lt;runtime&gt;
    &lt;assemblyBinding xmlns=""urn:schemas-microsoft-com:asm.v1""&gt;
      &lt;dependentAssembly&gt;
        &lt;assemblyIdentity name=""System.Runtime"" publicKeyToken=""b03f5f7f11d50a3a"" culture=""neutral"" /&gt;
        &lt;bindingRedirect oldVersion=""0.0.0.0-4.1.2.0"" newVersion=""4.1.2.0"" /&gt;
      &lt;/dependentAssembly&gt;
      &lt;dependentAssembly&gt;
        &lt;assemblyIdentity name=""System.Reflection"" publicKeyToken=""b03f5f7f11d50a3a"" culture=""neutral"" /&gt;
        &lt;bindingRedirect oldVersion=""0.0.0.0-4.1.2.0"" newVersion=""4.1.2.0"" /&gt;
      &lt;/dependentAssembly&gt;
      &lt;dependentAssembly&gt;
        &lt;assemblyIdentity name=""System.Runtime.Extensions"" publicKeyToken=""b03f5f7f11d50a3a"" culture=""neutral"" /&gt;
        &lt;bindingRedirect oldVersion=""0.0.0.0-4.1.2.0"" newVersion=""4.1.2.0"" /&gt;
      &lt;/dependentAssembly&gt;
      &lt;dependentAssembly&gt;
        &lt;assemblyIdentity name=""System.Text.RegularExpressions"" publicKeyToken=""b03f5f7f11d50a3a"" culture=""neutral"" /&gt;
        &lt;bindingRedirect oldVersion=""0.0.0.0-4.1.1.0"" newVersion=""4.1.1.0"" /&gt;
      &lt;/dependentAssembly&gt;
      &lt;dependentAssembly&gt;
        &lt;assemblyIdentity name=""System.Linq"" publicKeyToken=""b03f5f7f11d50a3a"" culture=""neutral"" /&gt;
        &lt;bindingRedirect oldVersion=""0.0.0.0-4.1.2.0"" newVersion=""4.1.2.0"" /&gt;
      &lt;/dependentAssembly&gt;
      &lt;dependentAssembly&gt;
        &lt;assemblyIdentity name=""System.Net.Http"" publicKeyToken=""b03f5f7f11d50a3a"" culture=""neutral"" /&gt;
        &lt;bindingRedirect oldVersion=""0.0.0.0-4.1.1.0"" newVersion=""4.1.1.0"" /&gt;
      &lt;/dependentAssembly&gt;
      &lt;dependentAssembly&gt;
        &lt;assemblyIdentity name=""Microsoft.AspNet.TelemetryCorrelation"" publicKeyToken=""31bf3856ad364e35"" culture=""neutral"" /&gt;
        &lt;bindingRedirect oldVersion=""0.0.0.0-1.0.4.0"" newVersion=""1.0.4.0"" /&gt;
      &lt;/dependentAssembly&gt;
      &lt;dependentAssembly&gt;
        &lt;assemblyIdentity name=""DocumentFormat.OpenXml"" publicKeyToken=""8fb06cb64d019a17"" culture=""neutral"" /&gt;
        &lt;bindingRedirect oldVersion=""0.0.0.0-2.8.1.0"" newVersion=""2.8.1.0"" /&gt;
      &lt;/dependentAssembly&gt;
      &lt;dependentAssembly&gt;
        &lt;assemblyIdentity name=""System.IO.Compression"" publicKeyToken=""b77a5c561934e089"" culture=""neutral"" /&gt;
        &lt;bindingRedirect oldVersion=""0.0.0.0-4.1.2.0"" newVersion=""4.1.2.0"" /&gt;
      &lt;/dependentAssembly&gt;
      &lt;dependentAssembly&gt;
        &lt;assemblyIdentity name=""System.Diagnostics.DiagnosticSource"" publicKeyToken=""cc7b13ffcd2ddd51"" culture=""neutral"" /&gt;
        &lt;bindingRedirect oldVersion=""0.0.0.0-4.0.3.0"" newVersion=""4.0.3.0"" /&gt;
      &lt;/dependentAssembly&gt;
      &lt;dependentAssembly&gt;
        &lt;assemblyIdentity name=""WebGrease"" publicKeyToken=""31bf3856ad364e35"" culture=""neutral"" /&gt;
        &lt;bindingRedirect oldVersion=""0.0.0.0-1.6.5135.21930"" newVersion=""1.6.5135.21930"" /&gt;
      &lt;/dependentAssembly&gt;
      &lt;dependentAssembly&gt;
        &lt;assemblyIdentity name=""Antlr3.Runtime"" publicKeyToken=""eb42632606e9261f"" culture=""neutral"" /&gt;
        &lt;bindingRedirect oldVersion=""0.0.0.0-3.5.0.2"" newVersion=""3.5.0.2"" /&gt;
      &lt;/dependentAssembly&gt;
      &lt;dependentAssembly&gt;
        &lt;assemblyIdentity name=""Newtonsoft.Json"" publicKeyToken=""30ad4fe6b2a6aeed"" culture=""neutral"" /&gt;
        &lt;bindingRedirect oldVersion=""0.0.0.0-11.0.0.0"" newVersion=""11.0.0.0"" /&gt;
      &lt;/dependentAssembly&gt;
      &lt;dependentAssembly&gt;
        &lt;assemblyIdentity name=""Microsoft.Owin"" publicKeyToken=""31bf3856ad364e35"" culture=""neutral"" /&gt;
        &lt;bindingRedirect oldVersion=""0.0.0.0-4.0.0.0"" newVersion=""4.0.0.0"" /&gt;
      &lt;/dependentAssembly&gt;
      &lt;dependentAssembly&gt;
        &lt;assemblyIdentity name=""Microsoft.Owin.Security.OAuth"" publicKeyToken=""31bf3856ad364e35"" culture=""neutral"" /&gt;
        &lt;bindingRedirect oldVersion=""0.0.0.0-4.0.0.0"" newVersion=""4.0.0.0"" /&gt;
      &lt;/dependentAssembly&gt;
      &lt;dependentAssembly&gt;
        &lt;assemblyIdentity name=""Microsoft.Owin.Security"" publicKeyToken=""31bf3856ad364e35"" culture=""neutral"" /&gt;
        &lt;bindingRedirect oldVersion=""0.0.0.0-4.0.0.0"" newVersion=""4.0.0.0"" /&gt;
      &lt;/dependentAssembly&gt;
    &lt;/assemblyBinding&gt;
  &lt;/runtime&gt;
  &lt;entityFramework&gt;
    &lt;defaultConnectionFactory type=""System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework""&gt;
      &lt;parameters&gt;
        &lt;parameter value=""mssqllocaldb"" /&gt;
      &lt;/parameters&gt;
    &lt;/defaultConnectionFactory&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;
&lt;/configuration&gt;
</code></pre>

<p>Edit: Log</p>

<pre><code>*** Assembly Binder Log Entry  (9/20/2018 @ 7:49:44 PM) ***

The operation failed.
Bind result: hr = 0x80070002. The system cannot find the file specified.

Assembly manager loaded from:  C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll
Running under executable  C:\PROGRAM FILES (X86)\MICROSOFT VISUAL STUDIO\2017\COMMUNITY\COMMON7\IDE\EXTENSIONS\TESTPLATFORM\testhost.x86.exe
--- A detailed error log follows. 

=== Pre-bind state information ===
LOG: DisplayName = System.Runtime, Version=4.1.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL
 (Fully-specified)
LOG: Appbase = file:///C:/Users/NAME/source/repos/Proj/Proj.UnitTests/bin/Debug/
LOG: Initial PrivatePath = NULL
LOG: Dynamic Base = NULL
LOG: Cache Base = NULL
LOG: AppName = Tests_16537946
Calling assembly : (Unknown).
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\Users\NAME\source\repos\Proj\Proj.UnitTests\bin\Debug\Proj.UnitTests.dll.config
LOG: Using host configuration file: 
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Redirect found in application configuration file: 4.1.2.0 redirected to 4.1.2.0.
LOG: ProcessorArchitecture is locked to MSIL.
LOG: Post-policy reference: System.Runtime, Version=4.1.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL
LOG: GAC Lookup was unsuccessful.
LOG: Attempting download of new URL file:///C:/Users/NAME/source/repos/Proj/Proj.UnitTests/bin/Debug/System.Runtime.DLL.
LOG: Attempting download of new URL file:///C:/Users/NAME/source/repos/Proj/Proj.UnitTests/bin/Debug/System.Runtime/System.Runtime.DLL.
LOG: Attempting download of new URL file:///C:/Users/NAME/source/repos/Proj/Proj.UnitTests/bin/Debug/System.Runtime.EXE.
LOG: Attempting download of new URL file:///C:/Users/NAME/source/repos/Proj/Proj.UnitTests/bin/Debug/System.Runtime/System.Runtime.EXE.
LOG: All probing URLs attempted and failed.
</code></pre>
",https://stackoverflow.com/questions/52432085/moq-filenotfoundexception-could-not-load-file-or-assembly-system-runtime,"['c#', 'moq']",8738,TRUE,6,1
CMake unit structure with many tests,"<p>I would like to set up cmake to run on a project with unit testing. The project structure is as follows:</p>

<pre><code>|---CMakeLists.txt
|---build
|---source
|   |---CMakeLists.txt
|   |---many .cpp and .h files
|---tests
|   |---CMakeLists.txt
|   |---many .cpp files
</code></pre>

<p>The source files in <code>tests</code> use Boost <code>unit_test.h</code> library.</p>

<p>My outer <code>CMakeLists.txt</code> is as follows:</p>

<pre><code>cmake_minimum_required(VERSION 2.8.11)

set(CMAKE_CXX_FLAGS ""-std=c++11"")

project(MyProject CXX)
add_subdirectory(source)
add_subdirectory(tests)
enable_testing()
</code></pre>

<p>The <code>CMakeLists.txt</code> in the <code>source</code> folder is:</p>

<pre><code>file( GLOB LIB_SOURCES *.cpp )
file( GLOB LIB_HEADERS *.h )
add_library( MyProject_lib ${LIB_SOURCES} ${LIB_HEADERS} )
</code></pre>

<p>And the <code>CMakeLists.txt</code> in the <code>tests</code> folder is:</p>

<pre><code># require old policy to allow for source files containing the name ""test""
cmake_policy(SET CMP0037 OLD)
# Locate Boost libraries: unit_test_framework, date_time and regex
set(Boost_USE_STATIC_LIBS ON)
set(Boost_USE_MULTITHREADED ON)
set(Boost_USE_STATIC_RUNTIME OFF)
find_package(Boost 1.59 REQUIRED COMPONENTS unit_test_framework date_time regex)

include_directories(""${CMAKE_SOURCE_DIR}/source"" ${Boost_INCLUDE_DIRS})

file(GLOB APP_SOURCES *.cpp)
foreach(testsourcefile ${APP_SOURCES})
    string(REPLACE "".cpp"" """" testname ${testsourcefile})
    add_executable(${testname} ${testsourcefile})
    target_link_libraries(${testname} LINK_PUBLIC ${Boost_LIBRARIES} MyProject_lib)
    add_custom_target(targetname)
    add_custom_command(TARGET targetname POST_BUILD COMMAND ${testname})
endforeach(testsourcefile ${APP_SOURCES})
</code></pre>

<p>If I comment the lines with <code>add_custom_target</code> and <code>add_custom_command</code>, the result of this configuration is that the library is correctly built and linked, but none of the tests is compiled.</p>

<p>If I do not comment the two lines with <code>add_custom_target</code> and <code>add_custom_command</code>, The error I get by running <code>cmake</code> is:</p>

<pre><code>CMake Error at tests/CMakeLists.txt:25 (add_custom_target):
add_custom_target cannot create target ""targetname"" because another target
with the same name already exists.  The existing target is a custom target
created in source directory ""/tests"".  See
documentation for policy CMP0002 for more details.
</code></pre>

<p>Since I have a large number of tests, listing them one by one is not practical. I would like to have cmake to find all the .cpp files, as done for the library in the source folder, compile and run them.</p>
",https://stackoverflow.com/questions/48110838/cmake-unit-structure-with-many-tests,"['c++', 'unit-testing', 'cmake']",1600,TRUE,1,1
Passing DISPPARAMS,"<p>I'm unit testing a function with the following signature,</p>

<pre><code>void foo(DISPPARAMS* pDispParams, VARIANT* pVarResult)
</code></pre>

<p>I need to pass this <code>pDispParams</code> from outside, pointing to the mock type I have at hand. I'm creating the mock types using GMock.</p>

<p>I create a mock object locally on the stack and try to pass it around like so,</p>

<pre><code>Mock_Item mock_Item; //my mock type on which I would like to set expectations

DISPPARAMS dp = { nullptr, nullptr, 0, 0 };
VARIANT *args = new VARIANT[1];
VariantInit(&amp;args[0]);
args[0].vt = VT_DISPATCH;
args[0].pdispVal = &amp;mock_Item;
dp.rgvarg = args;
dp.cArgs = 1;
</code></pre>

<p><code>foo</code>, internally does the following,</p>

<pre><code>IDispatch* pCtrl(nullptr);
</code></pre>

<p>and tries to get the value out of the <code>pDispParams</code> passed to it </p>

<pre><code>if (pDispParams != nullptr &amp;&amp; 
pDispParams-&gt;rgvarg != nullptr &amp;&amp; 
VT_DISPATCH == pDispParams-&gt;rgvarg[1].vt)
        pCtrl = pDispParams-&gt;rgvarg[1].pdispVal;
</code></pre>

<p>but with this <code>pCtrl</code> always turns out to be <code>nullptr</code>. I'm not very good at using these types related to COM. <strong>How should I populate the <code>VARIANT</code> and  <code>DISPPARAMS</code> so that <code>pCtrl</code> will point to my mock object correctly ?</strong> In particular, it appears to me that, the condition (<code>VT_DISPATCH == pDispParams-&gt;rgvarg[1].vt</code>) fails, as I see in the debugger's watch window. It has a value that is not <code>9</code>(<code>VT_DISPATCH</code>). <code>Mock_Item</code> is derived from <code>IDispatch</code> as you might have guessed.</p>
",https://stackoverflow.com/questions/50522727/passing-dispparams,"['com', 'parameter-passing']",478,TRUE,1,1
Using local imports in Pytest,"<p>I have never really fully understood how packages are handled in Python and I'm having a problem with that right now. But googling doesn't seem to help as I find the topic really confusing.</p>

<p>I have a project with this structure:</p>

<pre><code>project_name/
    src/
        main.py
        utils/
            string_utils.py
    tests/
        test_string_utils.py
</code></pre>

<p>I am using Pytest for running unit testing and currently inside the  ""test_string_utils.py"" file I have the following:</p>

<pre><code>from ..src.utils.string_utils import StringUtilsClass
</code></pre>

<p>But I go to the folder ""project_name"" and try to run tests with any of this command I get errors:</p>

<pre><code>$ pytest tests/
</code></pre>

<p>ValueError: attempted relative import beyond top-level package</p>

<p>I know about the -m argument for python, but it seems that  running ""pytest -m"" has a completely different behavior.</p>

<p>How can I solve this? Am I using the wrong folder architecture? I don't think what I'm building should be a pip package (which would simplify imports) </p>
",https://stackoverflow.com/questions/53362259/using-local-imports-in-pytest,"['python', 'pytest']",384,TRUE,1,1
ComponentNotRegisteredException even with registered instance,"<p>I have an interface <code>IMyInterface</code> and I am registering a Moq object for unit testing like this</p>

<pre><code>var myMockObject = new Mock&lt;IMyInterface&gt;();
myMockObject.Setup(a =&gt; a.MyMethod(It.IsAny&lt;string&gt;()))
 .Returns(new MyResult()
{
    Props1 = ""Testing123"",
  }).Callback(() =&gt;
                {

                });

builder.RegisterInstance(myMockObject).As&lt;IMyInterface&gt;(); 
var test = container.Resolve&lt;IMyInterface&gt;();
</code></pre>

<p>But I am always getting the following error:  </p>

<blockquote>
  <p>Autofac.Core.Registration.ComponentNotRegisteredException: 'The
  requested service 'IMyInterface' has not been registered. To avoid
  this exception, either register a component to provide the service,
  check for service registration using IsRegistered(), or use the
  ResolveOptional() method to resolve an optional dependency.'</p>
</blockquote>

<p>One thing to note is that I am accessing the AutoFac builder inside a static class. I have made sure that the autofac builder instance is only created once.</p>

<p>UPDATE it looks like I have to call <code>builder.Build()</code> after registering the instance. I guess all instances and types have to be registered and after that you call <code>Build()</code>. So it's not really possible to register more instances after that.</p>
",https://stackoverflow.com/questions/48806357/componentnotregisteredexception-even-with-registered-instance,"['c#', 'dependency-injection', 'autofac']",3693,TRUE,1,1
How to fake a user in unit tests in Meteor using practicalmeteor:mocha?,"<p>I'm having a difficult time trying to test a methods in meteor that requires a connected user.  Basically I need to test if a user of the app can add an article to it's cart.  The methods will tests if a user is connected and, in order to test that will use Meteor.userId().  This seems to be a problem in unit testing as I get the error:<br>
""Meteor.userId can only be invoked in method calls or publications.""</p>

<p>So far, I tried to do what's proposed in this post: <a href=""https://stackoverflow.com/questions/41316635/how-to-unit-test-a-meteor-method-with-practicalmeteormocha"">How to unit test a meteor method with practicalmeteor:mocha</a> but I don't understand what the solution is doing.</p>

<p>Here is my testing method: </p>

<pre><code>import { Meteor } from 'meteor/meteor';
import { Random } from 'meteor/random';
import { assert } from 'meteor/practicalmeteor:chai';
import { sinon } from 'meteor/practicalmeteor:sinon';

import { Carts } from '/imports/api/carts/carts.js';
import { Articles } from '/imports/api/articles/articles.js';

import '/imports/api/carts/carts.methods.js';

import { SecurityEnsurer } from '/lib/security/security.js';

function randomInt (low, high) {
    return Math.floor(Math.random() * (high - low) + low);
}

if (Meteor.isServer) {
  describe('Carts', () =&gt; {
  describe('methods', () =&gt; {
    let currentUser;

    beforeEach(() =&gt; {
      Factory.define('user', Meteor.users, {
        name: ""userTest"",
        currentUser: {
          email: 'user@shop.info',
          password: '123456',
        }

      });

      currentUser = Factory.create('user');
      sinon.stub(Meteor, 'user');
      Meteor.user.returns(currentUser);

      Articles.remove({});

      articleId = Articles.insert({
        name : ""azerty"",
        description : ""descTest"",
        modelNumber : ""wxcvbn"",
        categoryName : ""CatTest"",
        price : 1,
        advisedPrice: 2,
        supplierDiscount : 0,
        brandId : ""BrandTest"",
        isAvailable: true,
        restockingTime: 42,
        color: ""Yellow"",
        technicals: [
          {
            name : ""GPU"",
            value : ""Intel""
          },
        ],
      });

      Carts.insert({
        owner: currentUser,
        entries: [],
      });

    });

    afterEach(() =&gt; {
      Meteor.user.restore();
      Articles.remove({});
      Carts.remove({});
    });

    it('can add article', () =&gt; {
      let quantity = randomInt(1,50);

      const addArticleToCart = Meteor.server.method_handlers['carts.addArticle'];

      const invocation = {};

      addArticleToCart.apply(invocation, [articleId, quantity]);

      assert.equal(Cart.find({owner: currentUser, entries: {$elemMatch: {articleId, quantity}}}).count(), 1);
      });
    });
  }); 
}
</code></pre>

<p>If anyone can help me find out how to create my test, this would realy help me.</p>
",https://stackoverflow.com/questions/48525183/how-to-fake-a-user-in-unit-tests-in-meteor-using-practicalmeteormocha,"['javascript', 'unit-testing', 'meteor', 'mocha.js']",693,TRUE,1,2
Testing HttpModule wtih Response.Filter and Response.Write,"<p>I'm working on an Http Module that simply records the response time and size and then appends the results to the response body.</p>

<p>My module looks something like this:</p>

<pre><code>public override void PreRequestHandlerExecute(HttpContextBase context)
{
    // Add a filter to capture response stream
    context.Response.Filter = new ResponseSniffer(context.Response.Filter);
}

public override void ApplicationEndRequest(HttpContextBase context)
{
    ....
    context.Response.Write(builder.ToString());
}
</code></pre>

<p>I now wish to unit test this module. I'm very new to unit testing. I've adapted code from <a href=""https://o2platform.wordpress.com/2011/04/05/mocking-httpcontext-httprequest-and-httpresponse-for-unittests-using-moq/"" rel=""nofollow noreferrer"">o2platform</a> to get a moq httpcontext and that works so far. However, the response filter does seem to get set in Pre and the response body is what I initialized it has from the test setup.</p>

<p>I've tried a handful options (and read a lot of stuff) but none of these seemed to work:</p>

<pre><code>public Mock&lt;HttpResponseBase&gt; MockResponse { get; set; }
...
var outputStream = new MemoryStream();
var filter = new MemoryStream();

//MockResponse.Setup(response =&gt; response.OutputStream).Returns(GetMockStream(outputStream).Object);
//MockResponse.Setup(response =&gt; response.Filter).Returns(GetMockStream(filter).Object);

MockResponse.Setup(response =&gt; response.OutputStream).Returns(() =&gt; outputStream);
//MockResponse.SetupSet(response =&gt; response.OutputStream = It.IsAny&lt;Stream&gt;()).Returns(() =&gt; outputStream);

MockResponse.Setup(response =&gt; response.Filter).Returns(() =&gt; filter);
MockResponse.SetupSet(response =&gt; response.Filter = It.IsAny&lt;Stream&gt;());
MockResponse.SetupSet(response =&gt; response.Filter = It.IsAny&lt;ResponseSniffer&gt;());
</code></pre>

<h1>Test Method</h1>

<pre><code>[TestMethod]
public void TestMethod1()
{
    var mockHttpContext = new MoqHttpContext();

    var httpContext = mockHttpContext.HttpContext();
    var html = @""&lt;html&gt;
                    &lt;head&gt;&lt;/head&gt;
                    &lt;body&gt;
                        &lt;h1&gt;Hello World&lt;/h1&gt;
                    &lt;/body&gt;
                &lt;/html&gt;"";

    httpContext.ResponseWrite(html);
    httpContext.StreamWrite(httpContext.Response.Filter, html);


    var module = new Module();

    module.PreRequestHandlerExecute(mockHttpContext.HttpContext());
    module.ApplicationBeginRequest(mockHttpContext.HttpContext());
    module.ApplicationEndRequest(mockHttpContext.HttpContext());

    var responseRead = httpContext.ResponseRead(); //extension method to get output stream
    var b = 1; //put breakpoint here
}
</code></pre>

<p>I realize the test needs to Assert rather then the breakpoint. I also realize that the test should be broken up a bit.</p>

<h1>Code Repo</h1>

<p><a href=""https://github.com/Eonasdan/httpmodule-challenge"" rel=""nofollow noreferrer"">Github</a></p>
",https://stackoverflow.com/questions/48888130/testing-httpmodule-wtih-response-filter-and-response-write,"['c#', 'integration-testing', 'moq']",797,TRUE,1,1
Junit test with entity mananger,"<p>I am beginner in Unit Testing. I have a Java Web Application build in Netbeans 8.1 and Maven. I have created this class to try to test querys in  my PostgreSQl database:</p>

<pre><code>public class DatesUtil {

    private Collection&lt;Menusistema&gt; listamenus = new LinkedList&lt;&gt;();

    private Menusistema menu= new Menusistema();

    private String nombreBuscar = null;

    private static final EntityManager entityManager;
    static {
        entityManager = Persistence.createEntityManagerFactory(""com.controlpersonal.pu"").
        createEntityManager();
    }

   public static EntityManager getEntityManager() { 
        return entityManager;
    };

    public DatesUtil() {

    }

    @BeforeClass
    public static void setUpClass() {


    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }

    // TODO add test methods here.
    // The methods must be annotated with annotation @Test. For example:
    //
     @Test
     public void hello() {
        buscarTodo();

     }


     public void buscarTodo(){
        findAll(Menusistema.class);
     }



    public &lt;T&gt; List&lt;T&gt; findAll(Class&lt;T&gt; clazz) {
        return (List&lt;T&gt;) getEntityManager().createQuery(""SELECT p FROM "" + clazz.getSimpleName() + "" p"", clazz).getResultList();
    }  


}
</code></pre>

<p>I got the next error when I right click on netbeans and select: Test File:</p>

<blockquote>
  <p>[EL Info]: 2018-04-30
  20:30:57.78--ServerSession(252553541)--EclipseLink, version: Eclipse
  Persistence Services - 2.5.2.v20140319-9ad6abd [EL Severe]: ejb:
  2018-04-30 20:30:57.836--ServerSession(252553541)--Exception
  [EclipseLink-7060] (Eclipse Persistence Services -
  2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.ValidationException Exception
  Description: Cannot acquire data source [jdbc/controlpersonal].
  Internal Exception: javax.naming.NoInitialContextException: Need to
  specify class name in environment or system property, or as an applet
  parameter, or in an application resource file: 
  java.naming.factory.initial</p>
</blockquote>

<p>My persistence.xml is:</p>

<pre><code>&lt;?xml version=""1.0"" encoding=""UTF-8""?&gt;
&lt;persistence version=""2.1"" xmlns=""http://xmlns.jcp.org/xml/ns/persistence"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xsi:schemaLocation=""http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd""&gt;
  &lt;persistence-unit name=""com.controlpersonal.pu"" transaction-type=""JTA""&gt;
    &lt;jta-data-source&gt;jdbc/controlpersonal&lt;/jta-data-source&gt;
    &lt;exclude-unlisted-classes&gt;false&lt;/exclude-unlisted-classes&gt;
    &lt;properties/&gt;
  &lt;/persistence-unit&gt;
&lt;/persistence&gt;
</code></pre>

<p>I really would like to test if this is posible. Thanks in advance!</p>
",https://stackoverflow.com/questions/50110708/junit-test-with-entity-mananger,"['java', 'unit-testing', 'junit', 'eclipselink', 'entitymanager']",6040,TRUE,1,1
Creating a factory inside the state and getting the id of itself in Laravel,"<p>I am developing a Laravel application. I am using factories in my application especially for unit testing and setting them up, but I am having an issue with setting up the factory with state. Here is my database structure:</p>
<h2>Bid</h2>
<pre><code>id, amount, created_at, updated_at, user_id
</code></pre>
<p>Then I have another model as follows:</p>
<h2>BidLog</h2>
<pre><code>id, bid_status, created_at, updated_at, bid_id
</code></pre>
<p>The database structure is pretty straight forward. The thing is the BidLog will only be created in the event listener of the Bid. It only exists when the Bid exists. It is basically the state of the Bid. So when I set up the factory for the BidLog, I set up something like this.</p>
<p>BidLogFactory.php</p>
<pre><code>$factory-&gt;define(BidLog::class, function (Faker $faker) {
    $bid = Bid::inRandomOrder()-&gt;first();
    return [
        'bid_id' =&gt; $bid-&gt;id,
        'bid_status' =&gt; 'open'//Bid factory will override this value
    ];
});
</code></pre>
<p>Then I set up the states of the BidFactory like this.</p>
<pre><code>$factory-&gt;state(Bid::class, 'open', function ($faker) {
    $bidLog = factory(BidLog::class)-&gt;create([
       'bid_status' =&gt; 'open',
       'bid_id' =&gt; //how can I get the bid id here?
    ]);
    return [
       'updated_at' =&gt; now()
    ];
});
</code></pre>
<p>The thing is how can get the Bid id in the state callback function? Or how can I set it up?</p>
",https://stackoverflow.com/questions/53301757/creating-a-factory-inside-the-state-and-getting-the-id-of-itself-in-laravel,"['laravel', 'factory']",3076,TRUE,1,2
Why does clang++ report a structured binding with &quot;value stored to &#39;...&#39; during its initialization is never read&quot;?,"<p>I have the following test case:</p>

<pre><code>testcase(""[room] exits"") {
    auto [center, east, north, south, west] = make_test_rooms();

    check_eq(center-&gt;east(), east);
    check_eq(center-&gt;north(), north);
    check_eq(center-&gt;south(), south);
    check_eq(center-&gt;west(), west + 1);
}
</code></pre>

<p>When I compile it, clang++ (clang version 5.0.1 (tags/RELEASE_501/final)) reports:</p>

<pre><code>room.cpp:52:7: note: Value stored to '[center, east, north, south, west]' during its initialization is never read
</code></pre>

<p>In the code above, <code>testcase</code> and <code>check_eq</code> are macros defined for <a href=""https://github.com/onqtam/doctest"" rel=""nofollow noreferrer"">the doctest unit testing package</a> that expand to <code>DOCTEST_TEST_CASE()</code> (some kind of self-registering variable+function pair) and <code>DOCTEST_CHECK_EQ</code> (basically, ""assert a == b"", with magic handling).</p>

<p>I know this code is being executed, since the <code>west + 1</code> is a deliberately-introduced error. When I run my tests, I get a failure message like this one:</p>

<pre><code>===============================================================================
/.../room.cpp(51)
TEST CASE:  [room] exits

/.../room.cpp(57) ERROR!
  CHECK_EQ( center-&gt;west(), west + 1 )
with expansion:
  CHECK_EQ( 0x00007fd6f1d011a0, 0x00007fd6f1d011f8 )
</code></pre>

<p>As far as I can see, I am using all of the values in the structured binding: <code>center</code> appears on the left of my checks, and <code>north, south, east, west</code> appear on the right. Why is clang++ reporting something as ""never read""? </p>

<p><strong>Update</strong></p>

<p>Here is code that reproduces the issue. I run this command line (taken from the output of <code>make VERBOSE=1</code> and reduced):</p>

<pre><code>$ /opt/local/bin/cmake -E __run_co_compile --tidy=/opt/local/bin/clang-tidy --source=test.cpp -- /opt/local/bin/clang++  -g -std=gnu++1z -o test.cpp.o -c test.cpp
/Users/austin/Code/agb/test.cpp:12:7: warning: Value stored to '[a, b, c]' during its initialization is never read [clang-analyzer-deadcode.DeadStores]
        auto [a,b,c] = foo();
             ^
/Users/austin/Code/agb/test.cpp:12:7: note: Value stored to '[a, b, c]' during its initialization is never read
</code></pre>

<p>I used this source file as <code>test.cpp</code>:</p>

<pre><code>#include &lt;tuple&gt;

static std::tuple&lt;int, int, int&gt;
foo()
{
    return {1,2,3};
}

bool
test()
{
    auto [a,b,c] = foo();

    return a&lt;b and b&lt;c;
}
</code></pre>
",https://stackoverflow.com/questions/48412729/why-does-clang-report-a-structured-binding-with-value-stored-to-during,"['c++', 'clang++', 'c++17', 'structured-bindings']",1494,FALSE,5,1
how to test controller methods in c#,"<p>I have recently started unit testing c# code But I never tested controller classes before. I have following class I need to write test cases for this. </p>

<pre><code>namespace nH.MasterData.API.Controllers
{
    [Produces(""application/json"")]
    [Route(""api/AType"")]
    public class ATypeController : Controller
    {
        private readonly IProcessor _domain;
        private readonly ILogger _logger;
        private const string Version = ""VERSION_1"";
        private const string Model = ""model"";
        private const string Entity = ""AType"";

        public ATypeController(IProxy proxy, ILogger&lt;ATypeController&gt; logger)
        {
            _logger = logger;
            var proxy = proxy.GetProxy();
            _domain = new InstitutionAddressProcessor(proxy);
        }

        [HttpGet]
        public OkObjectResult Get()
        {
            try
            {
                return Ok(_domain.GetATypesMembers(Model, Version, Entity, MemberType.Leaf, null));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message + "" "" + ex.StackTrace);
                return new OkObjectResult(BadRequest());
            }
        }

    }
}
</code></pre>

<p>Here, <code>_domain.GetATypesMembers()</code> is not in my project and I am not creating the object of <code>_domain</code> explicitly (Its created inside the constructor). How Do I get control over the object which is being created in constructor? So that I can mock the response when called without actually making actual call.</p>

<p>Usually, I would <code>setup</code> the mock on the object as <code>wcfMockService.Setup(x =&gt; x.GetATypesMembers(...).ReturnAsync(response);</code> But how can I write for this one? </p>

<p>I appreciate any suggestions. </p>

<p>Edit1: 
creating objects inside the constructor is bad practice. But this is a legacy code and being used in many places. So I am just trying to write tests as the code exists. </p>
",https://stackoverflow.com/questions/52194951/how-to-test-controller-methods-in-c,"['c#', 'api', 'controller', 'nunit', 'moq']",1469,TRUE,0,4
Mocked java class in spock test is not being executed,"<p>I'm trying to use spock framework for unit testing some java class. The structure looks like this:</p>

<ul>
<li><code>com.myorg.requests</code> (Class name: <code>RequestProcessor</code>)</li>
<li><code>com.myorg.query</code> (Class name: <code>DatabaseQuery</code>)</li>
</ul>

<p>The first class looks something like this:</p>

<pre><code>public class RequestProcessor {

   private String request;

   public RequestProcessor(String aRequest) {
      this.request = request;
   }

   public String processRequest() {
       String response ;
       //do something here

       try {
           if(condition meets) {
              response = executeRequest();
           }
       } catch ( various exceptions... ) {
           System.out.println(""something went wrong..."");
       }
   }

   private String executeRequest() throws &lt;&lt;exceptions thrown by DatabaseQuery&gt;&gt; {
       //do something here
       DatabaseQuery queryResult = new DatabaseQuery(request)
   }
}
</code></pre>

<p>I'm trying to write a Spock test for this <code>RequestProcessor</code> class which has a dependency on <code>DatabaseQuery</code>. I'm thinking of mocking <code>DatabaseQuery</code> class in order to simply test the <code>RequestProcessor</code> class in isolation.</p>

<p>The <code>RequestProcessor</code>'s <code>processRequest()</code> method is being called, which relies on another private method. That method will use <code>DatabaseQuery</code> to get the actual query result. This is what my Spock test looks like:</p>

<pre><code>class RequestProcessorSpec extends Specification {

    //Class to be tested
    RequestProcessor requestProcessor

    //Dependencies
    DatabaseQuery dbquery

    def ""Given a valid request, dbquery's executeQuery method is called"" () {
        given: ""a valid request""
            def queryRequest = '{""info1"":""value1"",""info2"":""value2"",""query"":""select * from users""}'

        and: ""mock the DBQuery class""
            dbquery = Mock(DatabaseQuery)

        and: ""create a new request""
            requestProcessor = new RequestProcessor(queryRequest)

        when: ""the request is processed""
            requestHandler.processRequest()

        then: ""dbquery executeQuery method is called""
            1 * dbquery.executeQuery(_ as String)
    }
 }
</code></pre>

<p>This isn't exactly working for me. I'm getting an error:</p>

<ul>
<li>Too few invocations</li>
<li>Unmatched invocations</li>
</ul>

<p>When I run the test with <code>gradlew test --info</code> for more results, I see a log printed on the console that is captured by try-catch statement in <code>processRequest</code> method.</p>

<p>What am I doing wrong here?</p>
",https://stackoverflow.com/questions/49302445/mocked-java-class-in-spock-test-is-not-being-executed,"['java', 'unit-testing', 'mocking', 'spock']",1964,TRUE,0,1
"Testing Javascript (Server: Node.js, Client: React - Redux - Saga)","<p><em>A quick disclaimer: I am not having issues, I am simply asking for guidance. I don't feel like the other topics provide a guiding point towards a particular style of testing or library rather than just helping other with their actual choice of library and style.</em></p>

<p>Hey guys! I was thinking, is there anyone in here that could provide me with some guidance for unit testing? What kind of testing do I want (I am a newbie)? e2e, tdd, bdd etc.? Any particular recommendations for libraries and good practices? I am currently working on a React Redux-Saga project and a node backend that we'd like to start testing as well. Is there library that we can use for both or do we need two different since it is essentially two different projects (Client, Server).</p>
",https://stackoverflow.com/questions/49066525/testing-javascript-server-node-js-client-react-redux-saga,"['javascript', 'reactjs', 'unit-testing', 'redux', 'redux-saga']",57,TRUE,0,2
Why java lambda jumps filter,"<p>I have the following code:</p>

<pre><code>public List&lt;MainObject&gt; filterListByNestedObjectAttribute(List&lt;MainObject&gt; mainObjects) {
    List&lt;MainObject&gt; mainObjectFiltered = mainObjects.stream()
                .filter(mainObject -&gt; {
                    NestedObject nestedObject = Collections.max(mainObject.getNestedObjects(), Comparator.comparing(nestedObject -&gt; nestedObject.getDate()));
                    return businessValidation(nestedObject) || businessValidation2(nestedObject);
                })
                .collect(Collectors.toList());
}
</code></pre>

<p>The point is, the filter is NEVER called...
Doesn't matter what I do, the filter is ignored and the result of the stream is the <strong>same</strong> list!!</p>

<p>Am I doing something wrong?
The call to another Java lambda breaks the filter call?</p>

<hr>

<p>EDIT</p>

<p>I applied the same code in the void main and worked...</p>

<p>In unit test the IDE is caching the value of filter, I don't know why...</p>

<p>Code:</p>

<pre><code>public class LambdaJumpsFilter {

    public static void main(String[] args) {
        LambdaJumpsFilter lambdaJumpsFilter = new LambdaJumpsFilter();

        NestedObject nestedA1 = lambdaJumpsFilter.new NestedObject(""A"", OffsetDateTime.now().plusDays(3));
        NestedObject nestedB1 = lambdaJumpsFilter.new NestedObject(""B"", OffsetDateTime.now().plusDays(2));
        NestedObject nestedC1 = lambdaJumpsFilter.new NestedObject(""C"", OffsetDateTime.now().plusDays(1));
        NestedObject nestedA2 = lambdaJumpsFilter.new NestedObject(""A"", OffsetDateTime.now().plusDays(1));
        NestedObject nestedB2 = lambdaJumpsFilter.new NestedObject(""B"", OffsetDateTime.now().plusDays(2));
        NestedObject nestedC2 = lambdaJumpsFilter.new NestedObject(""C"", OffsetDateTime.now().plusDays(3));

        MainObject mainObject1 = lambdaJumpsFilter.new MainObject();
        MainObject mainObject2 = lambdaJumpsFilter.new MainObject();

        List&lt;NestedObject&gt; nestedObjects1 = new ArrayList&lt;&gt;();
        nestedObjects1.add(nestedA1);
        nestedObjects1.add(nestedB1);
        nestedObjects1.add(nestedC1);

        List&lt;NestedObject&gt; nestedObjects2 = new ArrayList&lt;&gt;();
        nestedObjects2.add(nestedA2);
        nestedObjects2.add(nestedB2);
        nestedObjects2.add(nestedC2);

        mainObject1.setNestedObjects(nestedObjects1);
        mainObject2.setNestedObjects(nestedObjects2);

        List&lt;MainObject&gt; mainObjects = new ArrayList&lt;&gt;();
        mainObjects.add(mainObject1);
        mainObjects.add(mainObject2);

            List&lt;MainObject&gt; mainObjectFiltered = mainObjects.stream()
                    .filter(mainObject -&gt; {
                        NestedObject nestedObjectMax = Collections.max(mainObject.getNestedObjects(), Comparator.comparing(nestedObject -&gt; nestedObject.getDateTime()));
                        return lambdaJumpsFilter.businessValidation(nestedObjectMax) || lambdaJumpsFilter.businessValidation2(nestedObjectMax);
                    })
                    .collect(Collectors.toList());

        System.out.println(mainObjectFiltered.size());
    }

    private boolean businessValidation2(NestedObject nestedObject) {
        return nestedObject.equals(""D"");
    }

    public boolean businessValidation(NestedObject nestedObject){
        return nestedObject.value.equals(""A"");
    }

    public class MainObject{
        private List&lt;NestedObject&gt; nestedObjects;


        public List&lt;NestedObject&gt; getNestedObjects() {
            return nestedObjects;
        }

        public void setNestedObjects(List&lt;NestedObject&gt; nestedObjects) {
            this.nestedObjects = nestedObjects;
        }
    }

    public class NestedObject {
        private String value;
        private OffsetDateTime dateTime;

        public NestedObject(String value, OffsetDateTime dateTime) {
            this.value = value;
            this.dateTime = dateTime;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }

        public OffsetDateTime getDateTime() {
            return dateTime;
        }

        public void setDateTime(OffsetDateTime dateTime) {
            this.dateTime = dateTime;
        }
    }

}
</code></pre>

<hr>

<p>I know it was despair, but I spent hours looking for something like that.</p>

<p>I found the why not DEBYG not pass in the filter ...</p>

<p>As I'm doing unit testing, I spend the same value and (I don't know why) the IDE already knows the value of the filter and ends up ignoring the filter.</p>
",https://stackoverflow.com/questions/49831178/why-java-lambda-jumps-filter,"['java', 'lambda']",77,TRUE,0,1
"Error while doing writing unit test case -Could not load file or assembly &#39;Oracle.DataAccess, Version=4.112.4.0","<p>We have a requirement to do unit testing using either MS Test or NUnit Framework for our C# code. There are many methods which includes DB call. When trying to do so, I am getting below error:</p>

<p><strong>*{""Could not load file or assembly 'Oracle.DataAccess, Version=4.112.4.0, Culture=neutral, PublicKeyToken=*******' or one of its dependencies. An attempt was made to load a program with an incorrect format.""}*</strong></p>

<p>I checked the Oracle version to make sure there is no mismatch, but no success. Also read couple of articles that instead of making DB call one should be using mocking to bypass DB. But with this limitation the coverage is very minimal.
Could anyone please guide to fix the above error. Adding the sample code which i tried just for POC</p>

<pre><code>public class Class1
    {
        public IEnumerable&lt;ModelClass&gt; GetListOfExceptions()
        {
            OracleConnection conn = new OracleConnection(Constants.ConnectionString);
            try
            {
                conn.Open();
                OracleCommand cmd = new OracleCommand(Constants.&lt;Oracle Query&gt;, conn);
                cmd.CommandType = CommandType.Text;
                //cmd.CommandType = CommandType.StoredProcedure;
                OracleDataReader dr = cmd.ExecuteReader();
                ModelClass modelException = null;
                List&lt;ModelClass&gt; lst = new List&lt;ModelClass&gt;();
                while (dr.Read())
                {
                    modelException = new ModelClass();
                    modelException.POLICYNO = Convert.ToString(dr.GetValue(1));
                    modelException.PREMIUM = Convert.ToInt32(dr.GetValue(2));
                    modelException.AGE = Convert.ToInt32(dr.GetValue(3));
                    lst.Add(princeException);
                }
                return lst;

            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                conn.Close();
            }

        }


    }

    [TestFixture]
    public class Class1Tests
    {
        [Test]
        public void GetListOfExceptionsTest()
        {
            Class1 obj = new Class1();
            obj.GetListOfExceptions();

        }
     }
</code></pre>
",https://stackoverflow.com/questions/49490287/error-while-doing-writing-unit-test-case-could-not-load-file-or-assembly-oracl,"['c#', 'oracle', 'unit-testing', 'nunit']",509,FALSE,0,2
"Should I use mocking, or Enzyme with shallow?","<p>I have studying React for a couple of weeks now and I have just started to get into the Unit testing part. 
I am quite confused tho as there are very little standards when it comes to testing. 
I have seen that a lot of people opt for 'Jest' so this is the path that I chose too.
Since I am working with ES6 classes in my code, I can't just export the methods, I export the component classes. <br/>
The code here is my testing case which works fine, but I don't want to build bad practices from the go: </p>

<pre><code>import Calc from './Calc';
import React from 'react';
import {configure, shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

configure({ adapter: new Adapter() });

const wrapper = shallow(&lt;Calc /&gt;);

const calculator = wrapper.instance();


test('Parentheses should close and evaluate automatically',() =&gt; {
    calculator.clear();
    const start = ['2','*(', '2', '+', '2'];


    for (let i = 0; i &lt; start.length; i++) {
        calculator.addSign(start[i]);
    }
    calculator.calculate()

    expect(calculator.state.answ).toBe(8);

});
</code></pre>

<p>And this is part of the Calc component(the function which is to be evaluated): </p>

<pre><code>class Calc extends React.Component{

state = {
    answ: 0,
    sumToEval: [],
    sumToShow:'',
}

calculate = () =&gt; {
    try{
        let sum = '';
        let bClose = false;
        let bStartingIndex = -1;
        let openCount = 0;
        let closeCount = 0;
        let closeString = '';
        for (let i = 0; i &lt; this.state.sumToEval.length; i++) {
            if (this.state.sumToEval[i].indexOf('(') &gt; -1) {
                if(bStartingIndex === -1) {
                    bStartingIndex = i;
                }
                openCount++;
            }
        }
        if (bStartingIndex &gt; -1) {
            bClose = true;
            for (let i = bStartingIndex; i &lt; this.state.sumToEval.length; i++) {
                if ( this.state.sumToEval[i].indexOf(')') &gt; -1 ) {
                    bClose = false;
                    closeCount ++;
                }
            }
        }

        for (let i = 0; i &lt; openCount-closeCount; i++) {
            closeString += ')';
        }



        // eslint-disable-next-line
        this.state.sumToEval.map((val) =&gt; {sum += val;})
        let answ;
        // eslint-disable-next-line
        bClose ? answ = eval(sum + closeString) : answ = eval(sum);
        console.log(answ);
        this.setState((prevState) =&gt;{
            if (!bClose) {
                return {
                    answ: answ,
                    sumToEval: [answ + ''],
                    sumToShow: answ
                }
            }else{

                let tempArr = prevState.sumToEval;
                tempArr.push(')');
                return{
                    answ: answ,
                    sumToEval: [answ + ''],
                    sumToShow: answ
                }
            }

        });

    }catch(err){
      //  console.log(err);
        throw err;
    }
}
</code></pre>

<p>So is this the proper approach or is mocking the components always the way to go? </p>
",https://stackoverflow.com/questions/51139003/should-i-use-mocking-or-enzyme-with-shallow,"['javascript', 'jestjs', 'enzyme']",41,FALSE,0,1
Pytest test case fails but gives correct result when run from terminal with same input,"<p>I am new to pytest and using it for unit testing my python code.
I have a class called <code>ProblemSorting</code> in the file called <code>difficulty</code>. There is a method <code>get_difficulty_order()</code> in the class.</p>

<p>Below is the unit test that I have written to test the method:</p>

<pre><code>import pytest
from difficulty import ProblemSorting

@pytest.mark.parametrize(""num_of_problems, num_of_subtasks, problems, result"",
                         [
                             pytest.param(3, 3, [[16, 24, 60],
                                                 [498, 861, 589],
                                                 [14, 24, 62],
                                                 [72, 557, 819],
                                                 [16, 15, 69],
                                                 [435, 779, 232]], [2, 1, 3]),
                             pytest.param(1, 1, [[2], [5]], [1]),
                             pytest.param(0, 0, [], [])])
def test_get_difficulty_order(num_of_problems, num_of_subtasks, problems, result):
    '''hello'''
    prob_sort = ProblemSorting(num_of_problems, num_of_subtasks, problems)
    assert prob_sort.get_difficulty_order() == result
</code></pre>

<p>Now the problem is that the <code>2nd</code> test case fails. But when I remove the <code>1st</code> and the <code>3rd</code> test cases and retain the <code>2nd</code> test case it works. Even when I manually check the code with the <code>2nd</code> input it gives the expected result.</p>

<p><strong>Note:</strong> I have also noted that no matter how many test cases it has it only succeed the first and the last test case and all in the middle fails.</p>

<p><strong>Edit:</strong> difficulty.py
'''check'''</p>

<pre><code>import operator

class ProblemSorting:
    '''Class implementing various methods to solve the problem
       which requires ordering of problem based on its difficulty level
    '''

    # stores the tuple (i, difficulty) where 'i' is the problem number
    # and 'difficulty' is the difficulty level associated with the 'i'th problem
    difficulty_of_problems = list()

    def __init__(self, num_of_problems, num_of_subtasks, problems):
        self.num_of_problems = num_of_problems
        self.num_of_subtasks = num_of_subtasks
        self.problems = problems
</code></pre>

<p>I don't understand what is wrong with this.
Any help will be greatly appreciated.</p>
",https://stackoverflow.com/questions/53567021/pytest-test-case-fails-but-gives-correct-result-when-run-from-terminal-with-same,"['python', 'unit-testing', 'pytest']",276,FALSE,0,0
How can I use functions and objects without require them in NodeJS,"<p>I have been studying NodeJS for about a year and today I found something strange for me. We all know that in order to use a module (function, object or variable) in another module we must export and import it except for the native modules like String, Number, Promise, etc. I installed an external package for unit testing called <a href=""https://facebook.github.io/jest/"" rel=""nofollow noreferrer"">Jest</a>.</p>

<p>The strange thing here is that I have created two test modules called: <code>logic.js</code> and <code>logic.test.js</code>, in none I have imported the Jest module, however I can access all its methods. Let's show some code:</p>

<p><strong>logic.js</strong> </p>

<pre><code>module.exports.add = function(a, b){
    return a + b;
}
</code></pre>

<p><strong>logic.test.js</strong></p>

<pre><code>const lib = require('../logic')

test('Add - Should return the sum of two numbers', () =&gt; {
    const result = lib.add(1,3);
    expect(result).toBe(4);
});
</code></pre>

<p>As you can see in <code>logic.test.js</code> I have access to <strong><code>expect</code></strong> and <strong><code>test</code></strong> methods and i have not impoted nothing about Jest.</p>

<p>The questions here are:</p>

<ul>
<li>How is this posible? </li>
<li>Its a good practice to do this with my modules</li>
</ul>
",https://stackoverflow.com/questions/50818702/how-can-i-use-functions-and-objects-without-require-them-in-nodejs,"['javascript', 'node.js', 'import', 'module', 'export']",953,TRUE,0,1
Makefile weird variable behaviour,"<p>In the following Makefile, I'm modifying the content of $(SRC) based on whether the target rule is 'test'. This rule is supposed to be for unit testing.<br>
My objects are built with the implicit rule<br>
<code>OBJ =    $(SRC:.cpp=.o)</code><br>
but when building the object, even if the SRC variable changes, it always uses its default value. Here is the Makefile :</p>

<pre><code>CC =              g++

SRC_DIR =         src
SRC_TEST_DIR =    tests/src

INC_DIR =         include/
test: INC_DIR +=  tests/include/

SRC_MAIN =        $(SRC_DIR)/main.cpp
test: SRC_MAIN =  $(SRC_TEST_DIR)/main.cpp

SRC =             $(SRC_MAIN) \             # &lt;=== The value that changes in SRC
                  $(SRC_DIR)/minicalc.cpp \
                  $(SRC_DIR)/io.cpp

OBJ =             $(SRC:.cpp=.o)

CPPFLAGS +=       -I$(INC_DIR) -g -Wall -Wextra

test: LDFLAGS +=  -lcppunit

OUT =             minicalc
test: OUT =       tests/tests


all: $(OBJ)
# DEBUG :
    @echo SRC: '$(SRC)'
    @echo OBJ: '$(OBJ)'

    $(CC) $(OBJ) -o $(OUT) $(LDFLAGS)

test: all
    ls $(OUT) &amp;&amp; ./$(OUT)
</code></pre>

<p><strong>Here are the outputs</strong> :<br>
<code>make</code> gives expected output with default value of SRC :</p>

<pre><code>g++  -Iinclude/ -g -Wall -Wextra  -c -o src/main.o src/main.cpp
g++  -Iinclude/ -g -Wall -Wextra  -c -o src/minicalc.o src/minicalc.cpp
g++  -Iinclude/ -g -Wall -Wextra  -c -o src/io.o src/io.cpp
SRC: src/main.cpp src/minicalc.cpp src/io.cpp 
OBJ src/main.o src/minicalc.o src/io.o
g++ src/main.o src/minicalc.o src/io.o -o minicalc 
</code></pre>

<p>But <code>make test</code> doesn't build test/src/main.o even if it is in SRC :</p>

<pre><code>g++  -Iinclude/ -g -Wall -Wextra  -c -o src/main.o src/main.cpp
g++  -Iinclude/ -g -Wall -Wextra  -c -o src/minicalc.o src/minicalc.cpp
g++  -Iinclude/ -g -Wall -Wextra  -c -o src/io.o src/io.cpp
SRC: tests/src/main.cpp src/minicalc.cpp src/io.cpp 
OBJ: tests/src/main.o src/minicalc.o src/io.o
g++ tests/src/main.o src/minicalc.o src/io.o -o tests/tests -lcppunit
g++: error: tests/src/main.o: No such file or directory
make: *** [Makefile:41: all] Error 1
</code></pre>

<p><code>all</code> requires <code>$(OBJ)</code>, but <strong>the object created are not corresponding to the content of the <code>$(SRC)</code> variable</strong></p>

<hr>

<p><strong>Not using the implicit .cpp.o rules by doing it manually WORKS</strong> :<br>
<em>Same Makefile but replaced <code>$(OBJ)</code> by the rule <code>create_obj</code></em></p>

<pre><code>CC =              g++

SRC_DIR =         src
SRC_TEST_DIR =    tests/src

INC_DIR =         include/
test: INC_DIR +=  tests/include/

SRC_MAIN =        $(SRC_DIR)/main.cpp
test: SRC_MAIN =  $(SRC_TEST_DIR)/main.cpp

SRC =             $(SRC_MAIN) \
                  $(SRC_DIR)/minicalc.cpp \
                  $(SRC_DIR)/io.cpp    

OBJ =             $(SRC:.cpp=.o)

CPPFLAGS +=       -I$(INC_DIR) -g -Wall -Wextra

test: LDFLAGS +=  -lcppunit

OUT =             minicalc
test: OUT =       tests/tests


all: create_obj
# DEBUG :
    @echo   SRC: '$(SRC)'
    @echo   obj: '$(OBJ)'

    $(CC) $(OBJ) -o $(OUT) $(LDFLAGS)

create_obj:
    @echo Crafting Files:
    @$(foreach file, $(SRC), \
        echo  $(file),;  \
        $(CC) -c $(file) -o $(file:.cpp=.o) $(CPPFLAGS) $(LDFLAGS); \
    )

test: all
    ls $(OUT) &amp;&amp; ./$(OUT)
</code></pre>

<p><strong>Here are the outputs</strong> :<br>
<code>make</code> :</p>

<pre><code>Crafting Files:
src/main.cpp,
src/minicalc.cpp,
src/io.cpp,
SRC: src/main.cpp src/minicalc.cpp src/io.cpp 
OBJ: src/main.o src/minicalc.o src/io.o
g++ src/main.o src/minicalc.o src/io.o -o minicalc 
</code></pre>

<p><code>make test</code></p>

<pre><code>Crafting Files:
tests/src/main.cpp,
src/minicalc.cpp,
src/io.cpp,
SRC: tests/src/main.cpp src/minicalc.cpp src/io.cpp 
OBJ tests/src/main.o src/minicalc.o src/io.o
g++ tests/src/main.o src/minicalc.o src/io.o -o tests/tests -lcppunit
ls tests/tests &amp;&amp; ./tests/tests
tests/tests


OK (0)
</code></pre>

<hr>

<p>Why does the implicit building of my objects not change when changing my sources, while doing it manually works ?</p>
",https://stackoverflow.com/questions/52569402/makefile-weird-variable-behaviour,['makefile'],133,TRUE,0,2
abstract hardware dependencies in c++,"<p>I'm trying to abstract away hardware dependencies for an embedded application.</p>

<p>I have an interface (frameWriterI.h)</p>

<pre><code>template&lt;typename Message)    
class FrameWriterI
{
     public:
        virtual void writeMessage(Message m)=0;
}
</code></pre>

<p>With multiple implementations like this one</p>

<pre><code>(writerA.h)
class WriterA : public FrameWriterI&lt;MessageA&gt;
{
   public:
     void writeMessage(MessageA m)
}
(writerA.cpp)
void WriterA::writeMessage(MessageA m)
{
     /*use a DAC to write m with a format specific to A*/
     somethingReallyHardwareSpecific();
}
</code></pre>

<p>In the layer above, I have 1 state machine per implementation (A, B, C) that use the related Writers</p>

<pre><code> class StateMachineA:
 {
    public:
        void doSomethingThatUseWriterA();
    private:
         WriterA writer;
}
</code></pre>

<p>problem is that now, my state machines are hardware dependent. So in order to mock the writer for unit testing, I should use the interface instead:</p>

<pre><code> class StateMachineA:
 {
    public:
        void doSomethingThatUseWriterA();
    private:
         FrameWriterI&lt;MessageA&gt;&amp; writer;
}
</code></pre>

<p>but where do I initialize the real WriterA?</p>

<p>in the constructor I cannot reference a temporary</p>

<pre><code>(StateMachineA.cpp)
StateMachineA::StateMachineA(): writer(WriterA()){} //not valid
</code></pre>

<p>I try to avoid pointers as much as possible (limited heap space and coding preference) but if it's the only solution I could live with it but it can't be dynamically allocated.</p>

<p>The only solution that I found so far is the have a file scoped variable</p>

<pre><code>(StateMachineA.cpp)
WriterA realWriter;
StateMachineA::StateMachineA(): writer(realWriter){}
</code></pre>

<p>Any better/cleaner solution?</p>
",https://stackoverflow.com/questions/51540157/abstract-hardware-dependencies-in-c,"['c++', 'embedded', 'abstract-class', 'hardware-interface']",242,FALSE,0,0
How To Unit Test Multiple Instances Of Class In xUnit,"<p>I'm fairly new to unit testing. I understand the concept, but I keep find myself bumping into walls with the execution. How, in xUnit, do I test multiple instances of a class? For instance, say I have a constructor with a signature:</p>

<pre><code>public FileWatcher(string path = """", bool startWatching = true)
</code></pre>

<p>I want to run all of my unit tests for each public property and method that I'm testing against multiple instances of <code>FileWatcher</code>, each with the constructor passed different arguments. This way I can run all of my tests against an instance of <code>FileWatcher</code> where no arguments were passed in, and then one where arguments were. I don't know if what I'm trying to do reeks of code smell or if I don't know the correct nomenclature to turn up any results, but I can't find <em>anything</em> on this subject.</p>
",https://stackoverflow.com/questions/50479236/how-to-unit-test-multiple-instances-of-class-in-xunit,"['c#', 'unit-testing', 'xunit']",1495,TRUE,0,1
how to do error handling in Nifi Template,"<p>I am creating template in Nifi, and then importing them in Kylo. Each template is specific to my business usecase, and they consist of multiple (30+) Nifi processors. </p>

<p>for my unit testing and for some sanity, I am forwarding error relationship of each processor to separate logAttribute.</p>

<p>but when I am importing this template to Kylo, even when flow fails, Kylo doesn't treat it as error, as all errors are going to logArribute.</p>

<p>Now I can forward error relation of each processor within template to single logArribute. And then forward that flow to Kylo's error port.</p>

<p>Is this a right solution? if not, what other developers do? I am thinking, Nifi should have some sort of SINK processor where I am dump all my error relation.</p>

<p>Please comment.</p>

<p>Thanks,</p>
",https://stackoverflow.com/questions/52325545/how-to-do-error-handling-in-nifi-template,"['apache-nifi', 'kylo']",441,FALSE,0,0
Unit test with angular 5. I am trying mock a service but I receive : &quot;[object ErrorEvent] thrown&quot;,"<p>I am trying mock a service but I receibe : ""[object ErrorEvent] thrown"".</p>

<p>I'm trying using the way proposed by snorkpete:</p>

<p><a href=""https://stackoverflow.com/questions/43549861/unit-testing-and-mocking-a-service-with-di"">Unit testing and mocking a service with DI</a></p>

<p>This is the test that is returning 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-js lang-js prettyprint-override""><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { MyComponent1Component } from './my-component1.component';
import {MyService1Service} from '../../service/my-service1.service';
import {MyComponent2Component} from '../../components/my-component2/my-component2.component'


fdescribe('MyComponent1Component', () =&gt; {
  let component: MyComponent1Component;
  let fixture: ComponentFixture&lt;MyComponent1Component&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ MyComponent1Component,MyComponent2Component ],
      imports: [],
      providers: [{ provide: MyService1Service, useClass: MockService }]
    }) 
    .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(MyComponent1Component);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
});

class MockService {
 	
	id: 1;
	userId: 'ruben';
	body: 'test';
};</code></pre>
</div>
</div>
</p>

<p>This is .ts component1 src/app/my-component1/my-component1.component.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 { Component, OnInit,Renderer2,ViewChild,ElementRef } from '@angular/core';
import {MyService1Service} from '../../service/my-service1.service';
import { Post } from '../../models/post';
@Component({
  selector: 'app-my-component1',
  templateUrl: './my-component1.component.html',
  styleUrls: ['./my-component1.component.css']
})
export class MyComponent1Component implements OnInit {
  @ViewChild(""myButton"") myButton: ElementRef;
  constructor(private renderer: Renderer2, private _myService1Service: MyService1Service) { }
  public messagge1: Post[];

  func1(){    
    this.renderer.addClass(this.myButton.nativeElement, ""my-class"");
    this._myService1Service.test();
  }

  ngOnInit() {
    
    this._myService1Service.getPost().subscribe(
      result =&gt;{
        console.log(""from component1"")
        console.log(result);
        this.messagge1=result;
      },
      error =&gt; {
        console.log(error);
      }
    )
  }
}</code></pre>
</div>
</div>
</p>

<p>This is the html component1 src/app/my-component1/my-component1.component.html:</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;p&gt;
  my-component1 works!
&lt;/p&gt;

&lt;button #myButton (click)=""func1()""&gt;press me&lt;/button&gt;
&lt;app-my-component2 *ngIf=""messagge1"" [messagge1]=""messagge1""&gt;loading...&lt;/app-my-component2&gt;</code></pre>
</div>
</div>
</p>

<p>This is the .ts component 2 src/app/components/my-component2/my-component2.component.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 { Component, OnInit, Input } from '@angular/core';
import { Post} from '../../models/post'
@Component({
  selector: 'app-my-component2',
  templateUrl: './my-component2.component.html',
  styleUrls: ['./my-component2.component.css']
})
export class MyComponent2Component implements OnInit {

  @Input() messagge1: Post[];
  constructor() { }

  ngOnInit() {
    console.log(""from component2"")
    console.log(this.messagge1);
  }

}</code></pre>
</div>
</div>
</p>

<p>This is the html component2 src/app/my-component1/my-component1.component.html:</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;p&gt;
  my-component2 works!
&lt;/p&gt;</code></pre>
</div>
</div>
</p>

<p>This is the model returning by the service, src/app/models/post.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 interface Post {
	
	id: number;
	userId: string;
	body: string;
	
}</code></pre>
</div>
</div>
</p>

<p>This is the service, src/app/service/my-service1.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-js lang-js prettyprint-override""><code>import { Injectable } from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {Post} from '../models/post';

@Injectable()
export class MyService1Service {

  constructor(public http: HttpClient) { }

  test(){
    console.log(""test"");
  }

  getPost(){
		return this.http.get&lt;Post[]&gt;(`http://jsonplaceholder.typicode.com/posts`);
	}
}</code></pre>
</div>
</div>
</p>

<p>Can someone help me know why I receive the error and check if I am correctly implementing the snorkpete answer?</p>

<p>Thanks very much.</p>
",https://stackoverflow.com/questions/49481959/unit-test-with-angular-5-i-am-trying-mock-a-service-but-i-receive-object-er,"['angular', 'karma-jasmine']",881,TRUE,0,1
React - how to write logic/service class that will be accessed inside of smart component,"<p>I am coming from Angular, where I used dependency injection, but how to decouple here in React, that would be suitable easily for unit testing later? I feel like having instances with new() is huge anti pattern, because it introduces coupling, but on other side static methods can be tested?</p>

<p>I am using smart-dumb component pattern. I also want to separate huge logic classes from smart component into own classes(aka services).</p>

<p>Which one is correct way to create those classes which then will be called inside of smart component?</p>

<p>Option 1:</p>

<pre><code>export default class AuthValidation {

    // id_token C7: The current time MUST be before the time represented by the exp Claim (possibly allowing for some small leeway to account for clock skew).
    public IsTokenExpired(token: string, offsetSeconds?: number): boolean {

        let decoded: any;
        decoded = this.GetPayloadFromToken(token, false);

        let tokenExpirationDate = this.getTokenExpirationDate(decoded);
        offsetSeconds = offsetSeconds || 0;

        if (tokenExpirationDate == null) {
            return false;
        }

        // Token expired?
        return !(tokenExpirationDate.valueOf() &gt; (new Date().valueOf() + (offsetSeconds * 1000)));
    }
}
</code></pre>

<p>then access inside of smart component like:</p>

<pre><code>AuthValidation auth = new AuthValidation();
</code></pre>

<p>or Option 2:</p>

<pre><code>export class AuthValidation {
    // id_token C7: The current time MUST be before the time represented by the exp Claim (possibly allowing for some small leeway to account for clock skew).
    static IsTokenExpired(token: string, offsetSeconds?: number): boolean {

        let decoded: any;
        decoded = this.GetPayloadFromToken(token, false);

        let tokenExpirationDate = this.getTokenExpirationDate(decoded);
        offsetSeconds = offsetSeconds || 0;

        if (tokenExpirationDate == null) {
            return false;
        }

        // Token expired?
        return !(tokenExpirationDate.valueOf() &gt; (new Date().valueOf() + (offsetSeconds * 1000)));
    }
}
</code></pre>

<p>Access inside of component:</p>

<pre><code>AuthValidation.IsTokenExpired(...);
</code></pre>

<p>I have 10 methods inside of authentication, and I don't want to put it in smart component container, it looks too crowded, or is that the only way?</p>
",https://stackoverflow.com/questions/50805735/react-how-to-write-logic-service-class-that-will-be-accessed-inside-of-smart-c,"['reactjs', 'typescript']",274,FALSE,0,1
Make multiple connections to same H2 In memory Database,"<p>I have the same problem on a regular basis: I want to perform unit testing on my DAO using an in-memory database. I am using H2, but I believe the problem is pretty much the same with HSQLDB. My unit test involves three steps:</p>

<ul>
<li>create database and setup database schema (using SQL script for instance)</li>
<li>insert required data for the test in the database (ex: with DbUnit)</li>
<li>perform actual testing</li>
</ul>

<p>In very simple situations, it is possible to use the very same connection for all three steps, but as soon as things get a little more complicated (for instance when using a framework for querying the database rather than using direct PreparedStatements), one connection per step is required.</p>

<p>Problem: the database seems to be dropped as soon as the connection is closed. How to solve it?</p>
",https://stackoverflow.com/questions/49921752/make-multiple-connections-to-same-h2-in-memory-database,"['java', 'unit-testing', 'jdbc', 'h2']",4005,TRUE,4,1
Profile unit test in Visual Studio 2017 + NUnit + Resharper,"<p>I have a C# project in Visual Studio 2017 Professional.  It has some unit tests: methods declared with <code>[Test]</code> which display a little green tick icon in the editor, where I can right-click and 'Run' or 'Debug' the test.  When I do so, a window opens with all tests in the solution and I can click a green 'play' triangle to run them all.</p>

<p>I can also run my program under the profiler starting from Debug -> Performance Profiler.</p>

<p>So far so good.  Now, how do I run a unit test under the profiler?</p>

<p>When I first asked this question I looked for profiling unit tests and saw it was a feature in Visual Studio Professional.  But in fact, I'm not using VS's own unit testing support, but rather NUnit, driven by Resharper.  Sorry to throw everyone off the scent.</p>
",https://stackoverflow.com/questions/50864590/profile-unit-test-in-visual-studio-2017-nunit-resharper,"['c#', 'unit-testing', 'visual-studio-2017', 'resharper', 'profile']",3529,TRUE,4,3
How to run Django units test with default and unmanaged database?,"<p>I have a Django project with a default database used for storing things like user, orders etc.</p>

<p>We also have an unmanaged database. Now when you run Django test they try to make test databases, but since we have an unmanaged db we cannot do this. I cannot create migrations of this db since that will land 300 errors about clashing reverse accessor.</p>

<p>We use Docker and automatically spin up this unmanaged database and fill it with some mock data. This one is used for development and such. I would like the unit test to use this one for testing.</p>

<p>I tried things like creating migrations but since the reverse accessor issue this is not possible.</p>

<p>Is there a way to use the unmanaged database for unit testing? The test_default database which Django creates is fine, but I cannot create a test_unmanaged database.</p>
",https://stackoverflow.com/questions/53887725/how-to-run-django-units-test-with-default-and-unmanaged-database,"['python', 'django', 'django-unittest']",737,TRUE,3,1
Failed: Uncaught (in promise): Error: Cannot match any routes. URL Segment: &#39;login&#39;. Jasmine &amp; Angular 6,"<p>Community I just starting to play with unit testing and I have set up an Angular 6 project with Jasmine &amp; karma for unit testings.</p>

<p>for some weird reason, I get this error when i <strong>RUN</strong> <code>ng test</code> 
Jasmine opens new browser window on <code>http://localhost:9876/?id=34428211</code></p>

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

<pre><code>Failed: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'login'
Error: Cannot match any routes. URL Segment: 'login'
</code></pre>

<p>I am on the <strong>grid-page.component.ts</strong> where I don't have any route that redirects to <strong>login page</strong> expect the authentication service that checks if the user is logged in and if the user token has expired and only then I redirect to the login page. 
That's the only possible solution I can find can someone explain to me what I can do solve this.</p>

<p>One more thing I want to ask you guys is if I need to make any test for the <strong>app-routing.module.ts</strong> because I don't test any routes.</p>

<h3>grid-page.component.spec.ts</h3>

<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { NotificationsComponent } from '../../../components/ui/notifications/notifications.component';
import { MaterialModule } from '@app-modules/material.module.ts';
import { SidenavComponent } from '../../../components/ui/sidenav/sidenav.component';
import { HeaderComponent } from '../../../components/ui/header/header.component';
import { PlotToolbarComponent } from '../../../components/ui/plot-toolbar/plot-toolbar.component';
import { GridFiltersComponent } from '../../../pages/analytics/grid-page/components/grid-filters/grid-filters.component';
import { LoaderComponent } from '../../../components/loaders/loader/loader.component';
import { CalendarGridPlotComponent } from '../../../pages/analytics/grid-page/components/calendar-grid-plot/calendar-grid-plot.component';
import { RouterTestingModule } from '@angular/router/testing';
import { DropDownMenuComponent } from '../../../components/form_controls/drop-down-menu/drop-down-menu.component';
import { ReactiveFormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { GridPageComponent } from './grid-page.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HttpClientModule  } from '@angular/common/http';

describe('GridPageComponent', () =&gt; {
  let component: GridPageComponent;
  let fixture: ComponentFixture&lt;GridPageComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [ MaterialModule, RouterTestingModule, ReactiveFormsModule, HttpModule, BrowserAnimationsModule, HttpClientModule ],
      declarations: [
        GridPageComponent, NotificationsComponent, SidenavComponent,
        HeaderComponent, PlotToolbarComponent, GridFiltersComponent,
        LoaderComponent, CalendarGridPlotComponent, DropDownMenuComponent
      ]
    })
    .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(GridPageComponent);
    component = fixture.componentInstance;
    // fixture.detectChanges();
  });

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });

  // ===========================================================================
  // Variable specs
  // ===========================================================================

  fit('should spinnerLoader variable to be true', () =&gt; {
    expect(component.spinnerLoader).toBeTruthy();
  });

  fit('should barLoader variable to be true', () =&gt; {
    expect(component.barLoader).toBeTruthy();
  });

  fit('should isDarkTheme variable to be true', () =&gt; {
    expect(component.isDarkTheme).toBeFalsy();
  });

  fit('should sideNavState variable to be close', () =&gt; {
    expect(component.sideNavState).toBe('close');
  });

  fit('should form variable to be undefined', () =&gt; {
    expect(component.form).toBeUndefined();
  });


});
</code></pre>

<h3>app-routing.module.ts</h3>

<pre><code>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { AuthGuard } from './guards/auth.guard';


// PAGES

// STATUS PAGES
import { LoginComponent } from './pages/login/login.component';
import { Page404Component } from './pages/status/page404/page404.component';

import { DashboardComponent } from './pages/dashboard/dashboard.component';
import { InventoryComponent } from './pages/inventory/inventory.component';

import { LocationAnalyticsComponent } from './pages/analytics/location-analytics/location-analytics.component';
import { TimelinePageComponent } from './pages/analytics/timeline-page/timeline-page.component';
import { GridPageComponent } from './pages/analytics/grid-page/grid-page.component';
import { StoreSelectionPageComponent } from './pages/store-selection-page/store-selection-page.component';


import { SettingsComponent } from './pages/settings/settings.component';


export const routes: Routes = [

  { path: '',                     redirectTo: 'dashboard', pathMatch: 'full', canActivate: [AuthGuard] },
  { path: 'dashboard',            component: DashboardComponent, canActivate: [AuthGuard] },
  { path: 'login',                component: LoginComponent },

  { path: 'store-selection',      component: StoreSelectionPageComponent, canActivate: [AuthGuard] },
  { path: 'inventory',            component: InventoryComponent, canActivate: [AuthGuard] },

  { path: 'analytics/timeline',   component: TimelinePageComponent, canActivate: [AuthGuard] },
  { path: 'analytics/grid',       component: GridPageComponent, canActivate: [AuthGuard] },
  { path: 'analytics/location',   component: LocationAnalyticsComponent, canActivate: [AuthGuard] },

  { path: 'settings',             component: SettingsComponent, canActivate: [AuthGuard] },

  { path: '**',                   component: Page404Component }

];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
</code></pre>
",https://stackoverflow.com/questions/52419155/failed-uncaught-in-promise-error-cannot-match-any-routes-url-segment-log,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",1648,TRUE,3,1
How to implement Azure table storage to allow for Unit Tests,"<p>I am implementing unit tests for a Azure Table Storage based persistence component. The project has multiple Table Storage persistence components, so currently these implement an abstract <code>TableStorageBase</code> class to share common code between them.</p>

<p>Say we have a class <code>FooTableStorageComponent</code> under test, that retrieves a <code>Foo</code> from Table Storage, and if it has expired (i.e. the timestamp is older than 7 days), it creates a new <code>Foo</code>. I would like to create a Table Storage stub that always gives <code>FooTableStorageComponent</code> a dummy <code>Foo</code> older than 7 days. I would then like to create a unit test that checks that a new <code>Foo</code> is hence created. Unfortunately, due to the abstract <code>TableStorageBase</code> class, I can't fake connecting to Azure. </p>

<p><strong>How can I redesign this structure to make it unit testable? How should I go about unit testing my <code>FooTableStorageComponent</code>?</strong></p>

<p><strong>Abstract TableStorageBase class:</strong></p>

<pre><code>public abstract class TableStorageBase
{
    private readonly string tableName;
    protected readonly CloudStorageAccount storageAccount;
    protected TableRequestOptions DefaultTableRequestOptions { get; }
    protected OperationContext DefaultOperationContext { get; }
    public CloudTable Table
    {
        get
        {
            return storageAccount.CreateCloudTableClient().GetTableReference(tableName);
        }
    }

    public TableStorageBase(
        string connectionString,
        string tableName,
        LocationMode consistency)
    {
        this.tableName = tableName;
        storageAccount = CloudStorageAccount.Parse(connectionString);
        ServicePoint tableServicePoint = 
            ServicePointManager.FindServicePoint(storageAccount.TableEndpoint);
        tableServicePoint.UseNagleAlgorithm = false;
        tableServicePoint.ConnectionLimit = 500;
        DefaultTableRequestOptions = new TableRequestOptions()
        {
            PayloadFormat = TablePayloadFormat.JsonNoMetadata,
            MaximumExecutionTime = TimeSpan.FromSeconds(5),
            RetryPolicy = new LinearRetry(TimeSpan.FromMilliseconds(500), 3),
            LocationMode = consistency
        };

        DefaultOperationContext = new OperationContext();
        Table.CreateIfNotExists(DefaultTableRequestOptions, DefaultOperationContext);
    }
}
</code></pre>

<p><strong>Class under test:</strong></p>

<pre><code>public class FooTableStorageComponent : TableStorageBase, IFooComponent
{
    private const string TableName = ""foo"";
    private const LocationMode ConsistencyMode = LocationMode.PrimaryOnly;

    public FooTableStorageComponent(string connectionString)
         : base(connectionString, TableName, ConsistencyMode)
    {
    }

    public GetFoo(string partitionKey, string rowKey)
    {
        var retrieveOperation = TableOperation.Retrieve&lt;FooTableEntity&gt;(partitionKey, rowkey)
        var tableEntity = (await Table.ExecuteAsync(
            retrieveOperation, 
            DefaultTableRequestOptions, 
            DefaultOperationContext)).Result as FooTableEntity;
        if (tableEntity != null &amp;&amp; tableEntity.Timestamp &gt; DateTime.Now.AddDays(-7))
        {
            return tableEntity.ToEntity();
        }
        else
        {
            var foo = CreateFoo(partitionKey, rowKey)
            var insertOperation = TableOperation.InsertOrMerge(FooTableEntity.From(foo));
            await Table.ExecuteAsync(insertOperation);
            return foo;
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/48763607/how-to-implement-azure-table-storage-to-allow-for-unit-tests,"['c#', 'unit-testing', 'azure', 'mocking', 'azure-table-storage']",1834,TRUE,2,1
"Spark : Scala mocking, Task not serializable","<p>I am trying to use mockito for unit testing some scala code. I want to run spark locally, i.e. in my IntelliJ IDE. Here is a sample</p>

<pre><code>class MyScalaSparkTests extends FunSuite with BeforeAndAfter with MockitoSugar with java.io.Serializable{

  val configuration:SparkConf  = new SparkConf()
    .setAppName(""Your Application Name"")
    .setMaster(""local"");
  val sc = new SparkContext(configuration);
  lazy val testSess = SparkSession.builder.appName(""local_test"").getOrCreate()
  test (""test service"") {
    import testSess.implicits._
    // (1) init
    val testObject = spy(new MyScalaClass(&lt;some args&gt;))
    val testDf = testSess.emptyDataset[MyCaseClass1].toDF()
    testDf.union(Seq(MyCaseClass(&lt;some args&gt;)).toDF())
    testObject.testDataFrame = testDf
    val testSource = testSess.emptyDataset[MyCaseClass2].toDF()
    testSource.union(Seq(MyCaseClass2(&lt;some args&gt;)).toDF())
    testObject.setSourceDf(testSource)
    val testRes = testObject.someMethod()

    val r = testRes.take(1)
    println(r)

  }

}
</code></pre>

<p>so basically, here is what I am trying to do</p>

<p><code>MyScalaClass</code> has <code>someMethod()</code> which compares data between two data frames called <code>testDataFrame</code> and <code>testSource</code>. It then returns another data frame which has the results. Now, in my unit test, I am spying on <code>MyScalaClass</code> to create <code>testObject</code>. Then I create <code>testDataFrame</code> and <code>testSource</code> and assign them to <code>testObject</code>. Finally, I call <code>testObject.someMethod()</code>.</p>

<p>Now in the debugger, at this line</p>

<pre><code>val r = testRes.take(1)
</code></pre>

<p>I see that <code>testRes</code> is a <code>Dataset</code> hence something is being returned by the method. But when I try to <code>take</code> something from it in order to verify the results I get</p>

<pre><code>Task not serializable
org.apache.spark.SparkException: Task not serializable
</code></pre>

<p>and further down the stacktrace</p>

<pre><code>Caused by: java.io.NotSerializableException: org.mockito.internal.creation.DelegatingMethod
Serialization stack:
    - object not serializable (class: org.mockito.internal.creation.DelegatingMethod, value: org.mockito.internal.creation.DelegatingMethod@a97f2bff)
    - field (class: org.mockito.internal.invocation.InterceptedInvocation, name: mockitoMethod, type: interface org.mockito.internal.invocation.MockitoMethod)
    - object (class org.mockito.internal.invocation.InterceptedInvocation, bSV2PartValidator.toString();)
    - field (class: org.mockito.internal.invocation.InvocationMatcher, name: invocation, type: interface org.mockito.invocation.Invocation)
    - object (class org.mockito.internal.invocation.InvocationMatcher, bSV2PartValidator.toString();)
    - field (class: org.mockito.internal.stubbing.InvocationContainerImpl, name: invocationForStubbing, type: interface org.mockito.invocation.MatchableInvocation)
    - object (class org.mockito.internal.stubbing.InvocationContainerImpl, invocationForStubbing: bSV2PartValidator.toString();)
    - field (class: org.mockito.internal.handler.MockHandlerImpl, name: invocationContainer, type: class org.mockito.internal.stubbing.InvocationContainerImpl)
    - object (class org.mockito.internal.handler.MockHandlerImpl, org.mockito.internal.handler.MockHandlerImpl@47c019d7)
    - field (class: org.mockito.internal.handler.NullResultGuardian, name: delegate, type: interface org.mockito.invocation.MockHandler)
    - object (class org.mockito.internal.handler.NullResultGuardian, org.mockito.internal.handler.NullResultGuardian@7222e168)
    - field (class: org.mockito.internal.handler.InvocationNotifierHandler, name: mockHandler, type: interface org.mockito.invocation.MockHandler)
    - object (class org.mockito.internal.handler.InvocationNotifierHandler, org.mockito.internal.handler.InvocationNotifierHandler@1e4f8430)
    - field (class: org.mockito.internal.creation.bytebuddy.MockMethodInterceptor, name: handler, type: interface org.mockito.invocation.MockHandler)
    - object (class org.mockito.internal.creation.bytebuddy.MockMethodInterceptor, org.mockito.internal.creation.bytebuddy.MockMethodInterceptor@34d08905)
    - field (class: com.walmart.labs.search.signals.validators.BSV2PartValidator$MockitoMock$213785213, name: mockitoInterceptor, type: class org.mockito.internal.creation.bytebuddy.MockMethodInterceptor)
    - object (class com.walmart.labs.search.signals.validators.BSV2PartValidator$MockitoMock$213785213, com.walmart.labs.search.signals.validators.BSV2PartValidator$MockitoMock$213785213@7f289126)
    - field (class: com.walmart.labs.search.signals.validators.BSV2PartValidator$$anonfun$1, name: $outer, type: class com.walmart.labs.search.signals.validators.BSV2PartValidator)
    - object (class com.walmart.labs.search.signals.validators.BSV2PartValidator$$anonfun$1, &lt;function1&gt;)
    - element of array (index: 1)
    - array (class [Ljava.lang.Object;, size 7)
    - field (class: org.apache.spark.sql.execution.WholeStageCodegenExec$$anonfun$8, name: references$1, type: class [Ljava.lang.Object;)
    - object (class org.apache.spark.sql.execution.WholeStageCodegenExec$$anonfun$8, &lt;function2&gt;)
    at org.apache.spark.serializer.SerializationDebugger$.improveException(SerializationDebugger.scala:40)
    at org.apache.spark.serializer.JavaSerializationStream.writeObject(JavaSerializer.scala:46)
    at org.apache.spark.serializer.JavaSerializerInstance.serialize(JavaSerializer.scala:100)
    at org.apache.spark.util.ClosureCleaner$.ensureSerializable(ClosureCleaner.scala:295)
    ... 78 more
</code></pre>

<p>What am i doing wrong? Is it even possible to spy on or mock spark behavior in IDE?</p>
",https://stackoverflow.com/questions/53820877/spark-scala-mocking-task-not-serializable,"['scala', 'apache-spark', 'intellij-idea', 'mockito', 'spy']",3803,TRUE,2,1
How to unit test against gen_server callbacks?,"<p>I have a case where a process starts, sends itself a message in the <code>init</code> block, and has a side effect elsewhere of dynamically creating some processes. I want to unit test this, but there is no way to determine exactly when the activities will be complete to make assertions against the mocks. Eg it's <em>eventually</em> invoked after starting the process. In scala, scalatest has mechanisms to test items like this but I'm thinking that unit testing against the callback would be sufficient.</p>

<p>Is it considered improper to unit test again GenServer callbacks directly (<code>handle_info</code>, <code>handle_call</code> and <code>handle_cast</code>)?
I can understand that there may be value in the test in starting the process, but that's more of an integration test.
Would it be okay to invoke eg <code>handle_info/2</code> in a unit test on a Module instead of starting a process and checking for effects?</p>
",https://stackoverflow.com/questions/49323979/how-to-unit-test-against-gen-server-callbacks,"['unit-testing', 'elixir', 'erlang-otp', 'gen-server']",342,FALSE,2,0
Chutzpah unable to find imported angular library module,"<p>I recently brought this angular library to my project:</p>

<p><a href=""https://github.com/a5hik/angular-multi-select-tree"" rel=""nofollow noreferrer"">https://github.com/a5hik/angular-multi-select-tree</a></p>

<p>Everything works great with it besides my unit testing.  I am getting this error when running my tests:</p>

<pre><code>Module 'multi-select-tree' 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>Which puzzles me as I have added it to my chutzpah.json references (and confirmed the paths are correct many times) like so:</p>

<pre><code>{ ""Path"": ""../Scripts/Lib/ng-multi-select-tree/ng-multi-select-tree.js"" },
{ ""Path"": ""../Scripts/Lib/ng-multi-select-tree/ng-multi-select-tree.tpl.js"" },
</code></pre>

<p>And have included it in my main app.js file.  The commented out code allows for Chutzpah to find the library, however this breaks all functionality of it:</p>

<pre><code>// work around for Chutzpah test discovery
//angular.module('multi-select-tree', []);
var authoring = angular.module('authoring', ['ms-content', 'portalCommon', 'ngFileUpload', 'ckeditor', 'ui.bootstrap', 'AdalAngular', 'ui.sortable', 'nvd3', 'multi-select-tree']).run(['$rootScope', function ($rootScope) {}]);
</code></pre>

<p>The thing I am noticing is how this library instantiates the module like so:</p>

<pre><code>(function () {
    'use strict';
    var mainModule = angular.module('multi-select-tree');
</code></pre>

<p>They seem to instantiate the module and then set it to a variable.  Coworkers of mine are implying that this may be the problem.  Any ideas as to why Chutzpah is having a hard time finding this particular module?</p>
",https://stackoverflow.com/questions/48412833/chutzpah-unable-to-find-imported-angular-library-module,"['javascript', 'angularjs', 'chutzpah']",74,TRUE,2,1
Stubbing with sinon.stub in meteor.js using local modules,"<p>I am having trouble doing some basic stubbing with sinon, for unit testing. When the stubbed method is eventually called, it is calling the real method rather than the stubbed version. </p>

<p>I have created a simple version of this to illustrate the problem I'm dealing with. I am running meteor 1.6.1 and using the <code>meteortesting</code> package using the command <code>meteor test --once --driver-package meteortesting:mocha</code>, the following files are all inside the <code>/server</code> directory. I use <code>module.exports</code> instead of export on the module thats being stubbed because an error is thrown otherwise (a seperate bug, <code>import * as foo from './file'</code> should work).</p>

<p>Interestingly, the stub works correctly if I export in <code>calc-module.js</code> using export default, the problem is that I am working in a large production app, and I'd like to avoid using export default throughout just for stubbing purposes.</p>

<p>I have tried almost identical code in node 8, and it works fine. </p>

<pre><code>//calc-module.test.js
import { expect } from 'chai';
import { runAdd5 } from './wrappers';
import calcModule from  './calc-module';
import sinon from 'sinon';

describe('calcModule', () =&gt; {
    before(() =&gt; {
        sinon.stub(calcModule, 'add5').callsFake((number) =&gt; {
            return number
        });
    });
    it('stubbed add5 causes function to not add anything', () =&gt; {
        const result = runAdd5(0)
        expect(result).to.eql(0)
    });
});


//calc-module.js
const add5 = (number) =&gt; {
    return number + 5
}

module.exports = {
    add5
}

//wrappers.js
import { add5 } from './calc-module';

const runAdd5 = (number) =&gt; {
    return add5(number)
};

export {
    runAdd5
};
</code></pre>
",https://stackoverflow.com/questions/49888989/stubbing-with-sinon-stub-in-meteor-js-using-local-modules,"['node.js', 'meteor', 'sinon', 'stub']",352,FALSE,2,0
How to unit test a ViewModel that extends AndroidViewModel. Having issues with the application in the constructor,"<p>So I'm having to write unit tests and I need to test my ViewModels. </p>

<p>I have a base ViewModel and that BaseViewModel extends AndroidViewModel. The reason I extend AndroidViewModel is so that I can use the context for Dagger. </p>

<p>My BaseViewModel. </p>

<pre><code>public class BaseViewModel extends AndroidViewModel {

protected @Inject SharedPreferencesHelper sharedPreferencesHelper;

public BaseViewModel(@NonNull Application application) {
    super(application);

    //Only inject sharedPreferences since it is used in almost all of the VMs.
    ((CommissioningApplication) getApplication()).getAppComponent().inject(this);
}
</code></pre>

<p>}</p>

<p>Essentially I'm having issues creating an instance of my ViewModel in my unit tests. I have tried many things and have been unsuccessful. </p>

<p>I have considered extending ViewModel instead of AndroidViewModel and creating a Factory that will pass the application context to my ViewModels. But in the end I will run towards the same issue whenever I try to create an instance of my ViewModel. </p>

<p>Does anyone have an example that I could follow on how to test this? Or would have I have to do Instrumented testing instead of Unit testing? </p>

<p>I'm very new to testing so maybe I'm not doing things properly, any help would be great. </p>

<p>Thanks</p>
",https://stackoverflow.com/questions/51365453/how-to-unit-test-a-viewmodel-that-extends-androidviewmodel-having-issues-with-t,"['android', 'unit-testing', 'testing', 'mvvm', 'viewmodel']",1508,TRUE,5,1
Mocking the Internal Clock of Asyncio Event Loop,"<p>We are using <code>asyncio.get_event_loop()</code> as a scheduler in a real-time message driven environment.</p>

<p>For (back)testing purposes we replay the time-stamped messages and regard their time-stamp as the simulated/synthetic/mock time.
This only works if we replace the internal clock of the event loop. How can we do this?</p>

<p>Note that Python 3.6.6, BaseEventLoop implements</p>

<pre><code>def time(self):
    return time.monotonic()
</code></pre>

<p>and we'd like to have</p>

<pre><code>def time(self):
    return current_message.timestamp
</code></pre>

<p>Possible solutions, all flawed:</p>

<ol>
<li>Subclass AbstractEventLoop? -> Not really, as AbstractEventLoop is pretty naked.</li>
<li>Subclass BaseEventLoop? -> Docs state: It should not be used directly; use AbstractEventLoop instead.</li>
<li>Monkey patch asyncio.get_event_loop().time()? -> May work, but may break anytime.</li>
<li>Monkey patch time.monotonic()? Worse than (3).</li>
<li>Try to understand asyncio.test_utils.TestLoop? -> Internal, not documented.</li>
<li>Kick asyncio altogether?</li>
</ol>

<p>Related: <a href=""https://stackoverflow.com/questions/33940518/unit-testing-a-periodic-coroutine-with-mock-time"">Unit-testing a periodic coroutine with mock time</a></p>

<p>Note: <code>sched.scheduler()</code> can be injected with a synthetic time (!), but it does blocking sleeps.</p>
",https://stackoverflow.com/questions/53829383/mocking-the-internal-clock-of-asyncio-event-loop,"['python-3.x', 'python-asyncio']",690,TRUE,1,2
Updating make file to link dependency files,"<p>I am using the Unity C unit testing framework (<a href=""http://www.throwtheswitch.org/unity"" rel=""nofollow noreferrer"">http://www.throwtheswitch.org/unity</a>). I am using the sample makefile that they provide (<a href=""http://www.throwtheswitch.org/build/make"" rel=""nofollow noreferrer"">http://www.throwtheswitch.org/build/make</a>). </p>

<p>My question is how do I declare dependencies in this makefile.  </p>

<p>For example: I have a file a.c and it has the header b.h. I have a file b.c and it has the header b.h. b.c implements the function foo(). a.c uses the function foo(). How do I setup linking like this using the makefile below: </p>

<pre><code>CLEANUP = rm -f
MKDIR = mkdir -p
TARGET_EXTENSION=out

.PHONY: clean
.PHONY: test

PATHU = unity/
PATHS = src/
PATHT = test/
PATHB = build/
PATHD = build/depends/
PATHO = build/objs/
PATHR = build/results/

BUILD_PATHS = $(PATHB) $(PATHD) $(PATHO) $(PATHR)

SRCT = $(wildcard $(PATHT)*.c)

COMPILE=gcc -c
LINK=gcc
DEPEND=gcc -MM -MG -MF
CFLAGS=-I. -I$(PATHU) -I$(PATHS) -DTEST

RESULTS = $(patsubst $(PATHT)Test%.c,$(PATHR)Test%.txt,$(SRCT) )

PASSED = `grep -s PASS $(PATHR)*.txt`
FAIL = `grep -s FAIL $(PATHR)*.txt`
IGNORE = `grep -s IGNORE $(PATHR)*.txt`

test: $(BUILD_PATHS) $(RESULTS)
    @echo ""-----------------------\nIGNORES:\n-----------------------""
    @echo ""$(IGNORE)""
    @echo ""-----------------------\nFAILURES:\n-----------------------""
    @echo ""$(FAIL)""
    @echo ""-----------------------\nPASSED:\n-----------------------""
    @echo ""$(PASSED)""
    @echo ""\nDONE""

$(PATHR)%.txt: $(PATHB)%.$(TARGET_EXTENSION)
    -./$&lt; &gt; $@ 2&gt;&amp;1

$(PATHB)Test%.$(TARGET_EXTENSION): $(PATHO)Test%.o $(PATHO)%.o $(PATHU)unity.o #$(PATHD)Test%.d
    $(LINK) -o $@ $^

$(PATHO)%.o:: $(PATHT)%.c
    $(COMPILE) $(CFLAGS) $&lt; -o $@

$(PATHO)%.o:: $(PATHS)%.c
    $(COMPILE) $(CFLAGS) $&lt; -o $@

$(PATHO)%.o:: $(PATHU)%.c $(PATHU)%.h
    $(COMPILE) $(CFLAGS) $&lt; -o $@

$(PATHD)%.d:: $(PATHT)%.c
    $(DEPEND) $@ $&lt;

$(PATHB):
    $(MKDIR) $(PATHB)

$(PATHD):
    $(MKDIR) $(PATHD)

$(PATHO):
    $(MKDIR) $(PATHO)

$(PATHR):
    $(MKDIR) $(PATHR)

clean:
    $(CLEANUP) $(PATHO)*.o
    $(CLEANUP) $(PATHB)*.$(TARGET_EXTENSION)
    $(CLEANUP) $(PATHR)*.txt

.PRECIOUS: $(PATHB)Test%.$(TARGET_EXTENSION)
.PRECIOUS: $(PATHD)%.d
.PRECIOUS: $(PATHO)%.o
.PRECIOUS: $(PATHR)%.txt
</code></pre>

<p>So, far my project directory is setup with </p>

<ul>
<li>src/node.c</li>
<li>src/node.h</li>
<li>src/lca.c</li>
<li>lca.c uses a function newNode defined in node.h (which is implemented in node.c)</li>
<li>test/Testlca.c is the test function which Unity tests lca.c with</li>
</ul>

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

<pre><code>cc -I. -Iunity/ -Isrc/ -DTEST   -c -o unity/unity.o unity/unity.c
gcc -o build/Testlca.out build/objs/Testlca.o build/objs/lca.o unity/unity.o
Undefined symbols for architecture x86_64:
  ""_newNode"", referenced from:
      _test_newNode_should_nodePointer in Testlca.o
     (maybe you meant: _test_newNode_should_nodePointer)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see     invocation)
make: *** [build/Testlca.out] Error 1
</code></pre>

<p>I believe this is due to errors in the makefile and that I have to tweak the makefile.</p>
",https://stackoverflow.com/questions/52595518/updating-make-file-to-link-dependency-files,"['c', 'makefile', 'linker', 'dependencies', 'unity-test-framework']",685,TRUE,1,1
Can I use an environment other than &#39;test&#39; for Ember tests?,"<p>I have Ember.js 2.16 acceptance tests written using the Ember template test libraries (QUnit and testem) that test the general functionality of an Ember app. When I run <code>ember test</code>, the 'environment' for which environment variables are retrieved is always set to <code>test</code>.</p>

<p>Is there a way to run <code>ember test</code> with any environment other than <code>test</code>? Running it with <code>--environment=""my_other_test_env""</code> doesn't change the environment as it would for <code>ember build</code> or <code>ember serve</code>. </p>

<p>I’d like to be able to pass parameters to acceptance tests depending on what environment they are running in. Is this behavior supported, and if not, is there a reason I shouldn't be doing this? I understand that for lower-level unit testing, I shouldn't be dealing with external dependencies, but for end-to-end acceptance testing, it seems normal that there would be different environments I would want to run the tests in.</p>
",https://stackoverflow.com/questions/51954680/can-i-use-an-environment-other-than-test-for-ember-tests,['ember.js'],513,TRUE,1,1
Karma Unit Test Cordova native Keyboard plugin HTML Doc not defined,"<p>When running Unit Tests with Karma I get following error:</p>

<pre><code>TypeError: Cannot read property '__zone_symbol__addEventListener' of undefined
        at Platform.registerListener Users/berfuc/workspace/paysafecash-app/node_modules/ionic-angular/es2015/platform/platform.js:573:1)
        at Keyboard.focusOutline Users/berfuc/workspace/paysafecash-app/node_modules/ionic-angular/es2015/platform/keyboard.js:223:1)
        at new Keyboard Users/berfuc/workspace/paysafecash-app/node_modules/ionic-angular/es2015/platform/keyboard.js:32:1)
        at _createClass Users/berfuc/workspace/paysafecash-app/node_modules/@angular/core/esm2015/core.js:8800:1)
        at _createProviderInstance$1 Users/berfuc/workspace/paysafecash-app/node_modules/@angular/core/esm2015/core.js:8764:1)
        at resolveNgModuleDep Users/berfuc/workspace/paysafecash-app/node_modules/@angular/core/esm2015/core.js:8749:1)
        at NgModuleRef_.get Users/berfuc/workspace/paysafecash-app/node_modules/@angular/core/esm2015/core.js:9737:1)
        at resolveDep Users/berfuc/workspace/paysafecash-app/node_modules/@angular/core/esm2015/core.js:10212:1)
        at createClass Users/berfuc/workspace/paysafecash-app/node_modules/@angular/core/esm2015/core.js:10083:1)
        at createDirectiveInstance Users/berfuc/workspace/paysafecash-app/node_modules/@angular/core/esm2015/core.js:9922:24)
    TypeError: Cannot read property 'nativeElement' of undefined
        at UserContext.&lt;anonymous&gt; Users/berfuc/workspace/paysafecash-app/src/pages/storelocator/list/storelocator-list.spec.ts:83:17)
        at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke Users/berfuc/workspace/paysafecash-app/node_modules/zone.js/dist/zone.js:392:1)
        at ProxyZoneSpec.webpackJsonp.../../../../zone.js/dist/proxy.js.ProxyZoneSpec.onInvoke Users/berfuc/workspace/paysafecash-app/node_modules/zone.js/dist/proxy.js:79:1)
        at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invoke Users/berfuc/workspace/paysafecash-app/node_modules/zone.js/dist/zone.js:391:1)
        at Zone.webpackJsonp.../../../../zone.js/dist/zone.js.Zone.run Users/berfuc/workspace/paysafecash-app/node_modules/zone.js/dist/zone.js:142:1)
        at UserContext.&lt;anonymous&gt; Users/berfuc/workspace/paysafecash-app/node_modules/zone.js/dist/jasmine-patch.js:104:1)
        at ZoneQueueRunner.webpackJsonp.../../../../zone.js/dist/jasmine-patch.js.jasmine.QueueRunner.ZoneQueueRunner.execute Users/berfuc/workspace/paysafecash-app/node_modules/zone.js/dist/jasmine-patch.js:132:1)
</code></pre>

<p>my karma.conf.js:</p>

<pre><code>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', '@angular/cli'],

angularCli: {
  environment: 'prod'
},

// plugins to use
plugins: [
  require('@angular/cli/plugins/karma'),
  require('karma-jasmine'),
  require('karma-chrome-launcher'),
  require('karma-junit-reporter'),
  require('karma-coverage')
],

client:{
  clearContext: false // leave Jasmine Spec Runner output visible in browser
},

reporters: ['progress', 'junit', 'coverage'],

junitReporter: {
  outputDir: '',
  outputFile: 'test-results.xml',
  useBrowserName: false
},

// 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: false,


// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['ChromeHeadless'],


// 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>

<p>my tsconfig.json:</p>

<pre><code>{
""compilerOptions"": {
""allowSyntheticDefaultImports"": true,
""declaration"": false,
""emitDecoratorMetadata"": true,
""experimentalDecorators"": true,
""noImplicitAny"": false,
""lib"": [
  ""dom"",
  ""es2017""
],
""module"": ""es2015"",
""moduleResolution"": ""node"",
""sourceMap"": true,
""target"": ""es5"",
""typeRoots"": [
  ""../node_modules/@types""
],
""baseUrl"": ""./src"",
""paths"": {
  ""@app/env"": [
    ""environments/environment""
  ]
}
},
""include"": [
  ""src/**/*.ts""
],
""exclude"": [
  ""node_modules"",
  ""src/**/*.spec.ts"",
  ""src/**/__tests__/*.ts""
],
""compileOnSave"": false,
""atom"": {
  ""rewriteTsconfig"": false
}
}
</code></pre>

<p>my tsconfig.spec.json:</p>

<pre><code>{
  ""extends"": ""../tsconfig.json"",
  ""compilerOptions"": {
    ""outDir"": ""../out-tsc/spec"",
    ""baseUrl"": ""./"",
    ""types"": [
      ""jasmine"",
      ""node""
    ]
  },
  ""files"": [
    ""test.ts""
  ],
  ""include"": [
    ""**/*.spec.ts"",
    ""**/*.d.ts""
  ],
  ""exclude"": [
    ""node_modules""
  ]
}
</code></pre>

<p>We use:</p>

<ul>
<li>Angular 5.0.1</li>
<li>Ionic 4.4.0</li>
<li>Cordova Android 6.3.0</li>
<li>Cordova iOS 4.5.4</li>
<li>Ionic-Plugin-Keyboard 2.2.1</li>
<li>Angular-CLI 1.6.2</li>
<li>Karma 1.7.1</li>
<li>Jasmine 2.8.0</li>
<li>Typescript 2.4.2</li>
</ul>

<p>I try to create a UnitTest with Testbed like shown in this tutorial:
<a href=""https://codecraft.tv/courses/angular/unit-testing/change-detection/"" rel=""nofollow noreferrer"">https://codecraft.tv/courses/angular/unit-testing/change-detection/</a></p>

<p>But it fails with above Stacktrace. If I follow the Exception I find out that this <code>ele['__zone_symbol__addEventListener']</code> call throws it.</p>

<p>The method in <code>.../es2015/platform/platform.js</code> is called by this line <code>platform.registerListener(platform.doc(), 'keydown', keyDown, evOpts)</code> in <code>.../es2015/platform/keyboard.js</code> and the <code>doc()</code> returns a type of <code>HTML</code> seen here <code>doc(): HTMLDocument;</code>.</p>

<p>So maybe there is a problem with initialisation of the HTML but I'm not experienced with such deep framework issues.</p>

<p>I only get this error when running Unit Tests with <code>Testbed</code>. Our tests for pipes and our app build works without a problem.</p>
",https://stackoverflow.com/questions/48064399/karma-unit-test-cordova-native-keyboard-plugin-html-doc-not-defined,"['angular', 'cordova', 'unit-testing', 'ionic-framework', 'karma-runner']",446,FALSE,1,0
Jest + Enzyme: test Redux-form,"<p>My application has a lot of redux-form. I am using Jest and Enzyme for unit testing. However, I fail to test the redux-form. My component is a login form like:</p>



<pre class=""lang-jsx prettyprint-override""><code>import { login } from './actions';
export class LoginForm extends React.Component&lt;any, any&gt; {

  onSubmit(values) {
    this.props.login(values, this.props.redirectUrl);
  }

  render() {
    const { handleSubmit, status, invalid } = this.props;

    return (
      &lt;form onSubmit={handleSubmit(this.onSubmit.bind(this))}&gt;
        &lt;TextField label=""Email"" name=""email""&gt;
        &lt;TextField type=""password"" label=""Password"" name=""password"" autoComplete/&gt;
        &lt;Button submit disabled={invalid} loading={status.loading}&gt;
          OK
        &lt;/Button&gt;
      &lt;/form&gt;
    );
  }
}

const mapStateToProps = (state) =&gt; ({
  status: state.login.status,
});

const mapDispatchToProps = { login };

const form = reduxForm({ form: 'login' })(LoginForm);

export default connect(mapStateToProps, mapDispatchToProps)(form);
</code></pre>

<h2>Mock the store, Import connected component</h2>

<p><code>redux-form</code> uses the store to maintain the form inputs. I then use <code>redux-mock-store</code>:</p>

<pre class=""lang-jsx prettyprint-override""><code>import ConnectedLoginForm from './LoginForm';

const configureStore = require('redux-mock-store');
const store = mockStore({});
const spy = jest.fn(); 

const wrapper = shallow(
  &lt;Provider store={store}&gt;
    &lt;ConnectedLoginForm login={spy}/&gt;
  &lt;/Provider&gt;);

wrapper.simulate('submit');
expect(spy).toBeCalledWith();
</code></pre>

<p>But in this way, the <code>submit</code> is not simulated, my test case failed:</p>

<blockquote>
  <p>Expected mock function to have been called with: []
  But it was not called.</p>
</blockquote>

<h2>Mock the store, Import React component only.</h2>

<p>I tried to create redux form from the testing code:</p>

<pre class=""lang-jsx prettyprint-override""><code>import { Provider } from 'react-redux';
import ConnectedLoginForm, { LoginForm } from './LoginForm';

const props = {
  status: new Status(),
  login: spy,
};
const ConnectedForm = reduxForm({
  form: 'login',
  initialValues: {
    email: 'test@test.com',
    password: '000000',
  },
})(LoginForm);

const wrapper = shallow(
  &lt;Provider store={store}&gt;
    &lt;ConnectedForm {...props}/&gt;
  &lt;/Provider&gt;);

console.log(wrapper.html());

wrapper.simulate('submit');
expect(spy).toBeCalledWith({
  email: 'test@test.com',
  password: '000000',
});
</code></pre>

<p>In this case, i still got error of <code>function not called</code>. If I add <code>console.log(wrapper.html())</code>, I got error:</p>

<blockquote>
  <p>Invariant Violation: Could not find ""store"" in either the context or
  props of ""Connect(ConnectedField)"". Either wrap the root component in
  a , or explicitly pass ""store"" as a prop to
  ""Connect(ConnectedField)"".</p>
</blockquote>

<p>I cannot find documentations on official sites of redux-form or redux or jest/enzyme, or even Google.. Please help, thanks.</p>
",https://stackoverflow.com/questions/49665349/jest-enzyme-test-redux-form,"['react-redux', 'jestjs', 'jsx', 'redux-form', 'enzyme']",15081,TRUE,9,4
Can you access the controller name from within a webapi ExceptionHandler or ExceptionLogger,"<p>I'm using a webapi ExceptionHandler and ExceptionLogger to ensure consistent logging and handling of exceptions at the controller level in my web api projects.</p>

<p>I want to log the controller name in which the exception occurred but I find that the ActionContext and ControllerContext are always null even when the exception is originating in a controller during a request.</p>

<p>The documentation <a href=""https://learn.microsoft.com/en-us/aspnet/web-api/overview/error-handling/web-api-global-error-handling"" rel=""nofollow noreferrer"">Here</a> states (underneath the ExceptionContext class) that </p>

<blockquote>
  <p>When the framework calls an exception logger or an exception handler, it will always provide an Exception and a Request. Except for unit testing, it will also always provide a RequestContext. It will rarely provide a ControllerContext and ActionContext (only when calling from the catch block for exception filters). </p>
</blockquote>

<p>Is there an alternate way of being able to log the Controller Class Name from within the Handler / Logger?</p>
",https://stackoverflow.com/questions/50986048/can-you-access-the-controller-name-from-within-a-webapi-exceptionhandler-or-exce,"['c#', 'exception', 'asp.net-web-api2']",193,FALSE,0,1
Is this Command Handler testable?,"<p>I made some progress in understanding unit testing, but with every method I try to test, there are new questions:</p>

<pre><code>public function handle( SendNotification $command ) {

    $DTO = $this-&gt;Assembler-&gt;build();

    $subject = sprintf(
        $command-&gt;getFirstName(),
        $command-&gt;getLastName()
    );

    $EmailComponents = new EmailComponents(
        $subject,
        $DTO-&gt;getProject()-&gt;getSettings()-&gt;getValueOf( 'recipient' ),
        $this-&gt;OptionQuery-&gt;getOption( 'business_email' ),
        $this-&gt;NotificationRenderFactory-&gt;render( 'template' ) )
    );

    $this-&gt;Mailer-&gt;send( $EmailComponents );

}
</code></pre>

<p>The <code>$DTO</code> is basically an aggregate cluster with 'project' being the aggregate root. It reads data from a PHP Session to determine the current project, and the <code>OptionQuery</code> reads data from a database. So my current understanding is that I would have to create a fixture that sets up both an aggreate, a testing database and a mock that returns something for my session object. Is that correct and if so, why would I want to put that much effort into testing a single method?</p>

<p><strong>EDIT</strong> I the meantime, I refactored the <code>handle</code> method to make it more testable:</p>

<pre><code>public function handle( SendNotification $command ) {

    $EmailComponents = $this-&gt;EmailComponentsAssembler-&gt;build( $command );

    $this-&gt;Mailer-&gt;setup( $EmailComponents );

    $this-&gt;Mailer-&gt;send();

}
</code></pre>

<p>The <code>build</code> method of the assembler (which is more of a factory, really) is still pretty ugly though:</p>

<pre><code>public function build( SendNotification $command ): EmailComponentsDTO {

    $request = Request::createFromGlobals();

    $Recipient = $this-&gt;ProjectRecipientEmailQuery-&gt;execute( $request-&gt;request-&gt;get( 'destination' ) );

    if ( !\is_email( $Recipient ) ) :

        throw new \Exception( 'No email address found!' );

    endif;

    return new EmailComponentsDTO(
        TRUE,
        $Recipient,
        (array)$command-&gt;getCustomField( 'additional_recipients' ),
        $this-&gt;OptionQuery-&gt;getOption( 'email_from' ),
        $this-&gt;OptionQuery-&gt;getOption( 'email_email' ),
        (string)$this-&gt;NotificationSubject-&gt;render( $command ),
        (string)$this-&gt;NotificationRenderFactory-&gt;render( 'EmailNotification', $command ),
        $command-&gt;getPriority()
    );
}
</code></pre>

<p>But I feel concerns are now seperated a bit better.</p>
",https://stackoverflow.com/questions/53673396/is-this-command-handler-testable,"['php', 'database', 'unit-testing', 'session', 'fixtures']",129,TRUE,0,1
Kotlin: add an interface to guice-injected dependencies such that we could mock them just for unit test purposes?,"<p>I have a storm topology that uses guice to inject various dependencies in the bolts. The dependencies are not constructer injected because of storm serialization/deserialization issues. We pass a guice <code>injector</code> object to the bolt constructor and use it in the bolt's <code>prepare</code> method to field inject the dependencies (non-ideal, I know, but don't know a better scenario for now).</p>

<pre><code>class MyBolt(val injector: Injector) : AbstractRichBolt() {
   @Inject
   @Transient
   private lateinit var myController: MyController
   ...
   override fun prepare(...) {
       this.injector.injectMembers(this)
   }
   override fun execute(input: Tuple) {
       // use myController in our logic here
   }
}
</code></pre>

<p>I'm writing unit tests for the bolt with a test guice module such that I can inject mock dependencies for things like database controllers, etc. To do that, I need to bind the controller class to a mocked class:</p>

<pre><code>bind(MyController::class.java).toInstance(MockController())
</code></pre>

<p>However, to make this work, I have to make <code>MockController</code> inherit from the same interface/super class as <code>MyController</code>. What I am not sure about is if this is a good practice to add an interface to <code>MyController</code> just for unit testing.</p>
",https://stackoverflow.com/questions/51957364/kotlin-add-an-interface-to-guice-injected-dependencies-such-that-we-could-mock,"['java', 'kotlin', 'mockito', 'guice', 'apache-storm']",1079,TRUE,0,1
How to pass a &quot;don&#39;t care&quot; function as callback while testing with Mocha and Sinon?,"<p>Here is my code:</p>

<pre><code>var assert = require('assert')
var sinon = require('sinon')

// This is the business logic we want to test.
//
// Adds two numbers and returns the result. Also calls the callback with
// the result as argument when callback is defined.
function add(a, b, callback) {
  var result = a + b

  if (typeof callback !== 'undefined') {
    callback(result)
  }

  return result
}


describe('Tests', function () {
  it('test callback is called', function () {
    var callback = sinon.fake()
    add(1, 2, callback)
    assert(callback.calledWith(3))
  })

  it('test return value when callback absent', function () {
    var result = add(1, 2)
    assert(result, 3)
  })

  it('test return value when callback present', function () {
    var result = add(1, 2, sinon.fake())
    assert(result, 3)
  })
})
</code></pre>

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

<pre><code>$ node_modules/.bin/mocha foo.js 


  Tests
    ✓ test callback is called
    ✓ test return value when callback absent
    ✓ test return value when callback present


  3 passing (7ms)
</code></pre>

<p>I am concerned about the third test with description <code>'test return value when callback present'</code>. We don't care about the callback we pass to <code>add()</code> in the third test. I could have as well passed an anonymous function such as <code>function () {}</code> instead of <code>sinon.fake()</code>.  I see that I can also pass <code>sinon.stub()</code> or <code>sinon.mock()</code> instead of <code>sinon.fake()</code>.</p>

<p>With so many different choices, I am confused what is the appropriate argument to pass as a callback function when we do not care about the function at all? Since all four options: <code>function () {}</code>, <code>sinon.fake()</code>, <code>sinon.stub()</code>, and <code>sinon.mock()</code> seem to work fine, here is my question:</p>

<ol>
<li>Does the <code>sinon</code> project or unit testing concepts demand that we use one option over another for this case, or are all four options equally technically correct?</li>
<li>Do we have to be aware of any pitfalls associated with one or more of these options?</li>
</ol>
",https://stackoverflow.com/questions/52933962/how-to-pass-a-dont-care-function-as-callback-while-testing-with-mocha-and-sin,"['javascript', 'unit-testing', 'callback', 'mocha.js', 'sinon']",187,FALSE,0,0
test ansible roles with molecule and boto3,"<p>I have <code>ansible roles</code> that creates servers, S3 buckets, security groups ... and I want to establish some unit testing using <code>Molecule</code>.
After some researches, I found out that <code>Molecule</code> is using <code>Testinfra</code> to run some assert commands on the remote/local host. That can work for my roles that create some servers like <code>apache2</code>, <code>nginx</code>.. but how about the other roles that are just creating some other aws resources like <code>load balancers</code>, <code>autoscaling groups</code>, <code>security groups</code>, or just <code>s3 buckets</code>? in this case, there will be no host nor instances.</p>

<p>It would be easy to make tests by <code>Unittest</code> and <code>boto3</code> and call the AWS API, but my question is can I use <code>molecule</code> only and fire up an <code>EC2 instance</code> everytime I want to test my role of security group and then do something like this :</p>

<pre><code>def test_security_group_has_80_open(host):
    cmd = host.run('aws ec2 describe-security-groups --group-names MySecurityGroup')
    return_code = cmd.rc
    output = cmd.stdout
    assert output.contains('""ToPort"": 80')
</code></pre>

<p>That <code>EC2 instance</code> would have <code>AWSCLI</code> installed. Is this a correct way ? Is it possible to test all type of roles by <code>Molecule</code> by firing an <code>EC2</code> that runs <code>awscli</code> calls ?</p>
",https://stackoverflow.com/questions/50371158/test-ansible-roles-with-molecule-and-boto3,"['python', 'ansible', 'aws-sdk', 'aws-cli', 'molecule']",416,FALSE,0,1
How to assert in MiniTest if method is sent to object that is NOT a mock?,"<p>I understand that we can check if methods are sent to Mock objects using <code>expect</code>, but what about checking if methods are sent to objects that aren't Mocks, but actual objects in your app?</p>

<p>Motivation: Sandi Metz' talk 'Magic Tricks of Testing' <a href=""https://www.youtube.com/watch?v=URSWYvyc42M"" rel=""nofollow noreferrer"">https://www.youtube.com/watch?v=URSWYvyc42M</a> says that for unit testing outgoing command method calls (explained in her talk), we should verify that the message is sent. I'm attempting to do so but the only thing I've found in MiniTest is <code>assert_send</code>, which has a few issues:</p>

<ol>
<li>It's deprecated.</li>
<li>It doesn't take into account the value of the arguments sent to the receiving object. If I run <code>assert_send([object, :method_called, 'argument 1', 'argument 2'])</code>, the assertion will return true, even if <code>object</code> was expecting different strings than <code>'argument 1'</code> and <code>'argument 2'</code>.</li>
</ol>

<p>I've scoured the internet for the better part of 2 days on this. Anyone have any ideas?</p>
",https://stackoverflow.com/questions/52764850/how-to-assert-in-minitest-if-method-is-sent-to-object-that-is-not-a-mock,"['ruby-on-rails', 'ruby', 'unit-testing', 'mocking', 'minitest']",1956,TRUE,0,2
When Do UI Tests Happen in a React App?,"<p>So I understand the flow of unit testing, and enzyme/dom testing within a react project.  The tests pull components, mock what's necessary, and then these tests can be run manually, or through a CI tool or git hooks.</p>

<p>However, as I'm reading into and writing Puppeteer UI tests, I'm a little confused.  Most seem to require the entire server to be running, as they rely on localhost:3000.  In other words, <em>testing requires more than just running the test file</em>.</p>

<p>So I suppose my question is</p>

<ol>
<li>Am I misunderstanding <strong>how</strong> UI tests work, and is there a way to pull isolated/mocked components, so that these tests can be run just by running the test file</li>
</ol>

<p>or</p>

<ol start=""2"">
<li>Am I misunderstanding <strong>when</strong> UI tests are supposed to be done.  Are they something that are run manually by devs, infrequently?</li>
</ol>
",https://stackoverflow.com/questions/50725126/when-do-ui-tests-happen-in-a-react-app,"['reactjs', 'integration-testing', 'puppeteer']",94,FALSE,0,1
TDD in Flutter/Dart. How to reduce start up time,"<p>I try to do Test-Driven Development (TDD) in Dart for the business logic of apps with Flutter. The startup time for running the test feels a little bit slow for fast TDD cycles. It is around 4-5 seconds on my machine.</p>
<p>I am using the <code>package:test/test.dart</code>, so there is no need to deploy the app onto the device and the tests can run locally on the Dart VM. The tests themselves run fast.</p>
<p>While developing Android native apps with Java's JUnit and the local Java VM the startup time was much faster &lt; 1sec.</p>
<p>Is there a way to get the start-up time for unit testing in Dart that fast too? (Without buying a much faster physical machine).</p>
<p><strong>Edit:</strong>
My Dart versions:</p>
<ul>
<li>Flutter doctor -v: 2.0.0-dev.54.0.flutter-46ab040e58</li>
<li>The Dart Plugin uses:
2.0.0-edge.c080951d45e79cd25df98036c4be835b284a269c and is in my flutter installation: C:\flutter\bin\cache\dart-sdk</li>
</ul>
<p>The Dart tests are inside a Flutter project. I start the Dart tests in Android Studio via right-clicking a file with a test or just use the &quot;&gt;&quot; run test buttons in the IDE. Android Studio then generates a run config, so I can start it with keyboard shortcuts fast.</p>
<p><a href=""https://i.stack.imgur.com/SvzlM.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/SvzlM.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/50948136/tdd-in-flutter-dart-how-to-reduce-start-up-time,"['unit-testing', 'dart', 'tdd', 'flutter']",3580,TRUE,25,3
how to stub callback result in sinon?,"<p>I am new to nodejs. </p>

<p>How do I stub my return result which is a callback.</p>

<p>I know that I should not access the DB when doing testing. </p>

<p>I am doing unit testing at the controller level.</p>

<p>Here is my flow on how I going to do my test based on my understanding from java. </p>

<ol>
<li>Mock Request and Response.</li>
<li>Set param of request.</li>
<li>Mock bookDAO.selectBook so that it return a user defined result. Thus not calling DB.</li>
<li>Verify / assert the value of the return results. (i.e. Response must be 200, JSON format, must have column BOOK_ID, BOOK_TITLE, etc)</li>
</ol>

<p>However, i was not able to successfully mock my function. After running npm test, this is the error that I am receiving.</p>

<pre><code>2018-10-02T10:00:17.809   1) Book service
       1. should list a SINGLE Book /book/id GET:
     Error: selectBook cannot yield to '[object Object]' since no callback was passed. Received [XCV1234, function (result) {

                res.status(200).json({
                        message: format(message.DEFAULT_MSG, ""GET"", constant.MODULE_URL),
                        result: result
                });
        }]
      at throwYieldError (node_modules\sinon\lib\sinon\call.js:22:11)
      at Object.yieldToOn (node_modules\sinon\lib\sinon\call.js:167:13)
      at Object.yieldTo (node_modules\sinon\lib\sinon\call.js:156:31)
      at Function.spyApi.(anonymous function) [as yieldTo] (node_modules\sinon\lib\sinon\spy.js:416:61)
      at Context.it (test\controller\BookController.spec.js:47:17)
</code></pre>

<p>Am i doing it the right way? how do i return the callback result ?</p>

<hr>

<p><strong>bookController.js:</strong></p>

<pre><code>exports.getBook = (req, res) =&gt; {   

    //get from request
    const id = req.params.id;

    const params = [id];

    bookDao.selectBook(params, function (result) {

        res.status(200).json({
            message: format(message.DEFAULT_MSG, ""GET"", constant.MODULE_URL),
            result: result  
        });
    });
};
</code></pre>

<p><strong>bookDao.js:</strong></p>

<pre><code>function selectBook(params, callback) {

    pool.open(connString, function (err, conn) {

        conn.queryResult(query.SQL_SELECT, params, function (err, result) {

            if (err) {
                console.error(err);
                return conn.closeSync();
            }

            var data = result.fetchAllSync();

            // only when successful then call closeSync
            result.closeSync(); 

            return callback(data);
        });

        conn.close();
    });
}
</code></pre>

<p><strong>bookRest.js:</strong></p>

<pre><code>module.exports = (app) =&gt; {

    // map to controller
    const controller = require('../controller/bookController');

    app.route(constant.MODULE_URL + '/:id').get(controller.getbook);

    app.route(constant.MODULE_URL).put(controller.updateBooks);
};
</code></pre>

<p><strong>bookController.spec.js:</strong></p>

<pre><code>process.env.NODE_ENV = 'test';

const sinon = require('sinon');
const chai = require('chai');
const chaiHttp = require('chai-http');
const should = chai.should();
const httpMocks = require('node-mocks-http');

let server = require('../../../main.js');

const bookController = require('../../../controller/bookController.js');
const bookDao = require('../../../dao/bookDao.js');

chai.use(chaiHttp);

let req = httpMocks.createRequest();
let res = httpMocks.createResponse();

describe('Book service', () =&gt; {    
    beforeEach(() =&gt; {
    });

    afterEach(() =&gt; {
    });

    it('1. should list a SINGLE Book /book/id GET', (done) =&gt; {

        req.params.id = ""XCV1234"";
        const selectbook = sinon.stub(bookDao, ""selectbook"");

        bookController.getbook(req, res);
        selectbook.yieldTo({BOOK_ID : ""XCV1234""});

        res.should.have.status(200);
        res.should.be.json;
        res.body.should.be.a('object');

        res.body.result[0].should.include.keys(
            'BOOK_ID'
        );

        sinon.restore();
        done();
     });    
});
</code></pre>
",https://stackoverflow.com/questions/52601265/how-to-stub-callback-result-in-sinon,"['node.js', 'unit-testing', 'callback', 'sinon']",4220,TRUE,0,1
Connecting to the MySQL Database using Dependency Injection in PHP,"<p>I am currently trying to grasp the basics of Dependency Injection and I'm running into quite a bit of trouble.</p>

<p>While I do understand the basic premise of why it's useful (ease of unit testing, removal of hard-coded classes), I don't really understand how that goes into databases.</p>

<p>Basically, I cannot for the life of me understand how I can connect to a database using the DI technique.</p>

<p>As far as I understand I would have to pass all variables through a constructor</p>

<pre><code>Class DatabaseConfiguration
{
    private $servername;
    private $dbname;
    private $dbuser;
    private $dbpass;

    public function __construct(string $server, string $name, string $user, 
    string $pass, string $charset){
        $this-&gt;servername = $server;
        $this-&gt;dbname = $name;
        $this-&gt;dbuser = $user;
        $this-&gt;dbpass = $pass;
        $this-&gt;dbcharset = $charset;
}
</code></pre>

<p>This is where I get stuck. I am quite clueless on what I should be doing next to establish a connection.</p>

<p>Usually, I would hard-code the values and then call a function in which I would do something like this:</p>

<pre><code>public function connectDB(){
    try{
        $conn = ""mysql:host="".$this-&gt;servername."";dbname="".$this-&gt;dbname."";charset="".$this-&gt;dbcharset;
        $pdo = new PDO($conn, $this-&gt;dbuser, $this-&gt;dbpass);
        $pdo-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $pdo;
    }catch(PDOException $e){
        echo ""Connection failed: "".$e-&gt;getMessage();
    }
}
</code></pre>

<p>I have no clue how to do it the DI way, though.</p>
",https://stackoverflow.com/questions/53807828/connecting-to-the-mysql-database-using-dependency-injection-in-php,['php'],954,TRUE,0,1
Visual Studio unit test not working and not showing tests,"<p>I am following <a href=""https://msdn.microsoft.com/en-us/library/ms182470.aspx"" rel=""nofollow noreferrer"">MSDocs guide</a> to put up some unit testing. I've never used them before and I've never been using them because to me they are totally useless, but I see it's a common practice, so I wanted to learn more.</p>

<p>Obviously, this is not working.</p>

<p>I've put up some .NET Standard 2.0 libraries with little to no code to do some <a href=""https://logging.apache.org/log4net/"" rel=""nofollow noreferrer"">log4net</a> logging. I've addet a ""Unit test project"" as the guide suggests and added a method decorated with the ""TestMethod"" attribute and all the other attributes.</p>

<p>Test explorer windows does not show any test and I'm not able to even run them in any way. What am I missing?</p>

<p>Here's the code</p>

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

namespace UnitTests
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void ErrorLogOnFile_Default() =&gt; MrLogger.Instance.FileErrorLog(""I'M AN ERROR!!! :)"");
    }
}
</code></pre>

<p>The MrLogger class it's just a class that does logger.Debug(""Write message""), a classical log4net logging call.</p>

<p>I've tried <a href=""https://stackoverflow.com/questions/19298347/nunit-unit-tests-not-showing-in-test-explorer-with-test-adapter-installed"">this</a> too and it changes nothing.</p>

<p>Jeez... help</p>
",https://stackoverflow.com/questions/48259904/visual-studio-unit-test-not-working-and-not-showing-tests,"['visual-studio', 'unit-testing', 'log4net']",1067,TRUE,0,1
Eclipse Oxygen 3a (4.7.3a) not finding test classes with Java 9,"<p>I am trying to get my open source project (JFXtras) running with Java 9 in Eclipse. IntelliJ is working fine, but not a fan. </p>

<p>In JFXtras there is a subproject jfxtras-test-support which contains classes for unit testing. This is not a Java 9 module. The test-support subproject is added correctly to (for example) jfxtras-common in the Eclipse 'Java Build Path' under the Projects tabs as a classpath entry. The other required jars like junit are under the Libraries tabs as classpath entries. Exactly as I would expect.</p>

<p>However, Eclipse is showing errors that it cannot find the JUnit nor the JFXtras test classes. But if I ctrl-click on the import, Eclipse jumps to the correct source file. But starting any of the unit test fail because Eclipse can't find the class file.</p>
",https://stackoverflow.com/questions/50314651/eclipse-oxygen-3a-4-7-3a-not-finding-test-classes-with-java-9,"['eclipse', 'java-9']",252,FALSE,0,0
Setting environment variables inside PHP unit tests,"<p>I'm doing some basic unit testing on a utility function I made years ago but it involves accessing the <code>$_SERVER</code> array.</p>

<p>Since my unit tests are run from the command line, I have to manually set the values of the array myself.</p>

<p>This works well using GitLab Runners because on the <code>.gitlab-ci.yml</code> file I just do something like:</p>

<pre><code>before_script:
  - export SERVER_PORT=""80""
  - export SERVER_NAME=""gitlab""
</code></pre>

<p>My test is currently unable to test all statements from that function as it checks for the <code>$_SERVER['SERVER_NAME']</code> value.</p>

<h2>Unit Test</h2>

<pre><code>public function testGetEnvironment() {
    shell_exec('set SERVER_NAME=""localhost""');
    $this-&gt;assertEquals(""localhost"", $this-&gt;util-&gt;get_environment());

    shell_exec('set SERVER_NAME=""gitlab""');
    $this-&gt;assertEquals(""gitlab"", $this-&gt;util-&gt;get_environment());
}
</code></pre>

<p><strong>NOTE:</strong> I had to use <code>set</code> as I am on a Windows machine while our GitLab Runner is on a Linux machine so I used <code>export</code> on the <code>gitlab-ci.yml</code> file.</p>

<p>I was expecting this test to pass but it seems like the command to set the environment variable using <code>shell_exec</code> isn't changing the value at all. I still get the value from what was defined from the YAML file.</p>

<h2>Update</h2>

<p>Here's the failure message:</p>

<pre><code>1) UtilTest::testGetEnvironment
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'localhost'
+'gitlab'
</code></pre>
",https://stackoverflow.com/questions/52393375/setting-environment-variables-inside-php-unit-tests,"['php', 'unit-testing', 'environment-variables', 'gitlab', 'shell-exec']",2314,TRUE,4,1
Test api CRUD operation with Moq,"<p>I would like to test my Web api in asp.net core 2.0 using moq.
With operations like : GetAll, getByID there is no problem.
But issue starts when I want to test methods like Insert or Update.
Whenever I configure setup for example :</p>

<pre><code>serviceMock.Setup(x =&gt; x.Update(someModel))
                    .Returns(someModel);
</code></pre>

<p>then call method for Controller under test :</p>

<pre><code>ControllerUnderTest.UpdateRespondentList(someModel.ID, someModel);
</code></pre>

<p>Controller receives data properly but counter for my mock list doesn't increase.</p>

<p>I would like you to ask that is there other way then testing this using .Verify() method or create completely new List ?</p>

<p>-- there is what I mean :
<a href=""https://stackoverflow.com/questions/7599957/unit-testing-linq-to-sql-crud-operations-using-moq"">Unit testing LINQ to SQL CRUD operations using Moq</a></p>

<p>There is how I inject mocked service :</p>

<pre><code>ControllerUnderTest = new RespondentListController(_config, serviceMock.Object);
</code></pre>

<p>In my opinion cinfiguration works because whenever I test methods like : getall I have an access to mockedSerivice</p>

<p>Algorithm should looks like this :
Insert object into mocked list via ControllerUnderTest -> Asser.Equal (prevStateOfCounter, currentStateOfCounter-1)</p>
",https://stackoverflow.com/questions/51926925/test-api-crud-operation-with-moq,"['c#', 'asp.net-web-api', 'moq']",761,TRUE,0,1
Jest - How to get coverage for mocked classes and implementations,"<p>I'm currently working on a project where I'm using Jest for unit testing and code coverage.</p>

<p>Everything is working fine, except coverage for mocked classes/methods. I don't seem to get the desired coverage results. I've tried to find something in the Jest docs and searched online for an answer, but I can't seem to find anything about it.</p>

<p>The thing is that when I use a mocked implementation (for example <code>./services/__mocks__/UserService.js</code>), the actual implementation (<code>./services/UserService.js</code>) results in having 0% coverage. This is a logical outcome, since the implementation is overwritten by the mock.</p>

<p>I can get around this by using <code>/* istanbul ignore next */</code> on every method in the actual service or simply add the actual services to the <code>coveragePathIgnorePatterns</code> property in the Jest setup file and let it generate coverage for all mocked classes instead, but I wonder if there is any way to have Jest use the mocked implementation automatically for generating coverage results.</p>

<p>What is the way to go for mocked classes/functions and code coverage?</p>

<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/50348317/jest-how-to-get-coverage-for-mocked-classes-and-implementations,"['unit-testing', 'mocking', 'code-coverage', 'jestjs']",2377,TRUE,8,1
Spring boot pagination with native query throws NumberFormatException,"<p>The error started to show up when I added pagination (using <code>Pageable</code>) to the search query with <code>ORDER BY ?#{#pageable}</code>. I'm using H2 database for unit-testing with <code>database-platform: org.hibernate.dialect.H2Dialect</code>.</p>

<p>Spring boot version: <code>1.5.9.RELEASE</code>
Java version: <code>1.8</code></p>

<p>Repository:</p>

<pre><code>@Repository
public interface VacancyRepository extends PagingAndSortingRepository&lt;Vacancy, Long&gt; {

    @Query(value = ""SELECT * FROM vacancies WHERE location ILIKE %:location% AND CONCAT(title, ' ', description) ILIKE %:keyword% ORDER BY ?#{#pageable}"",
            countQuery = ""SELECT COUNT(*) FROM vacancies WHERE location ILIKE %:location% AND CONCAT(title, ' ', description) ILIKE %:keyword%"",
            nativeQuery = true)
    Page&lt;Vacancy&gt; search(@Param(""location"") String location, @Param(""keyword"") String keyword, Pageable pageable);

}
</code></pre>

<p>Controller method (controller is prefixed with <code>/vacancy/</code>):</p>

<pre><code>@RequestMapping(method = RequestMethod.GET, value = ""/search/location/{location}/keyword/{keyword}"", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity&lt;Page&lt;Vacancy&gt;&gt; search(@PathVariable String location, @PathVariable String keyword, Pageable pageable) {
    Page&lt;Vacancy&gt; vacancies = vacancyRepository.search(location, keyword, pageable);
    return ResponseEntity.ok().body(vacancies);
}
</code></pre>

<p>How it is used in tests:</p>

<pre><code>    // Given
    String path = ""/vacancy/search/location/searchQueryLocation/keyword/search?page=0&amp;size=1&amp;sort=id"";

    // When
    ResultActions sendRequest = mvc.perform(get(path));
</code></pre>

<p>Exception thrown:</p>

<pre><code>org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.DataException: could not extract ResultSet

    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
    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:160)
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:127)
    at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155)
    at uk.gov.cshr.vcm.controller.VacancyControllerTest.testSearch(VacancyControllerTest.java:336)
    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.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:104)
    at org.testng.internal.MethodInvocationHelper$1.runTestMethod(MethodInvocationHelper.java:205)
    at org.springframework.test.context.testng.AbstractTestNGSpringContextTests.run(AbstractTestNGSpringContextTests.java:175)
    at org.testng.internal.MethodInvocationHelper.invokeHookable(MethodInvocationHelper.java:217)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:641)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:851)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1177)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:129)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:112)
    at org.testng.TestRunner.privateRun(TestRunner.java:756)
    at org.testng.TestRunner.run(TestRunner.java:610)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:387)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:382)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340)
    at org.testng.SuiteRunner.run(SuiteRunner.java:289)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1293)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1218)
    at org.testng.TestNG.runSuites(TestNG.java:1133)
    at org.testng.TestNG.run(TestNG.java:1104)
    at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:72)
    at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:123)
Caused by: org.springframework.dao.DataIntegrityViolationException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.DataException: could not extract ResultSet
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:282)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:503)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:209)
    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.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy111.search(Unknown Source)
    at uk.gov.cshr.vcm.controller.VacancyController.search(VacancyController.java:82)
    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: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)
    ... 36 more
Caused by: org.hibernate.exception.DataException: could not extract ResultSet
    at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:118)
    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.extract(ResultSetReturnImpl.java:79)
    at org.hibernate.loader.Loader.getResultSet(Loader.java:2117)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1900)
    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.custom.CustomLoader.list(CustomLoader.java:336)
    at org.hibernate.internal.SessionImpl.listCustomQuery(SessionImpl.java:1967)
    at org.hibernate.internal.AbstractSessionImpl.list(AbstractSessionImpl.java:322)
    at org.hibernate.internal.SQLQueryImpl.list(SQLQueryImpl.java:125)
    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$PagedExecution.doExecute(JpaQueryExecution.java:188)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:87)
    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:499)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:477)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:56)
    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)
    ... 59 more
Caused by: org.h2.jdbc.JdbcSQLException: Data conversion error converting ""aced00057372002b6f72672e737072696e676672616d65776f726b2e646174612e646f6d61696e2e5061676552657175657374c0f950c5c09dc7260200014c0004736f72747400264c6f72672f737072696e676672616d65776f726b2f646174612f646f6d61696e2f536f72743b787200336f72672e737072696e676672616d65776f726b2e646174612e646f6d61696e2e41627374726163745061676552657175657374111be055001d2dc70200024900047061676549000473697a6578700000000000000001737200246f72672e737072696e676672616d65776f726b2e646174612e646f6d61696e2e536f72744f9e94bc46c7fa210200014c00066f72646572737400104c6a6176612f7574696c2f4c6973743b7870737200136a6176612e7574696c2e41727261794c6973747881d21d99c7619d03000149000473697a657870000000017704000000017372002a6f72672e737072696e676672616d65776f726b2e646174612e646f6d61696e2e536f7274244f7264657215210bb2a35266bb0200045a000a69676e6f7265436173654c0009646972656374696f6e7400304c6f72672f737072696e676672616d65776f726b2f646174612f646f6d61696e2f536f727424446972656374696f6e3b4c000c6e756c6c48616e646c696e677400334c6f72672f737072696e676672616d65776f726b2f646174612f646f6d61696e2f536f7274244e756c6c48616e646c696e673b4c000870726f70657274797400124c6a6176612f6c616e672f537472696e673b7870007e72002e6f72672e737072696e676672616d65776f726b2e646174612e646f6d61696e2e536f727424446972656374696f6e00000000000000001200007872000e6a6176612e6c616e672e456e756d000000000000000012000078707400034153437e7200316f72672e737072696e676672616d65776f726b2e646174612e646f6d61696e2e536f7274244e756c6c48616e646c696e6700000000000000001200007871007e000f7400064e4154495645740002696478""; SQL statement:
SELECT * FROM vacancies WHERE location ILIKE ? AND CONCAT(title, ' ', description) ILIKE ? ORDER BY ?, id asc limit ? [22018-196]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
    at org.h2.message.DbException.get(DbException.java:168)
    at org.h2.value.Value.convertTo(Value.java:996)
    at org.h2.value.Value.getInt(Value.java:459)
    at org.h2.command.dml.Query.prepareOrder(Query.java:518)
    at org.h2.command.dml.Select.prepare(Select.java:834)
    at org.h2.command.CommandContainer.recompileIfRequired(CommandContainer.java:88)
    at org.h2.command.CommandContainer.query(CommandContainer.java:109)
    at org.h2.command.Command.executeQuery(Command.java:201)
    at org.h2.jdbc.JdbcPreparedStatement.executeQuery(JdbcPreparedStatement.java:111)
    at sun.reflect.GeneratedMethodAccessor62.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.tomcat.jdbc.pool.StatementFacade$StatementProxy.invoke(StatementFacade.java:114)
    at com.sun.proxy.$Proxy124.executeQuery(Unknown Source)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:70)
    ... 88 more
Caused by: java.lang.NumberFormatException: For input string: ""aced00057372002b6f72672e737072696e676672616d65776f726b2e646174612e646f6d61696e2e5061676552657175657374c0f950c5c09dc7260200014c0004736f72747400264c6f72672f737072696e676672616d65776f726b2f646174612f646f6d61696e2f536f72743b787200336f72672e737072696e676672616d65776f726b2e646174612e646f6d61696e2e41627374726163745061676552657175657374111be055001d2dc70200024900047061676549000473697a6578700000000000000001737200246f72672e737072696e676672616d65776f726b2e646174612e646f6d61696e2e536f72744f9e94bc46c7fa210200014c00066f72646572737400104c6a6176612f7574696c2f4c6973743b7870737200136a6176612e7574696c2e41727261794c6973747881d21d99c7619d03000149000473697a657870000000017704000000017372002a6f72672e737072696e676672616d65776f726b2e646174612e646f6d61696e2e536f7274244f7264657215210bb2a35266bb0200045a000a69676e6f7265436173654c0009646972656374696f6e7400304c6f72672f737072696e676672616d65776f726b2f646174612f646f6d61696e2f536f727424446972656374696f6e3b4c000c6e756c6c48616e646c696e677400334c6f72672f737072696e676672616d65776f726b2f646174612f646f6d61696e2f536f7274244e756c6c48616e646c696e673b4c000870726f70657274797400124c6a6176612f6c616e672f537472696e673b7870007e72002e6f72672e737072696e676672616d65776f726b2e646174612e646f6d61696e2e536f727424446972656374696f6e00000000000000001200007872000e6a6176612e6c616e672e456e756d000000000000000012000078707400034153437e7200316f72672e737072696e676672616d65776f726b2e646174612e646f6d61696e2e536f7274244e756c6c48616e646c696e6700000000000000001200007871007e000f7400064e4154495645740002696478""
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Long.parseLong(Long.java:592)
    at org.h2.value.Value.convertTo(Value.java:641)
</code></pre>

<p>Judging by the ""aced"" in the beginnig, it looks like a serialized Java object, but I don't see where it is serialized.</p>

<p>Generated Hibernate log:</p>

<pre><code>Hibernate: SELECT * FROM vacancies WHERE location ILIKE ? AND CONCAT(title, ' ', description) ILIKE ? ORDER BY ?, id asc limit ?
2018-01-04 15:08:02.940  WARN 6872 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 22018, SQLState: 22018
2018-01-04 15:08:02.940 ERROR 6872 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : Data conversion error converting ""aced00057372002b6f72672e737072696e676672616d65776f726b2e646174612e646f6d61696e2e5061676552657175657374c0f950c5c09dc7260200014c0004736f72747400264c6f72672f737072696e676672616d65776f726b2f646174612f646f6d61696e2f536f72743b787200336f72672e737072696e676672616d65776f726b2e646174612e646f6d61696e2e41627374726163745061676552657175657374111be055001d2dc70200024900047061676549000473697a6578700000000000000001737200246f72672e737072696e676672616d65776f726b2e646174612e646f6d61696e2e536f72744f9e94bc46c7fa210200014c00066f72646572737400104c6a6176612f7574696c2f4c6973743b7870737200136a6176612e7574696c2e41727261794c6973747881d21d99c7619d03000149000473697a657870000000017704000000017372002a6f72672e737072696e676672616d65776f726b2e646174612e646f6d61696e2e536f7274244f7264657215210bb2a35266bb0200045a000a69676e6f7265436173654c0009646972656374696f6e7400304c6f72672f737072696e676672616d65776f726b2f646174612f646f6d61696e2f536f727424446972656374696f6e3b4c000c6e756c6c48616e646c696e677400334c6f72672f737072696e676672616d65776f726b2f646174612f646f6d61696e2f536f7274244e756c6c48616e646c696e673b4c000870726f70657274797400124c6a6176612f6c616e672f537472696e673b7870007e72002e6f72672e737072696e676672616d65776f726b2e646174612e646f6d61696e2e536f727424446972656374696f6e00000000000000001200007872000e6a6176612e6c616e672e456e756d000000000000000012000078707400034153437e7200316f72672e737072696e676672616d65776f726b2e646174612e646f6d61696e2e536f7274244e756c6c48616e646c696e6700000000000000001200007871007e000f7400064e4154495645740002696478""; SQL statement:
SELECT * FROM vacancies WHERE location ILIKE ? AND CONCAT(title, ' ', description) ILIKE ? ORDER BY ?, id asc limit ? [22018-196]
</code></pre>

<p>The same query without <code>Pageable</code> works as expected. I tried different ways of writing the same <code>Pageable</code> thing (including <code>ORDER BY /*#pageable*/</code> or <code>ORDER BY t.id DESC \n-- #pageable\n</code> or by trying to comment the <code>#pageable</code> in the query (<code>/*#pageable*/</code>) and passing my own page and page size parameters) but nothing works.</p>

<p>I know that I can replace this particular query with somethig that uses <code>to_upper()</code> instead of <code>ILIKE</code> and use JPA queries, but the following steps will imply something that is not implemented in JPA queries and requires native queries.</p>

<p>Any help would be much appreciated.</p>
",https://stackoverflow.com/questions/48097448/spring-boot-pagination-with-native-query-throws-numberformatexception,"['spring', 'hibernate', 'spring-boot', 'spring-data-jpa', 'h2']",1959,FALSE,3,0
Constants are undefined while testing using Enzyme + React Native + Jest,"<p>I want to unit test my React Native component with Enzyme and Jest.</p>

<p>It is a QR Scanner that calls a function after a successful scan. This function communicates with the server and returns a response. It then uses a <code>switch</code> statement to determine what to do next. When I just use the app, the component and it's function works finde. But the unit tests for this function fail, because all constants are undefined. How can I fix this?</p>

<p>For reference, here is the code of my unit tests (stripped for clarity):</p>

<pre><code>import React from ""react"";
import { shallow } from ""enzyme"";
import { Alert, View } from ""react-native"";

import * as qrCodeFunctions from ""../../api/qrCodes/qrCodes"";
import { ScannerScreen } from ""./ScannerScreen"";

Alert.alert = jest.fn();

const createTestProps = props =&gt; ({
  navigation: { navigate: jest.fn() },
  setData: jest.fn(),
  ...props
});

describe(""ScannerScreen"", () =&gt; {
  describe(""rendering"", () =&gt; {
    let wrapper;
    let props;
    beforeEach(() =&gt; {
      props = createTestProps();
      wrapper = shallow(&lt;ScannerScreen {...props} /&gt;);
    });

    it(""should render a &lt;View /&gt;"", () =&gt; {
      expect(wrapper.find(View)).toHaveLength(1);
    });

    it(""should render a &lt;QRCodeScanner /&gt;"", () =&gt; {
      expect(wrapper.find(""QRCodeScanner"")).toHaveLength(1);
    });
  });

  describe(""interaction"", () =&gt; {
    let wrapper;
    let props;
    beforeEach(() =&gt; {
      props = createTestProps();
      wrapper = shallow(&lt;ScannerScreen {...props} /&gt;);
    });

    afterEach(() =&gt; {
      jest.clearAllMocks();
    });

    describe(""scanning the qr code"", () =&gt; {
      describe(""data received"", () =&gt; {
        qrCodeFunctions.executeQRCodeFunction = jest.fn(
          () =&gt;
            new Promise(resolve =&gt;
              resolve({
                entities: {
                  houses: {
                    ""b813d3d1-9fdb-47bf-92ee-f7cb8bd6564b"": {
                      category: ""villa"",
                      price: 2.400.000,
                      uuid: ""b813d3d1-9fdb-47bf-92ee-f7cb8bd6564b""
                    }
                  },
                  ...
                },
                result: {
                  detail: ""Successfully received villas."",
                  qrCodeData: ""aeb1717f-480f-415f-9d15-00906750cae2""
                }
              })
            )
        );
        it(""should dispatch an event to set the data and show an alert"", () =&gt; {
          wrapper.instance().onRead({ data: { v1QRCodeData: ""abc"" } });
          expect(qrCodeFunctions.executeQRCodeFunction).toHaveBeenCalledTimes(1);
          expect(props.setData).toHaveBeenCalledTimes(1);
          expect(Alert.alert).toHaveBeenCalledTimes(1);
        });
      });
    });
  });
});
</code></pre>

<p><code>props.setData</code> should be (and is called while not unit testing) called depending on a switch statement just like this:</p>

<pre><code>  onRead = e =&gt; {
    executeQRCodeFunction(e.data.v1QRCodeData)
      .then(data =&gt; {
        console.log(data.result);
        console.log(SERVER_VALUES_QR_CODE_DETAIL_VILLAS_RECEIVED);
        console.log(data.result.detail);
        console.log(data.result.detail == SERVER_VALUES_QR_CODE_DETAIL_VILLAS_RECEIVED);
        switch (data.result.detail) {
          case SERVER_VALUES_QR_CODE_DETAIL_VILLAS_RECEIVED:
            this.villasReceived(data);
            break;
          ...
          default:
            alert(data.result);
        }
      })
      .catch(error =&gt; {
        alert(error);
      });
  };
</code></pre>

<p>The function <code>villasReceived</code> then calls setData. But in the unit tests this never happens, because the switch case always refers to the default case. Furthermore the results of the console logs are, that <code>data.result</code> and <code>data.result.detail</code> are correct, but the comparison is <code>false</code> and the constant <code>undefined</code>.</p>
",https://stackoverflow.com/questions/51752250/constants-are-undefined-while-testing-using-enzyme-react-native-jest,"['unit-testing', 'react-native', 'constants', 'jestjs', 'enzyme']",1751,FALSE,3,1
VS Code Python unittest &quot;No tests ran&quot;,"<p>I'm setting up python unit tests in VS Code using unittest, and running into some issues.  </p>

<p>I am able to run my tests by selecting Run Tests from the status bar, and by right-clicking my test file in Explorer.  When I do either of these, I see unit test output (e.g. ""test_name ... ok"" and ""Ran 1 test in 0.002s"") in the Python Test Log window, but I get a VS Code notification saying ""No tests ran, please check the configuration settings for the tests.""  I am also not seeing the Run Test | Debug Test code lens in the test file.  </p>

<p>I have followed the setup instructions in the VS Code docs here: <a href=""https://code.visualstudio.com/docs/python/unit-testing"" rel=""nofollow noreferrer"">https://code.visualstudio.com/docs/python/unit-testing</a>, but I'm wondering if there are other steps I'll need to follow to get proper integration with the IDE?</p>

<p>I am using VS Code version 1.12.1, on Windows.</p>
",https://stackoverflow.com/questions/49351494/vs-code-python-unittest-no-tests-ran,"['python', 'unit-testing', 'visual-studio-code']",4711,TRUE,3,1
If function A uses function B and I test function A is it an integration test?,"<p>I am currently writing an essay about unit test in JavaScript. I am facing the problem that I suspect my unit test (see Below) is actually an integration test, which of course makes my essay a bit more complicated.</p>

<p>This is what I've got. I am working with mocha and chai (assert):</p>

<pre><code>// region Implementation

/**
 * @param {number} i
 * @returns {number} i + 2
 */
function A(i) {
    return B(i + 1);
}

/**
 * @param {number} i
 * @returns {number} i + 1
 */
function B(i) {
    return i + 1;
}

// endregion

// region Test

lt(""B(i) returns i + 1"", () =&gt; {
    assert.equals(B(2), 3);
})

lt(""A(i) returns i + 2"", () =&gt; {
    assert.equals(B(2), 4);
})

// endregion
</code></pre>

<p>To me, the first test definitely looks like a unit test. Best practices for unit testing left out, it tests a function which in this case is a unit which can't be divided into smaller pieces and in this case it does not depend on any other function.</p>

<p>Function A though relies on function B. The result is, that if I test function A I have to assume that function A is correctly working.</p>

<p>So this got me thinking. Is the second test already an integration test rather than a unit test?</p>

<p>Sincerely
Fabian</p>
",https://stackoverflow.com/questions/49688555/if-function-a-uses-function-b-and-i-test-function-a-is-it-an-integration-test,"['javascript', 'unit-testing', 'integration-testing']",173,TRUE,3,1
How to mock RPi.GPIO in python,"<p>I'm attempting to mock <code>RPi.GPIO</code> in python code to do some unit testing.</p>

<p>The problem I have is that my import of <code>RPi.GPIO</code> fails when called in my unit tests which do not run on the actual Raspberry Pi.</p>

<p>e.g.</p>

<p><strong>tests.py</strong></p>

<pre><code>import iohandler
...
...
</code></pre>

<p><strong>iohandler.py</strong></p>

<pre><code>import RPi.GPIO

def function_to_test():
    pass
</code></pre>

<p>The problem here is that for tests to run it must import <code>iohandler</code> which in turn must import <code>RPi.GPIO</code>. This fails as <code>RPi.GPIO</code> is not installed on the machine which will run the tests.</p>

<p>I've attempted to try and trick the modules after looking at another answer on this site as follows:</p>

<p><strong>tests.py</strong></p>

<pre><code>import sys
import gpiomock # this is a file on the file system
sys.modules[""RPi.GPIO""] = gpiomock.GPIO()

import iohandler # the .py file that contains the actual GPIO import
</code></pre>

<p><strong>gpiomock.py</strong></p>

<pre><code>class GPIO():
    ...
    ...
</code></pre>

<p>As <code>sys.modules</code> is just a dictionary I would have thought this would work as I am providing a key for lookup of <code>RPi.GPIO</code> and also what I want to replace it with. However I get the following error message.</p>

<p><code>ImportError: No module named RPi.GPIO</code></p>

<p>It feels like the <em>nested</em> structure of the actual <code>RPi.GPIO</code> library is causing this not to work.</p>

<p>Any suggestions on how I can make this work?</p>
",https://stackoverflow.com/questions/51879185/how-to-mock-rpi-gpio-in-python,"['python', 'python-2.7']",2833,TRUE,7,2
How to mock the Context API nested Consumers in React to test?,"<p>I am using React new Context API to manage our components state, the following is my basic code structure:</p>

<ol>
<li><p>for each functional component, I have a Provider class to manage its state info. For example of EditFormCanvasProvider: </p>

<pre><code>class EditFormCanvasProvider extends React.Component&lt;Props, State&gt; {

    state = {
        controlsInfo: []
    }      

    render() {
        return (
            &lt;EditFormCanvasContext.Provider value={this.state}&gt;
                {this.props.children}
            &lt;/EditFormCanvasContext.Provider&gt;
        )
    }
}

export default EditFormCanvasProvider;
</code></pre></li>
<li><p>To consume the needed providers from other components, a consumers javascript file is created, the sample code is as follows:</p>

<pre><code>export default function FormBuilderConsumers(props) {
    const { children } = props;

    return (
        &lt;FormBuilderContext.Consumer&gt;
            {FormBuilder =&gt;
                &lt;EditFormCanvasContext.Consumer&gt;
                    {
                        EditFormCanvas =&gt; children({ FormBuilder, EditFormCanvas })
                    }
                &lt;/EditFormCanvasContext.Consumer&gt;
            }
        &lt;/FormBuilderContext.Consumer&gt;
    )
}
</code></pre></li>
<li><p>In the FormBuilder functional javascript component file, which consumes the FormBuilderConsumers. The code is as follows:</p>

<pre><code>const FormBuilder = () =&gt; {
    return (
        &lt;FormBuilderConsumers&gt;
            {(appData) =&gt;
                &lt;div &gt;
                    &lt;Modal dismissible={true}                       
                        isOpen={appData.FormBuilder.modalIsOpen}
                        prompt={appData.FormBuilder.modalPrompt}
                        title={appData.EditFormCanvas.controlsInfo[0]}
                        size=""medium""
                    &gt;
                        &lt;div&gt;
                            {appData.FormBuilder.modalMessage}
                        &lt;/div&gt;
                    &lt;/Modal&gt;


                &lt;/div&gt;
            }
        &lt;/FormBuilderConsumers&gt;
    )
}
export default FormBuilder;
</code></pre></li>
</ol>

<p>I am trying to mock the FormBuiderConsumers in the FormBuilder to test the FormBuilder component By using Jest. But I don't know how to do it. </p>

<p>I am referencing these articles: </p>

<ul>
<li><a href=""https://medium.com/@wyattsweet/testing-react-components-using-the-new-context-api-a1c553edc2fa"" rel=""nofollow noreferrer"">https://medium.com/@wyattsweet/testing-react-components-using-the-new-context-api-a1c553edc2fa</a></li>
<li><a href=""https://medium.com/@ryandrewjohnson/unit-testing-components-using-reacts-new-context-api-4a5219f4b3fe"" rel=""nofollow noreferrer"">https://medium.com/@ryandrewjohnson/unit-testing-components-using-reacts-new-context-api-4a5219f4b3fe</a></li>
</ul>

<p>but it seems they don't put multiple consumers into one file and export it to be consumed as what I am doing. </p>
",https://stackoverflow.com/questions/50705030/how-to-mock-the-context-api-nested-consumers-in-react-to-test,['reactjs'],3761,TRUE,2,1
Mocking a class inside an Android app - not in unit test scope,"<p>I would like to mock an object/class inside my app (this class interacts with a 3rd party library) and I would like to be able to run my app regardless of the actual response I get from the 3rd party library.</p>

<p>I would like to set my own responses to the methods called.</p>

<p>I tried to use mockito and compile it regularly (I have used compile instead of testCompile).</p>

<p>I have encountered different errors with different version when trying to invoke spy or mock static creation of the mock object.</p>

<p>My questions:</p>

<ol>
<li>Is Mockito suitable for running inside the app or it is built only for unit testing? if it is suitable , is there a link for a boilerplate code doing that for android ?</li>
<li>Is there any other better solution/framework other than writing the mock my self? (before I choose implementing a proxy pattern or something similar)</li>
</ol>
",https://stackoverflow.com/questions/48080103/mocking-a-class-inside-an-android-app-not-in-unit-test-scope,"['android', 'design-patterns', 'mocking', 'mockito', 'wrapper']",132,TRUE,2,1
Jest test mock -- mock fetch inside another function,"<p>I have a stateful component I'm trying to test. This component serves as an intermediate step before it calls my other function. Kinda works like this</p>

<pre><code>class MyList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      items: []
    };
  }

  componentDidMount() {
    this.props.loadMystuff().then(() =&gt; {
      if (this.state.eKey !== this.props.eKey) {
        let eKey = this.props.eKey;
        this.fetchSList(eKey);
      }
    }).catch((error) =&gt; toast(error.message));
  }

  fetchSList(eKey) {
    if (eKey !== '') {
      fetch(`some_api_url_config/${this.props.entityKey}`)
            .then(res =&gt; res.json())
            .then(
              (result) =&gt; {
                this.setState({
                  isLoaded: true,
                  items: result
              });
            },
            (error) =&gt; {
              this.setState({
                isLoaded: true,
                error
              });
            }
          );
    }
  }

  render() {
    const { error, isLoaded, items } = this.state;

    if (items) {
      return (
        &lt;div&gt;
          &lt;h3&gt;S List&lt;/h3&gt;
          &lt;ul&gt;
            {items.map(item =&gt; (
              &lt;li key={item}&gt;
                {item}
              &lt;/li&gt;
              ))}
          &lt;/ul&gt;
        &lt;/div&gt;
      );
    } else if (error) {
      return &lt;div&gt;Error: List Missing...{error.message}&lt;/div&gt;;
    } else if (!isLoaded) {
      return &lt;div&gt;Loading List...&lt;/div&gt;;
    } else {
        return &lt;div&gt;Not Found&lt;/div&gt;;
    }
  }
}
</code></pre>

<p>the <code>loadMystuff</code> essentially gives me an <code>eKey</code> which I can use to call <code>fetchSList</code>, which calls <code>fetch</code></p>

<p>I want to mock <code>fetch</code> and make it return an array of strings, but I haven't had any luck achieving that.</p>

<p>My test script looks like</p>

<pre><code>describe(&lt;MyList /&gt;, () =&gt; {
    let wrapper;
    let eKey = 'some_str';
    it(""should have some listed items"", () =&gt; {
        wrapper = shallow(&lt;MyList loadMystuff={loadMystuff()}
                                       eKey={eKey}/&gt;
        );
        expect(wrapper.find(""div"").find(""ul"").find(""li"").length).toBeGreaterThan(0);
})
)
</code></pre>

<p>How do I make the fetch command return an array like <code>['abc', 'def', 'ghi']</code>?</p>

<p><strong>EDIT:</strong></p>

<p>after reading <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 come up with</p>

<pre><code>it(""should have some listed items"", () =&gt; {
        window.fetch = jest.fn().mockImplementation(() =&gt;
            Promise.resolve(mockResponse(200, null, '[""abc"", ""def""]')));
        return store.dispatch(MyList(loadMystuff=loadMystuff(), eKey=eKey))
            .then(() =&gt; {
                const expectedActions = store.getActions();
                console.log('expectedActions', expectedActions);
            });
        })
</code></pre>

<p>but this doesn't seem to work</p>

<p><strong>EDIT2:</strong></p>

<p>I'm now investigating <code>fetch-mock</code> package.</p>

<p>My function is still <code>fetchSList</code> where there's a <code>fetch</code> in it. I'm running the test as</p>

<pre><code>let eKey = 'some_key';

describe(&lt;MyList /&gt;, () =&gt; {
    fetchMock.get('*', '[""abc"", ""def""]');
    it(""should have some listed items"", () =&gt; {
        wrapper = shallow(&lt;MyList loadMyStuff={loadMyStuff()}
                                       eKey={eKey}/&gt;
        );
    expect(wrapper.find(""div"").find(""ul"").find(""li"")).toBe('something_something');
</code></pre>

<p>and it's returning an object instead of some form of string. jest is nice enough to print out what's in the object and there's nothing I expect, which is <code>[""abc"", ""def""]</code></p>
",https://stackoverflow.com/questions/51791752/jest-test-mock-mock-fetch-inside-another-function,"['reactjs', 'jestjs']",1031,TRUE,2,1
How to write do {} catch {} in Xcode unit test with 100% code coverage,"<p>I'm relatively new to unit testing and I'm hoping to achieve as close to 100% code coverage as possible, the do {} catch {} pattern is giving me grief trying to reach that goal.</p>

<p>Given this piece of code:</p>

<pre><code>func testUrlRequest_WithAuthenticationNoToken_ExpectingAuthenticationFailure() {
        let mockController = MockAuthenticationController()
        mockController.token = nil
        Server.authenticationController = mockController
        do {
            _ = try Server.urlRequestWithHeaders(to: arbitraryEndpoint, excludeBearerToken: false)
            XCTFail(""Expected throw when no token is present"")
        } catch {
            XCTAssertEqual(error as? Server.Errors, .authenticationFailure)
        }
    }
</code></pre>

<p>The Server.urlRequestwithHeaders() method properly throws an error which gets caught by the catch {} block, but Xcode gives me this result for code coverage:</p>

<p><a href=""https://i.stack.imgur.com/nyG4l.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/nyG4l.png"" alt=""xcode code coverage not 100%""></a></p>

<p>Seems it has two issues, first a warning that XCTFail() will never be executed (the dashed red warning), then a 0 red coverage matching the last ""}"" in the code, so I'm assuming it's some auto-generated return code that never gets executed.</p>

<p>Is there any way to properly tell Xcode that a code path is absolutely not expected to be taken and therefore ignore it as far as code coverage? Or is there a better pattern to follow when you need to unit test exception generation?</p>
",https://stackoverflow.com/questions/52204616/how-to-write-do-catch-in-xcode-unit-test-with-100-code-coverage,"['swift', 'xcode', 'unit-testing', 'code-coverage']",977,TRUE,2,1
Python unittest mock: Is it possible to mock the value of the __init__&#39;s default arguments at test time?,"<p>I want to test a class created with default parameters by replacing the value of the default parameter during unit testing.</p>

<p>For example, I want the following line (throughout the code)
<code>
obj = SomeClass()
</code></p>

<p>To look like it was called with a parameter</p>

<p><code>
obj = SomeClass(overiden_parameter)
</code></p>

<p>One solution might be to create simple subclass:</p>

<p>```
def OriginalClass(object):</p>

<pre><code>def __init_(some_param=""default_value""):
    ...
</code></pre>

<p>```</p>

<p>```
def MockedOriginalClass(OriginalClass):</p>

<pre><code>def __init_():
    super(MockedOriginalClass, self).__init__(""some_other_value)
    ...
</code></pre>

<p>```</p>

<p>How to a mock/patch <code>OriginalClass</code> to be <code>MockedOriginalClass</code> thoughout the code? Keep in mind that I do want to keep functionality of the original class, the only one thing I want to change is it's default <code>__init__</code> parameter.</p>

<p>I feel this is a very simple thing to do with Mocking, I just didn't quite figure how to do it.</p>

<p>I found out about this question:
<a href=""https://stackoverflow.com/questions/24021491/python-unittest-mock-is-it-possible-to-mock-the-value-of-a-methods-default-arg"">Python unittest mock: Is it possible to mock the value of a method&#39;s default arguments at test time?</a></p>

<p>It's very close but I don't think the same trick can be applied to the <code>__init__</code> method.</p>
",https://stackoverflow.com/questions/50589552/python-unittest-mock-is-it-possible-to-mock-the-value-of-the-init-s-default,"['python', 'unit-testing', 'mocking']",979,TRUE,1,2
Include jars in pom.xml,"<p>So here is the scenario. 
I have a maven project for which I am using some(7) jars for unit testing. All these jars are present on maven remote/local(.m2) repository. and I have to add them individually as dependency. </p>

<p>I want to create a pom (parent) which contain these jars as dependency so that if I include this pom(parent) as dependency, all 7 dependencies are automatically resolved.</p>

<p>I tried this code but i think there are some issues with packaging type. (<code>pom</code> packaging didn't work either).</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;some.package&lt;/groupId&gt;
 &lt;artifactId&gt;full-PACK&lt;/artifactId&gt;
 &lt;version&gt;1.1&lt;/version&gt;
 &lt;packaging&gt;jar&lt;/packaging&gt;

 &lt;dependencies&gt;

  &lt;dependency&gt;
   &lt;groupId&gt;org.javassist&lt;/groupId&gt;
   &lt;artifactId&gt;javassist&lt;/artifactId&gt;
   &lt;version&gt;3.21.0&lt;/version&gt;
   &lt;scope&gt;test&lt;/scope&gt;
  &lt;/dependency&gt;

 &lt;!-- 6 more similar dependencies --&gt;

 &lt;/dependencies&gt;

&lt;/project&gt;
</code></pre>

<p>I want this pom to just act as pointer, and this should resolve dependencies in their respective packages not in package of this pom. I don't want to create a fat jar for this pom.</p>

<p>Is there a way in which I can use this pom as kind of pointer so that it just tells project to import those 7 jars?</p>
",https://stackoverflow.com/questions/49239918/include-jars-in-pom-xml,"['java', 'maven', 'jar', 'parent-child']",377,TRUE,1,1
Decoupling issue - improvements and alternatives,"<p>I'm into learning SOLID principles - especially Inversion Of Control-DI-Decoupling, and as I'm reviewing one of my codes, I noticed that this one method (see below) gets my attention.</p>

<p>This code will be called by any methods that needs to read the json file,  accepts string values that will be used to lookup on a json file. But as you can see(I simplified the code - excluded the exception handling for the sake of this topic), I'm not sure where to start(there are a lot of initializations or dependencies?? happening and I'm not sure where to start).</p>

<p>Could this method/scenario a good candidate to start with? Which do you think should I retain? and needs to be decoupled?</p>

<p>Thanks.</p>

<pre><code>public async Task&lt;object&gt; ReadJsonByKey(string jsonPath, string jsonKey)
{
    // First - is it okay to have an initialization at this stage?
    var value = new object();     

    // Second - is this fine to have this in the scope of this method?
    using (TextReader reader = File.OpenText(jsonPath))  
    {
        // Third -  Calling Jobject that accepts new instance of JsonTextReader
        var jObject = await JObject.LoadAsync(new JsonTextReader(reader)); 
        obj = jObject.SelectToken(jsonKey);
    }
    return value;
}
</code></pre>

<p>The reason also I asked this is because (based from the standards ) loosely-coupled stuff can be easily tested - i.e, Unit Testing</p>

<pre><code>[UnitTestSuite]
    [TestCase1]
        // Method should only be able to accept "".json"" or "".txt"" file

    [TestCase2]
        // JsonPath file is valid file system

    [TestCase3]
        // Method should be able to retrieve a node value based from a specific json and key

    [TestCase4]
        // Json-text file is not empty
</code></pre>
",https://stackoverflow.com/questions/51759322/decoupling-issue-improvements-and-alternatives,"['c#', 'asynchronous', 'json.net', 'solid-principles']",88,TRUE,1,3
How do I unit test a Vue.js component that relies on a complicated Vuex store and extends another component?,"<p>I am wondering how one goes about unit testing a component that uses a complicated Vuex store and extends another component.</p>

<p>Can someone please provide me with an example of how I might go about creating a test that simply asserts that a component that extends another component and relies on Vuex mounts and displays some simple text?</p>

<p>I've tried using <code>vue-test-utils</code> to <code>shallowMount</code> the component under test, but I can't get my test to fail because it has issues even building and mounting the component. As far as I can tell, this is a result of the component leveraging the extended component, and because both components rely on a complicated Vuex store.</p>

<p>Any kind of examples would be appreciated. Thanks.</p>

<p>EDIT:</p>

<p>For further context, our store is broken up into modules. Here is what the store definition file looks like:</p>

<pre><code>/* global phpvars */

import Vue from 'vue'
import Vuex from 'vuex'

import * as actions from './actions'
import * as getters from './getters'
import * as mutations from './mutations'

import acloverrides from '../../modules/acloverrides'
import api from '../../modules/api'
import callback from '../../modules/callback'
import clearlink from '../../modules/clearlink'
import configuration from '../../modules/configuration'
import customer from '../../modules/customer'
import drKeepAlive from '../../modules/drkeepalive'
import interaction from './modules/interaction'
import ivr from './modules/ivr'
import marketing from '../../modules/marketing'
import opportunities from './modules/opportunities'
import order from '../../modules/order'
import orderNotes from './modules/notes'
import products from '../../modules/products'
import sidebar from './modules/sidebar'
import sparks from './modules/sparks'
import training from '../../modules/training'
import transformers from '../../modules/transformers'
import user from '../../modules/user'

let brand = require('../brands/' + phpvars.brand.name + '/modules/brand').default
let forms = require('../brands/' + phpvars.brand.name + '/modules/forms').default

Vue.use(Vuex)

export default new Vuex.Store({
    modules: {
        acloverrides,
        api,
        brand,
        callback,
        clearlink,
        configuration,
        customer,
        drKeepAlive,
        forms,
        interaction,
        ivr,
        marketing,
        opportunities,
        order,
        orderNotes,
        products,
        sidebar,
        sparks,
        training,
        transformers,
        user
    },
    state: {
        availability: {
            status: false,
            results: {}
        },
        navigation: {
            enabled: phpvars.user.access.order.navigate,
            restrictTo: []
        },
        routes: [],
        router: {},
        editMode: false // Used to determine if the user has clicked the edit button on an existing order.
    },
    actions,
    getters,
    mutations
})
</code></pre>

<p>And here is my unit test file:</p>

<pre><code>import Vuex from 'vuex'
import { shallowMount, createLocalVue } from '@vue/test-utils'
import SelectedProducts from '../../resources/assets/js/components/formfields/products/SelectedProducts'
import BaseField from '../../resources/assets/js/components/BaseField'
import store from '../../resources/assets/js/orderform/store/index.js'

const Vue = createLocalVue()
Vue.use(Vuex)

describe('SelectedProducts', () =&gt; {
    fit('sanity check', () =&gt; {
      window.phpvars = {
        brand: {
          name: 'foobar'
        },
        user: {
          access: {
            order: {
              navigate: true
            }
          }
        }
      }
      const wrapper = shallowMount(SelectedProducts, {
        store: new Vuex.Store(store)
      })
        expect(wrapper.text()).toContain('Selected Products')
    })
})
</code></pre>
",https://stackoverflow.com/questions/52373240/how-do-i-unit-test-a-vue-js-component-that-relies-on-a-complicated-vuex-store-an,"['javascript', 'unit-testing', 'vue.js', 'vuex']",855,TRUE,1,1
Using NAudio.Lame,"<p>I'm new to C# and having a ball learning. I've built a text to speech console app for myself that i'm really happy with.</p>

<p>Because I'm so green, but getting a massive buzz from learning, I can't go past the code in this post by wjdavis5 without learning how to use it.</p>

<p>""
Install-Package NAudio.Lame
Code Snip: Mine obviously returns a byte[] - I have a separate save to disk method b/c I think it makes unit testing easier.</p>

<pre><code>public static byte[] ConvertWavToMp3(byte[] wavFile)
{

    using(var retMs = new MemoryStream())
    using (var ms = new MemoryStream(wavFile))
    using(var rdr = new WaveFileReader(ms))
    using (var wtr = new LameMP3FileWriter(retMs, rdr.WaveFormat, 128))
    {
        rdr.CopyTo(wtr);
        return retMs.ToArray();
    }
}
</code></pre>

<p>from this post:</p>

<p><a href=""https://stackoverflow.com/questions/19058530/change-format-from-wav-to-mp3-in-memory-stream-in-naudio"">change format from wav to mp3 in memory stream in NAudio</a></p>

<p>I understand the syntax, mostly, but I'm so green that I'm struggling to understand how to get the wavFile into the method.</p>

<p>Its basic C# stuff I'm obviously struggling with, and this is the first time I've been compelled to ask, but i just have to know! </p>

<p>Just look at that beautiful code!</p>

<p>Cheers
Andrew</p>
",https://stackoverflow.com/questions/51685230/using-naudio-lame,"['c#', 'mp3', 'text-to-speech', 'wav']",1974,TRUE,1,1
How to get results from method into spec.js testing file?,"<p>I have been given a challenge and must write code that passes tests that checks to see if my method produces a specific URL path string. My method correctly creates the URL path string but, since I have no experience with unit testing, I am not sure how the test attempt to evaluate my code. I was given the tests and must ensure that they pass when <code>npm test</code> is run. </p>

<p>I am mainly having difficulty seeing the results of my method in the spec.js file when I run <code>npm test</code>. The test I was given (below) creates an empty url string and then tests it, which seems strange. When I call the method itself by inserting <code>this.app.generateURLMethod</code> and saving its value to a variable, it says that that method has returned an undefined value. </p>

<p><strong>Here are two testing examples:</strong></p>

<p><strong>app.component.spec.ts</strong></p>

<pre><code>describe('API', () =&gt; {
       it('should add a greater than or equal to filter to the url', () =&gt; {
        const url = '';
        expect(url).toBe('/items?price_gte=100');
    });
    it('should add a less than filter to the url', () =&gt; {
        const url = '';
        expect(url).toBe('/items?price_lt=1000');
    });
});
</code></pre>

<p><strong>Here is my method that creates the URL string:</strong></p>

<p><strong>app.component.ts</strong></p>

<pre><code>import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

 userType = 'customer'; // Default user type is customer.
  lessThanValue;
  greaterThanValue;

  filterAdded;
  urlPathString;

constructor() {}

generateURLMethod(userType, greaterThanValue, lessThanValue, limitValue, offsetValue) {
    this.filterAdded = false;
    this.urlPathString = (`/${this.userType}`);

    if (greaterThanValue) {
        this.urlPathString += (`?price_gte=${greaterThanValue}`);
        this.filterAdded = true;
    }

    if (lessThanValue) {
      if (this.filterAdded === false) {
        this.urlPathString += (`?price_lt=${lessThanValue}`);
        this.filterAdded = true;
      } else {
        this.urlPathString += (`&amp;price_lt=${lessThanValue}`);
      }
    }
window.location.href = this.urlPathString;
</code></pre>

<p>}</p>
",https://stackoverflow.com/questions/49371208/how-to-get-results-from-method-into-spec-js-testing-file,"['angular', 'jasmine']",852,TRUE,1,1
Can you check if two classes are the same using Chai?,"<p>I am working on  project using Karma, Mocha, and Chai for unit testing and am running into an issue with matching two classes. Essentially, I have a <code>Root</code> class that creates, stores, and manages items of the <code>Child</code> class. However, this <code>Root</code> class also exposes the <code>Child</code> as a static property for standalone use.</p>

<h3>./src/Root.js:</h3>

<pre><code>import Child from './Child';

export class Root {
    constructor() {
        this.children = [];
    }

    addChild() {
        this.children.push(new Child());
    }

    static Child() {
        return Child;
    }
}
</code></pre>

<p>This part works; from manual testing, it appears that <code>Root.Child</code> is equivalent to <code>Child</code>. However, I'd like to add a unit test to ensure that this is always the case. And this is where I'm stuck.</p>

<h3>./test/root.spec.js:</h3>

<pre><code>import Root from './src/Root';
import Child from './src/Child';

describe('Root', () =&gt; {
    it('should be a class', () =&gt; {
        expect(Root).to.be.a('function'); // Passes
    });

    it('should expose Child as a static prop', () =&gt; {
        expect(Root).to.have.property('Child'); // Passes by itself
        expect(Root.Child).to.equal(Child); // Fails
    });
});
</code></pre>

<p>When I run this test, I get a failure stating: <code>expected [Function: Child] to equal [Function: Child]</code></p>

<p>I understand that the <code>Child</code> imported in Root is ""separate"" from the one imported in root.spec, so my question is, using Chai (and I suppose this could extend to JavaScript in general) is there a way to check of the two classes match? Or is there I better way I could be doing this?</p>
",https://stackoverflow.com/questions/49080818/can-you-check-if-two-classes-are-the-same-using-chai,"['javascript', 'unit-testing', 'mocha.js']",314,TRUE,1,1
Force relocation with realloc,"<p>I'm currently writing a heavily data oriented library in C. The last few hours I hunted for a segfault that was caused by a dangling pointer due to memory relocation with realloc somewhere deep inside the library. As this bug only occured due to a memory leak in another part of the library, I'm wondering if there's a way to make this class of bugs more reproducible.</p>

<p>I had the idea, that maybe there's a way to force realloc to relocate the allocated memory on every call. I would like to do this while unit testing to catch such bugs early.</p>

<p>Is there such a LD_PRELOAD library (or similiar) that hooks malloc/realloc/... calls in a way that it'll early crash for dangling pointers?</p>

<p>The library is intended to be cross platform, but I guess memory errors are one of the few portable things in C.</p>
",https://stackoverflow.com/questions/49692405/force-relocation-with-realloc,"['c', 'unit-testing', 'realloc']",246,TRUE,1,2
Mockito + Espresso + Dagger2 =&gt; ClassNotFoundException when running SDK is lower than target SDK,"<p>I came across this limitation when trying to mock a class that refers to classes present in SDK >= 26 and executed the test in a device running SDK 24.
I created a test app to better understand the problem.</p>

<pre><code>open class RandomStuff{

    @RequiresApi(Build.VERSION_CODES.O)
    fun createDefaultNotificationChannel(): NotificationChannel {
        return NotificationChannel(""test"", ""test"", NotificationManager.IMPORTANCE_DEFAULT)
    }

    fun testString(): String = ""This is a test string""
}
</code></pre>

<p>Note that the RandomStuff class refers to the NotificationChannel class, only found in SDK >=26.</p>

<p>The test object provided via Dagger is the following:</p>

<pre><code>@Module
class AppTestModule : AppModule() {

    @Provides
    override fun provideRandomStuff(): RandomStuff {

        return mock(RandomStuff::class.java)
    }
}
</code></pre>

<p><em>mock</em> will fail with this exception:
<em>java.lang.IllegalArgumentException: Could not create type
at provideRandomStuff(AppTestModule.kt)</em> ultimately caused by a
<em>ClassNotFoundException</em> thrown by ByteBuddy (a component used by Mockito).
I was able to work around this issue by adding some checks to my provide method:</p>

<pre><code>@Module
class AppTestModule : AppModule() {

    @Provides
    override fun provideRandomStuff(): RandomStuff? {
        if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.O) {
            return mock(RandomStuff::class.java)
        } else { 
            return null
        }
    }
}
</code></pre>

<p>This temporary solution is very intrusive since now, the production code has to take into consideration that RandomStuff may be null.
I call this a limitation since Mockito has always been promoted as a unit testing framework it does not seem that the Dagger + Espresso + Mockito is a fully supported combination.
Is there a more creative solution for this issue?</p>
",https://stackoverflow.com/questions/53306444/mockito-espresso-dagger2-classnotfoundexception-when-running-sdk-is-lower,"['android', 'mockito', 'dagger-2', 'byte-buddy']",88,FALSE,4,0
How to mock a Spark Scala DataFrame with a nested case-class schema?,"<p>How do I create/mock a Spark Scala dataframe with a case class nested inside the top level?</p>

<pre><code>root
 |-- _id: long (nullable = true)
 |-- continent: string (nullable = true)
 |-- animalCaseClass: struct (nullable = true)
 |    |-- name: string (nullable = true)
 |    |-- gender: string (nullable = true)
</code></pre>

<p>I am currently unit testing a function which outputs a dataframe in the above schema. To check equality, I used the toDF() which unfortunately gives a schema with nullable = true for ""_id"" in the mocked dataframe, thus making the test fail (Note that the ""actual"" output from the function has nullable = true for everything).</p>

<p>I also tried creating the mocked dataframe a different way which led to errors: <a href=""https://pastebin.com/WtxtgMJA"" rel=""nofollow noreferrer"">https://pastebin.com/WtxtgMJA</a></p>

<p>Here is what I tried in this approach: </p>

<pre><code>import org.apache.spark.sql.Encoders
val animalSchema = Encoders.product[AnimalCaseClass].schema

val schema = List(
  StructField(""_id"", LongType, true),
  StructField(""continent"", StringType, true),
  StructField(""animalCaseClass"", animalSchema, true)
)

val data = Seq(Row(12345L, ""Asia"", AnimalCaseClass(""tiger"", ""male"")), Row(12346L, ""Asia"", AnimalCaseClass(""tigress"", ""female"")))

val expected = spark.createDataFrame(
  spark.sparkContext.parallelize(data),
  StructType(schema)
)
</code></pre>

<p>I had to use this approach to make the nullable true for those fields where toDF makes the nullable false by default. </p>

<p>How could I make a dataframe with the same schema as the output of the mocked function and declare values which can also be a case class?</p>
",https://stackoverflow.com/questions/52393165/how-to-mock-a-spark-scala-dataframe-with-a-nested-case-class-schema,"['scala', 'apache-spark']",2028,TRUE,0,1
Embedded. H2 DB Auto Increment (Java Test Case),"<p>I have a Java Spring Application which has a MS SQL DB. For unit testing the DAO classes I'm using Embedded H2 DB to insert some dummy data into the H2 DB. But I'm struggling to get auto generation of the primary key working.</p>

<p>This is the create schema/table/Insert dummy data queries which is in a create.sql file in the resources folder in my Spring project dir :</p>

<pre><code>CREATE SCHEMA local_db AUTHORIZATION sa; 
CREATE TABLE local_db.test_db (
  id int(4) NOT NULL AUTO_INCREMENT,
  username varchar(25) NOT NULL,
  isActive varchar(1) NOT NULL,
  PRIMARY KEY (id)
);
</code></pre>

<p>Inserting dummy data </p>

<pre><code>INSERT INTO local_db.test_db VALUES (1,'TestDATA1','Y');
INSERT INTO local_db.test_db VALUES (2,'TestDATA2','Y');
INSERT INTO local_db.test_db VALUES (3,'TestDATA3','Y');
</code></pre>

<p>My test code reading this create.sql file which is creating the schema / table correctly with the dummy data.   </p>

<p>This is done in the test class setUp()</p>

<pre><code>DaoClassUnderTest daoClassUnderTest;
  public void setUp() throws Exception {
    EmbeddedDatabase db = new EmbeddedDatabaseBuilder().
    setType(EmbeddedDatabaseType.H2).
    addScript(""create.sql"").
    build(); 
    daoClassUnderTest  = new DaoClassUnderTest(db);
  }
</code></pre>

<p>But when I actually call the insert method on the DAO class (which is being tested), it inserts the data but it leaves the id field null without inserting any value in the id column. </p>

<pre><code>INSERT INTO local_db.test_db (username, isActive) VALUES (?,?);
</code></pre>

<p>How can I have the Auto increment working on the Embedded.H2 DB from the Junit test code?</p>
",https://stackoverflow.com/questions/49071975/embedded-h2-db-auto-increment-java-test-case,"['java', 'junit', 'h2']",847,FALSE,0,1
Java Junit Test with Hamcrest: cannot create compositional Matcher,"<p>I am new to unit testing in Java and am having a bit of trouble replicating something I performed in a tutorial.</p>

<p>I have an email class which has many properties, but among them is <code>firstName</code>.</p>

<pre><code>private final String firstName;
public String getFirstName() {
        return firstName;
}
</code></pre>

<p>The first name is set in the constructor in a standard fashion:</p>

<pre><code>this.firstName = firstName;
</code></pre>

<p>I've written a test to test if the email contains a first name. After set up the test looks like this:</p>

<pre><code>@Test
public void emailIsCreated() {
    assertThat(em1, hasProperty(""firstName""));
}
</code></pre>

<p>This test passes.
My problem is that I'm trying to extend the test with a compositional matcher to match the values of the firstname like so:</p>

<pre><code>@Test
public void emailIsCreated() {
    assertThat(em1, hasProperty(""firstName"", equalTo(""Jon"")));
}
</code></pre>

<p>But I keep getting a compile error that reads: </p>

<p><code>hasProperty (String) in HasProperty cannot be applied to (String, org.hamcrest.Matcher&lt;java.lang.String&gt;)</code></p>

<p>My intuition tells me it has a problem with equating the strings based on the message (and the fact that when I successfully preformed this before I was matching an int), but that doesn't seem right...
Does anybody know what I'm doing wrong here?</p>
",https://stackoverflow.com/questions/49588325/java-junit-test-with-hamcrest-cannot-create-compositional-matcher,"['java', 'unit-testing', 'junit', 'hamcrest']",247,TRUE,0,1
How do I fix my unit test methods when using auto generated test classes by InteliTest?,"<p>I am trying to understand <code>automated</code> test class generation in Visual Studio. I am using <code>Microsoft Plex Framework</code>. Here is the details of Pex framework. <a href=""https://www.microsoft.com/en-us/research/project/pex-and-moles-isolation-and-white-box-unit-testing-for-net/"" rel=""nofollow noreferrer"">https://www.microsoft.com/en-us/research/project/pex-and-moles-isolation-and-white-box-unit-testing-for-net/</a></p>
<p>I have used the code as shown below</p>
<pre><code>public class AuditRepository:BaseDataRepository&lt;AuditItem, int&gt;, IAuditRepository
{
    public AuditRepository(string connString, IContainerFactory containerFactory) : base(connString, containerFactory)
    {
    }

    public IEnumerable GetTopAudit(int topCount)
    {
        const string sql = &quot;SELECT TOP ({0}) * FROM audit ORDER BY CreatedTime DESC&quot;;
        return Query(string.Format(sql, topCount));
    }
}
</code></pre>
<p>I have used <code>InteliTest</code> to create <code>unit test</code> for above method and which automatically generated the <code>test files and methods</code> as shown below</p>
<pre><code>/// &lt;summary&gt;This class contains parameterized unit tests for AuditRepository&lt;/summary&gt;
[PexClass(typeof(AuditRepository))]
[PexAllowedExceptionFromTypeUnderTest(typeof(InvalidOperationException))]
[PexAllowedExceptionFromTypeUnderTest(typeof(ArgumentException), AcceptExceptionSubtypes = true)]
[TestClass]
public partial class AuditRepositoryTest
{
    /// &lt;summary&gt;Test stub for GetTopAudit(Int32)&lt;/summary&gt;
    [PexMethod]
    public IEnumerable GetTopAuditTest([PexAssumeUnderTest]AuditRepository target, int topCount)
    {
        IEnumerable result = target.GetTopAudit(topCount);
        return result;
        // TODO: add assertions to method AuditRepositoryTest.GetTopTest(AuditRepository, Int32)
    }
}
</code></pre>
<p>Now, when I tried to run the test using <code>InteliTest</code> , it shows warnings and suggested to fix by adding below code [Basically below code generated when clicked on 'Fix' button]</p>
<pre><code>public static partial class AuditRepositoryFactory
{
    /// &lt;summary&gt;A factory for Radiometer.RadCon.RAP.Repository.AuditRepository instances&lt;/summary&gt;
    [PexFactoryMethod(typeof(AuditRepository))]
    public static AuditRepository Create(string connString_s, IContainerFactory containerFactory_iContainerFactory)
    {
        AuditRepository auditRepository
           = new AuditRepository(connString_s, containerFactory_iContainerFactory);
        return auditRepository;

        // TODO: Edit factory method of AuditRepository
        // This method should be able to configure the object in all possible ways.
        // Add as many parameters as needed,
        // and assign their values to each field by using the API.
    }
}
</code></pre>
<p>I am not able to understand what's going on behind the screen, what does it mean by below commented lines</p>
<blockquote>
<p>// TODO: Edit factory method of AuditRepository</p>
<p>// This method should be able to configure the object in all possible ways.</p>
<p>// Add as many parameters as needed,</p>
<p>// and assign their values to each field by using the API.</p>
</blockquote>
",https://stackoverflow.com/questions/51378243/how-do-i-fix-my-unit-test-methods-when-using-auto-generated-test-classes-by-inte,"['c#', 'unit-testing', 'visual-studio-2017', 'pex']",244,TRUE,0,1
How to XCTAssertEqual on Alamofire response?,"<p>I am trying to make unit testing for my API with Alamofire as the rest framework. I have added the pod dependencies and everything in the Podfile and there is no error regarding missing modules or something. Currently as an example I am trying to hit google homepage and on response I am trying to evaluate the response code with <strong>XCRAssertEqual</strong>. The function is working fine if I use in view controller but it's not working in test class. By not working I meant it's giving <strong>true</strong> for both cases, for both response code being equal to <strong>.success</strong> and <strong>.filure</strong>. What can be the reason of this? Below are my TestClass where function is defined and the test case class where it is being used</p>

<pre><code>import Foundation
import Alamofire

class TestingClass {

    private init(){

    }

    static let sharedInstance = TestingClass()

    func getSquare(number:Int)-&gt;Int{
        return number * number
    }

    func getGoogleResponse(completion:@escaping (_ rest:Int)-&gt;Void){

        Alamofire.request(""https://google.com"").responseString { response in
            var result = -1
            switch response.result {
            case .success:
                result = 0
            case .failure(let error):
                result = 1
            }
            completion(result)
        }

    }

}
</code></pre>

<p>test case class</p>

<pre><code>import XCTest
@testable import MyApp

class MyAppTests: XCTestCase {

    func testSquare(){
        XCTAssertEqual(TestingClass.sharedInstance.getSquare(number:2),6)
    }

    func testGoogle(){
        TestingClass.sharedInstance.getGoogleResponse { (res) in
            print(""ANURAN \(res)"")
            XCTAssertEqual(res, 0)
        }
    }
}
</code></pre>

<p>First test case is working fine as it has nothing to do with Alamofire but second time never fails.</p>
",https://stackoverflow.com/questions/52004806/how-to-xctassertequal-on-alamofire-response,"['ios', 'swift', 'unit-testing', 'testing', 'alamofire']",618,TRUE,0,1
"Can Aggregate Root Factory create the root, and it&#39;s internal classes?","<p>Currently, my aggregates and value objects have protected constructors and almost all of them are being created by static factory methods inside the aggregate with descriptive names. It creates a nice <strong>DSL</strong> and pretty encapsulated model <strong>but makes the unit testing painful</strong> (if the domain model creation fails, the service/command handler will be marked as failed as well). Introducing factory methods on the other hand for each entity, and value object forces me to inject a factory interface per entity/value object into the service.</p>

<p>Is it ok to create a factory service per aggregate root with a factory method per entity/value object? 
Here's an example of a factory service which creates a company aggregate root, and it's internal entities/VOs:</p>

<pre><code>public class CompanyFactory : ICompanyAggregateRootFactory
{
    public Company CreateCompany(...){}
    public Employee CreateEmployee(...){}
    public CEO CreateCEO(...){}
    ....

}
</code></pre>

<p>Is there any other way which enforces the same level of encapsulation and <strong>DSL</strong> clarity without making the unit tests depending on one another? </p>
",https://stackoverflow.com/questions/51591083/can-aggregate-root-factory-create-the-root-and-its-internal-classes,"['c#', 'unit-testing', 'domain-driven-design', 'dsl', 'aggregateroot']",382,FALSE,0,1
Publishing multiple cobertura coverages with TFS CI,"<p>I have a monorepo project, created with lerna. And, I use Karma+Jasmine for the unit testing. The project structure looks as follows:</p>
<pre><code>|-packages
| |-package1
| | |-coverage
| | | |-cobertura
| | | | |-coverage.xml  // here goes the coverage report in cobertura format
| | | |-Browser1
| | | | |-html          // here goes the reports in html (istanbul) for Browser 1
| | | |-Browser2
| | |   |-html          // here goes the reports in html (istanbul) for Browser 2
| | |-src
| | |-tests
| |-package2
| | |-coverage
| | | |-cobertura
| | | | |-coverage.xml
| | | |-Browser1
| | | | |-html        
| | | |-Browser2
| | |   |-html        
| | |-src
| | |-tests
| .
| .
| .
|-karma.conf.js
</code></pre>
<p>The test setup is working properly and generating the html reports as well as the <code>coverage.xml</code> in Cobertura format inside the each individual package. In TFS CI, I have a &quot;Publish Code Coverage Results&quot; build step to publish the coverage results with following values for different options:</p>
<ul>
<li>Code Coverage Tool: <code>Cobertura</code></li>
<li>Summary File: <code>$(System.DefaultWorkingDirectory)\packages\*\coverage\cobertura\coverage.xml</code></li>
<li>Report Directory: <code>$(System.DefaultWorkingDirectory)\packages\*\coverage</code> (for HTML reports)</li>
</ul>
<p>However, the build step warns about following</p>
<blockquote>
<p>Multiple file or directory matches were found. Using the first match: C:\MyAgent\path\to\packages\package1\coverage\cobertura\coverage.xml</p>
<p>Multiple file or directory matches were found. Using the first match: C:\MyAgent\path\to\packages\package1\coverage</p>
</blockquote>
<p>Naturally it also shows the coverage results for only one package. Is there any way to publish all coverage reports without adding a build step in CI for each package?</p>
",https://stackoverflow.com/questions/49380451/publishing-multiple-cobertura-coverages-with-tfs-ci,"['javascript', 'tfs', 'cobertura', 'istanbul', 'monorepo']",2550,TRUE,4,1
Typescript: Visibility within the same Namespace across multiple files,"<p>Can you help me out - is this a bug or am I misunderstanding the documentation? </p>

<p>I have two files in a namespace - you'll find a simpler version below.</p>

<p>The Typescript docs <a href=""https://www.typescriptlang.org/docs/handbook/namespaces.html"" rel=""nofollow noreferrer"">state that</a> <em>""Even though the files are separate, they can each contribute to the same namespace and can be consumed as if they were all defined in one""</em>. 
Therefore I would assume that a class from one file could access another file from within the same namespace even if it was not exported. (Because that would be the case if they were defined in the same place) </p>

<p>However, tsc complains that it can't find the name ""Dispatcher"". Why does this happen? Am I misunderstanding the documentation at this point? Or is it just a compiler bug? Would be a shame if it was the former, because namespace only visibility would help a lot for unit testing and encapsulating.</p>

<p>Code: </p>

<p>(code changed for simplicity. If syntax errors are present, they are caused by that): </p>

<p><strong>Application.ts:</strong></p>

<pre><code>/// &lt;reference path=""Dispatcher.ts""/&gt;
namespace Application {
    export class Application {
        constructor() {
            new Dispatcher(); 
        }
    }
}
</code></pre>

<p><strong>Dispatcher.ts:</strong></p>

<pre><code>namespace Application {
    class Dispatcher { /* ... */ }
}
</code></pre>
",https://stackoverflow.com/questions/52429856/typescript-visibility-within-the-same-namespace-across-multiple-files,"['typescript', 'namespaces']",860,TRUE,4,1
How to make symfony display exceptions in functional testing with phpunit,"<p>When I run unit tests with PhpUnit in console all exceptions are display immediately there. However when I moved to functional testing I cannot see exceptions which occur.</p>

<p>First I tried symfony <code>WebTestCase</code> as it was said <a href=""https://symfony.com/doc/3.2/testing.html"" rel=""nofollow noreferrer"">here</a>. So I called <code>$client</code> with needed parameters and I have a response. But it took time to me to understand that this behaviour is just like I manually open a page I want to test. And a response from <code>$client-&gt;request</code> contains text (html). Yes errors are show there but there are pretty much html and it is really hard to find the exception. Yes, I can use <code>$crawler-&gt;filter('.text-exception')-&gt;first()-&gt;text()</code> but I want so that exception was visible like in unit test. When I tested commands exceptions are shown by PhpUnit as well as normal.</p>

<p>I tried to copy code from <code>web/app_dev.php</code> to test case. But it is the same. I have only html response.</p>

<p>So how can I make it so that PhpUnit display exceptions in functional testing like in unit testing?</p>
",https://stackoverflow.com/questions/49469246/how-to-make-symfony-display-exceptions-in-functional-testing-with-phpunit,"['symfony', 'phpunit']",1460,TRUE,4,1
How to replace component-scoped service with spy object in Angular 6?,"<p>Currently I'm (Context: I am Angular beginner) developing a simple login-screen in a larger project with Angular 6 also using jasmine-tests. For the communication with the backend we use websockets which connect to different endpoints. For that reason I have to define component-scoped providers for two services:</p>

<pre><code>// user-password-form.component.ts
@Component({
  selector: 'app-user-password-form',
  templateUrl: './user-password-form.component.html',
  styleUrls: ['./user-password-form.component.scss'],
  providers: [WebSocketService, AuthenticationService]
})
</code></pre>

<p>Now I want to test some functionality of <code>user-password-form.component.ts</code> by mocking <code>AuthenticationService</code> which uses <code>WebSocketService</code>. WebSocketService is also used by different other Services. The user-password-form.component only uses <code>AuthenticationService</code>, but due to the hierarchic DI, I also have to provide the WebSocketService at the component scope in order to receive an own instance. </p>

<p>Now, with jasmine, I want to test the functionality of the component by defining the following spec</p>

<pre><code>const authServiceSpy
    = jasmine.createSpyObj('AuthenticationService', ['authenticate']);


  beforeEach(() =&gt; {

    TestBed.configureTestingModule({
      declarations: [UserPasswordFormComponent],
      providers: [LoggerService, FormBuilder,
        {provide: AuthenticationService, useValue: authServiceSpy}
      ],
      imports: [RouterModule],
      schemas: [NO_ERRORS_SCHEMA]
    })
</code></pre>

<p>However, in this case the spy isn't injected instead of the real authenticationService. Consequently, I am not able to run the following line:</p>

<pre><code>expect(authService.authenticate.calls.mostRecent().args[0]).toEqual(authObj);
</code></pre>

<p>How can I force the Injection-mechanism to use the spyObject instead of the real AuthenticationService for the purpose of unit testing?</p>
",https://stackoverflow.com/questions/51649675/how-to-replace-component-scoped-service-with-spy-object-in-angular-6,"['angular', 'dependency-injection', 'scope', 'jasmine', 'angular-services']",1090,TRUE,4,1
Django rest-framework : Unit tests are using the production database,"<p>I'm currently working on a small app to learn about Django and Django-Rest-Framework and stumbled across a small issue related to unit testing.</p>

<p>I just have two applications in my project : api (which provides a RESTful api to mess around with the DB), and web (which just sends queries to the api and applies a layout to render web pages). Nothing complicated.
However, when launching unit tests, those testing the api work as expected and seem to use the temporary DB, but those testing the web application seem to use the production database.</p>

<p>Here is my model (api.models) :</p>

<pre><code>class User(AbstractUser):
    country = models.CharField(max_length=32, verbose_name=""Country of origin"", name=""country"", blank=True, null=True)
    phone = models.CharField(max_length=32, verbose_name=""Phone"", name=""phone"", blank=True, null=True)
    field = models.CharField(max_length=32, verbose_name=""Field of occupation"", name=""field"", blank=True, null=True)
    occupation = models.CharField(max_length=32, verbose_name=""Occupation"", name=""occupation"", blank=True, null=True)
    birthdate = models.DateField(verbose_name=""Birth Date"", name=""birthdate"", auto_now_add=False, auto_now=False, blank=True, null=True)
    description = models.TextField(verbose_name=""Description"", name=""description"", blank=True, null=True)

    def __str__(self):
        return self.username
</code></pre>

<p>Here is is the web view which causes problems (web.views):</p>

<pre><code>def profile(request, usrname):
    """"""Handles profile page behaviour and rendering""""""
    stdlogger.info(""PROFILE : request for home page"")

    if request.method == ""GET"":
        # retrieve single profile
        stdlogger.debug(""PROFILE_get : request for profile of '"" + usrname + ""' retrieval"")
        r = get(""http://localhost:8000"" + reverse(""get_delete_update_profile"", kwargs={'usrname': usrname}))
        if r.status_code == status.HTTP_200_OK:
            form = UserForm(data=r.json())

            if not form.is_valid():
                # login data is invalid
                stdlogger.error(""PROFILE_get : form data is invalid"")
                for field, errors in form.errors.items():
                    for error in errors:
                        stdlogger.error(field + "" -&gt; "" + error)
                        messages.add_message(request, messages.ERROR, field + "" : "" + error)

            return render(request, 'web/profile.html', {'form': form, 'usrname': usrname, })
        else:
            stdlogger.error(""PROFILE_get : profile for '"" + usrname + ""' could not be found"")
            return HttpResponseNotFound()
</code></pre>

<p>And here is a unit test which causes problems (web.tests.test_views) :</p>

<pre><code>from django.test import TestCase, Client

class getProfileTest(TestCase):
""""""Test module for GET requests on Profile page""""""

    def setUp(self):
        self.client = Client(enforce_csrf_checks=False)
        self.john = get_user_model().objects.create(
        username='john', password='test', first_name='John', last_name='Doe', country='UK', email='test@test.com',
        phone='+44123456789', field='Diplomacy', occupation='Spy', birthdate='1963-05-01', description='Tall guy')

    def test_valid_get_profile(self):
        response = self.client.get(reverse('profile', kwargs={'usrname': self.john.username}))
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertTemplateUsed(response, 'web/profile.html')
</code></pre>

<p>This test returns a Http code 404 and when I run a logger through it, it shows production users, not 'John Doe'</p>

<p>Would anyone have any idea? :)</p>
",https://stackoverflow.com/questions/49367093/django-rest-framework-unit-tests-are-using-the-production-database,"['django', 'unit-testing', 'django-rest-framework']",274,FALSE,0,0
How to unit test non-exported class in UWP component (C++/WinRT),"<p>I'm looking for some guidance on my strategy for unit testing UWP components.</p>

<p>I am developing a UWP component using the C++/WinRT projection. This component contains a helper class that manages communication with a Bluetooth device. I would like to write unit tests for that helper class (BthDevice) without exporting them to the UWP component's interface.</p>

<p>I started by following some guidelines for testing non-exported DLL classes. Specifically, I created a new UWP unit test project. I explicitly added my project's include directory, included BthDevice.h, and added the class' BthDevice.obj to the linker settings. I fought a few linker errors, and now it's falling over because I'm using precompiled headers in the UWP component. I've given up for now.</p>

<p>It feels like this should be a simple task, and that I'm going about it the wrong way. Any guidance is welcome! Thanks.</p>
",https://stackoverflow.com/questions/53225095/how-to-unit-test-non-exported-class-in-uwp-component-c-winrt,"['visual-c++', 'uwp', 'c++-winrt']",117,FALSE,0,0
Testing Hapi routes with Jest hangs if the test fails,"<p>I'm working on something where I'm using Hapi as a web server for a REST API, and I'm using Jest for unit testing. I've just set it up to test the REST routes themselves - by using <code>server.inject</code> on the created Hapi server.</p>

<p>This works fantastically, as long as the tests pass. If the tests fail then everything runs to completion but the process doesn't terminate.</p>

<p>For reference, my test looks like this:</p>

<pre><code>// @flow

import createServer from '../server';

describe('Hapi Healthchecks', () =&gt; {
    let server;

    beforeEach(async () =&gt; {
        server = await createServer();
    });

    test('Hapi Healthchecks respond correctly', async () =&gt; {
        const response = await server.inject({
            method: 'GET',
            url: '/health',
        });

        expect.assertions(1);
        expect(response.statusCode).toBe(200);
    });
});
</code></pre>

<p><code>createServer</code> returns the result of <code>Glue.compose</code>, so it's a configured but not-yet-started Hapi server. I don't start the server in the tests - there's no need - and so there's no call to <code>server.stop()</code>. However, if I add either or both of those in then it makes no difference.</p>

<p>As long as the test passes the assertion then everything is fine. If the test fails for any reason then everything else still runs - including <code>afterEach</code> and <code>afterAll</code> calls, but the process simply fails to exit.</p>

<p>Any suggestions for what I'm missing to get this working correctly?</p>
",https://stackoverflow.com/questions/50319667/testing-hapi-routes-with-jest-hangs-if-the-test-fails,"['node.js', 'jestjs', 'hapi.js']",1459,FALSE,4,1
How to mock React Navigation&#39;s navigation prop for unit tests with TypeScript in React Native?,"<p>I'm building a React Native app with TypeScript. For my navigation I use React Navigation and for my unit testing I use Jest and Enzyme.</p>

<p>Here is the (stripped down) code for one of my screen (LoadingScreen.tsx):</p>

<pre><code>import styles from ""./styles"";
import React, { Component } from ""react"";
import { Text, View } from ""react-native"";
import { NavigationScreenProps } from ""react-navigation"";

// Is this correct?
export class LoadingScreen extends Component&lt;NavigationScreenProps&gt; {
// Or should I've done:
// export interface Props {
//   navigation: NavigationScreenProp&lt;any, any&gt;;
// }

// export class LoadingScreen extends Component&lt;Props&gt; {
  componentDidMount = () =&gt; {
    this.props.navigation.navigate(""LoginScreen"");
  };

  render() {
    return (
      &lt;View style={styles.container}&gt;
        &lt;Text&gt;This is the LoadingScreen.&lt;/Text&gt;
      &lt;/View&gt;
    );
  }
}

export default LoadingScreen;
</code></pre>

<p>When trying to test the screens I came across a problem. The screens expects a prop with a type of NavigiationScreenProps because I'm accessing React Navigations <code>navigation</code> prop. Here is the testing file's code (LoadingScreen.test.tsx):</p>

<pre><code>import { LoadingScreen } from ""./LoadingScreen"";
import { shallow, ShallowWrapper } from ""enzyme"";
import React from ""react"";
import { View } from ""react-native"";
import * as navigation from ""react-navigation"";

const createTestProps = (props: Object) =&gt; ({
  ...props
});

describe(""LoadingScreen"", () =&gt; {
  describe(""rendering"", () =&gt; {
    let wrapper: ShallowWrapper;
    let props: Object;
    beforeEach(() =&gt; {
      props = createTestProps({});
      wrapper = shallow(&lt;LoadingScreen {...props} /&gt;);
    });

    it(""should render a &lt;View /&gt;"", () =&gt; {
      expect(wrapper.find(View)).toHaveLength(1);
    });
  });
});
</code></pre>

<p>The problem is, that <code>LoadingScreen</code> expects a <code>navigation</code> prop.</p>

<p>I get the error:</p>

<pre><code>[ts]
Type '{ constructor: Function; toString(): string; toLocaleString(): string; valueOf(): Object; hasOwnProperty(v: string | number | symbol): boolean; isPrototypeOf(v: Object): boolean; propertyIsEnumerable(v: string | ... 1 more ... | symbol): boolean; }' is not assignable to type 'Readonly&lt;NavigationScreenProps&lt;NavigationParams, any&gt;&gt;'.
  Property 'navigation' is missing in type '{ constructor: Function; toString(): string; toLocaleString(): string; valueOf(): Object; hasOwnProperty(v: string | number | symbol): boolean; isPrototypeOf(v: Object): boolean; propertyIsEnumerable(v: string | ... 1 more ... | symbol): boolean; }'.
(alias) class LoadingScreen
</code></pre>

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

<p>I think I somehow have to mock the <code>navigation</code> prop. I tried doing that (as you can see I imported <code>*</code> from React Navigation in my test), but couldn't figure out. There is only <code>NavigationActions</code> that is remotely useful but it only includes <code>navigate()</code>. TypeScript expects everything, even the state, to be mocked. How can I mock the <code>navigation</code> prop? </p>

<p><strong>Edit 1:</strong> Is the approach of using <code>NavigationScreenProps</code> even correct or should I use the <code>interface Props</code> approach? If yes how would you then mock than (it results in the same error).</p>

<p><strong>Edit 2:</strong>
Using the second approach with the interface and </p>

<pre><code>export class LoadingScreen extends Component&lt;Props, object&gt;
</code></pre>

<p>I was able to ""solve"" this problem. I literally had to mock every single property of the navigation object like this:</p>

<pre><code>const createTestProps = (props: Object) =&gt; ({
  navigation: {
    state: { params: {} },
    dispatch: jest.fn(),
    goBack: jest.fn(),
    dismiss: jest.fn(),
    navigate: jest.fn(),
    openDrawer: jest.fn(),
    closeDrawer: jest.fn(),
    toggleDrawer: jest.fn(),
    getParam: jest.fn(),
    setParams: jest.fn(),
    addListener: jest.fn(),
    push: jest.fn(),
    replace: jest.fn(),
    pop: jest.fn(),
    popToTop: jest.fn(),
    isFocused: jest.fn()
  },
  ...props
});
</code></pre>

<p>The question remains: Is this correct? Or is there a better solution?</p>

<p><strong>Edit 3:</strong>
Back when I used JS, it was enough to mock only the property I needed (often just navigate). But since I started using TypeScript, I had to mock every single aspects of navigation. Otherwise TypeScript would complain that the component expects a prop with a different type.</p>
",https://stackoverflow.com/questions/52569447/how-to-mock-react-navigations-navigation-prop-for-unit-tests-with-typescript-in,"['typescript', 'unit-testing', 'react-native', 'jestjs', 'react-navigation']",52723,TRUE,50,5
How to write a proper unit test for Elasticsearch in Java,"<p><strong>Overview:</strong></p>

<p>I'm totally new to Elastic search testing and I'm gonna add proper unit tests. The project compatibilities are as follow:</p>

<ul>
<li>Java 8</li>
<li>Elasticsearch 6.2.4</li>
<li>Project uses low level rest client for fetching data from ES</li>
</ul>

<p>More info about ES configurations is as follow:</p>

<pre><code>import static java.net.InetAddress.getByName;
import static java.util.Arrays.stream;

import java.net.UnknownHostException;
import java.util.Map;
import java.util.Objects;

import javax.inject.Inject;

import org.apache.http.HttpHost;

import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import au.com.api.util.RestClientUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Configuration
public class ElasticConfiguration implements InitializingBean{

    @Value(value = ""${elasticsearch.hosts}"")
    private String[] hosts;

    @Value(value = ""${elasticsearch.httpPort}"")
    private int httpPort;

    @Value(value = ""${elasticsearch.tcpPort}"")
    private int tcpPort;

    @Value(value = ""${elasticsearch.clusterName}"")
    private String clusterName;

    @Inject
    private RestClientUtil client;

    @Bean
    public RestHighLevelClient restHighClient() {

        return new RestHighLevelClient(RestClient.builder(httpHosts()));
    }

    @Bean
    @Deprecated
    public RestClient restClient() {

        return RestClient.builder(httpHosts()).build();

    }

    /**
     * @return TransportClient
     * @throws UnknownHostException
     */
    @SuppressWarnings(""resource"")
    @Bean
    public TransportClient transportClient() throws UnknownHostException{

        Settings settings = Settings.builder()
                .put(""cluster.name"", clusterName).build();

        return new PreBuiltTransportClient(settings).addTransportAddresses(transportAddresses());
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        log.debug(""loading search templates..."");
        try {
            for (Map.Entry&lt;String, String&gt; entry : Constants.SEARCH_TEMPLATE_MAP.entrySet()) {
                client.putInlineSearchTemplateToElasticsearch(entry.getKey(), entry.getValue());
            }
        } catch (Exception e) {
            log.error(""Exception has occurred in putting search templates into ES."", e);
        }
    }

    private HttpHost[] httpHosts() {
        return stream(hosts).map(h -&gt; new HttpHost(h, httpPort, ""http"")).toArray(HttpHost[]::new);
    }

    private TransportAddress[] transportAddresses() throws UnknownHostException {
        TransportAddress[] transportAddresses = stream(hosts).map(h -&gt; {
            try {
                return new TransportAddress(getByName(h), tcpPort);
            } catch (UnknownHostException e) {
                log.error(""Exception has occurred in creating ES TransportAddress. host: '{}', tcpPort: '{}'"", h, tcpPort, e);
            }
            return null;
        }).filter(Objects::nonNull).toArray(TransportAddress[]::new);

        if (transportAddresses.length == 0) {
            throw new UnknownHostException();
        }
        return transportAddresses;
    }
}
</code></pre>

<hr>

<p><strong>Issue:</strong></p>

<p>I don't know how to Mock ES or how to test ES without running an standalone ES on my machine. Please use the following class as an example and let me know how could I write a testcase (unit test not integration) for <code>getSearchResponse</code> method:</p>

<pre><code>    import java.util.Arrays;
    import java.util.List;
    import java.util.Map;
    import java.util.stream.Collectors;

    import org.elasticsearch.action.search.SearchRequest;
    import org.elasticsearch.action.search.SearchResponse;
    import org.elasticsearch.client.transport.NoNodeAvailableException;
    import org.elasticsearch.client.transport.TransportClient;
    import org.elasticsearch.script.ScriptType;
    import org.elasticsearch.script.mustache.SearchTemplateRequestBuilder;
    import org.elasticsearch.search.Scroll;
    import org.elasticsearch.search.aggregations.Aggregation;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.MessageSource;
    import org.springframework.stereotype.Repository;
    @Slf4j
@Repository
@NoArgsConstructor
public abstract class NewBaseElasticsearchRepository {

    @Autowired
    protected NewIndexLocator newIndexLocator;

    @Value(value = ""${elasticsearch.client.timeout}"")
    private Long timeout;

    @Autowired
    protected TransportClient transportClient;

    @Autowired
    protected ThresholdService thresholdService;

    @Autowired
    protected MessageSource messageSource;

    /**
     * @param script         the name of the script to be executed
     * @param templateParams a map of the parameters to be sent to the script
     * @param indexName      the index to target (an empty indexName will search all indexes)
     *
     * @return a Search Response object containing details of the request results from Elasticsearch
     *
     * @throws NoNodeAvailableException thrown when the transport client cannot connect to any ES Nodes (or Coordinators)
     * @throws Exception                thrown for all other request errors such as parsing and non-connectivity related issues
     */
    protected SearchResponse getSearchResponse(String script, Map&lt;String, Object&gt; templateParams, String... indexName) {
        log.debug(""transport client &gt;&gt; index name --&gt; {}"", Arrays.toString(indexName));

        SearchResponse searchResponse;

        try {
            searchResponse = new SearchTemplateRequestBuilder(transportClient)
                .setScript(script)
                .setScriptType(ScriptType.STORED)
                .setScriptParams(templateParams)
                .setRequest(new SearchRequest(indexName))
                .execute()
                .actionGet(timeout)
                .getResponse();
        } catch (NoNodeAvailableException e) {
            log.error(ELASTIC_SEARCH_EXCEPTION_NOT_FOUND, e.getMessage());
            throw new ElasticSearchException(ELASTIC_SEARCH_EXCEPTION_NOT_FOUND);
        } catch (Exception e) {
            log.error(ELASTIC_SEARCH_EXCEPTION, e.getMessage());
            throw new ElasticSearchException(ELASTIC_SEARCH_EXCEPTION);
        }

        log.debug(""searchResponse ==&gt; {}"", searchResponse);
        return searchResponse;
    }
</code></pre>

<p>So, I would be grateful if you could have a look on the example class and <em>share your genuine solutions with me here about how could I mock <code>TransportClient</code> and get a proper response from <code>SearchResponse</code> object.</em>  </p>

<hr>

<p><strong>Note:</strong> </p>

<ul>
<li>I tried to use <code>ESTestCase</code> from <code>org.elasticsearch.test:framework:6.2.4</code> but faced <code>jar hell</code> issue and could't resolve it. In the meantime, I could't find any proper docs related to that or Java ES unit testing, in general. </li>
</ul>
",https://stackoverflow.com/questions/53147850/how-to-write-a-proper-unit-test-for-elasticsearch-in-java,"['java', 'unit-testing', 'spring-boot', 'elasticsearch', 'junit']",5204,FALSE,3,0
Spock with DbUnit test cases slowness,"<p>We have implemented <strong>Spock + Db unit</strong> framework as a part of automated unit testing.</p>

<p>We have now <strong>2000 test cases (Features) for 150 Specifications with DbUnit</strong>. </p>

<p>Here, We add required entries in the DB and then test the behavior of each method.</p>

<p>What We have observed that it takes around 2 Hrs and 30 Mins around time to execute these test cases. </p>

<p>I have timestamped <code>setup</code> fixture and added time stamp in a feature method. Below are my observations:</p>

<pre class=""lang-none prettyprint-override""><code>allergy.dao.AllergyFormDAOSpec &gt; Get Allergy Form STANDARD_OUT
    setup method execution started at : Fri Jan 12 19:00:42 IST 2018

allergy.dao.AllergyFormDAOSpec &gt; API to get Allergy Form STANDARD_OUT
Feature method execution started at : Fri Jan 12 19:00:44 IST 2018
Feature method execution ended at: Fri Jan 12 19:00:45 IST 2018
Total time taken to run the one test case: 242

cleanup method execution started at : Fri Jan 12 19:00:45 IST 2018
Total time taken to run a feature method : 2531
</code></pre>

<p>Here, I have observed that it takes average 2-4 seconds to load a feature method after setup. But, Original test case execution time is less than a second.</p>

<p>I want to know if I can get pointers on what could be delay here ? As, 3 seconds for 2000 test cases means almost 1 Hr and 30 Min of time taken by Spock other than real feature execution.</p>

<p>To Summarize, We want to reduce total time taken by Spock test cases when we daily run it.</p>

<p><strong>Spec</strong></p>

<pre class=""lang-java prettyprint-override""><code>package allergy.dao

import java.util.Date

import org.dbunit.IDatabaseTester;
import org.dbunit.ext.mssql.InsertIdentityOperation;

import allergy.AllergyForm;
import be.janbols.spock.extension.dbunit.DbUnit;
import spock.lang.Shared
import util.MasterSpec

class AllergyFormDAOSpec extends MasterSpec {
    def dao = new AllergyFormDAO();
    @Shared Date timeStart1
    @Shared Date timeEnd1

@DbUnit(configure={ IDatabaseTester it -&gt;
    it.setUpOperation = InsertIdentityOperation.REFRESH
    it.tearDownOperation = InsertIdentityOperation.DELETE
})
def content =  {
    allergy_form(formId:99999,formName:'DummySpockForm',displayIndex:1,deleteFlag:0,is_biological:1)
    allergy_form_facilities(id:99999,formId:99999,facilityid:2)
    form_concentration(id:99999,formId:99999,name:'1:100',deleteflag:0,displayindex:1)
}

def setup(){
    timeStart1 = new Date()
    println ""setup method execution started at : "" +  timeStart1
}

def ""API to test delete Form facility""(){
    def startTime = new Date()
    println ""Feature method execution started at : "" +  startTime
    given:""form Id is given""
        def formId = 99999
    when:""delete form facilities""
        def result =dao.deleteFormFacilities(null, formId)
    then:""validate result""
        (result&gt;0)==true
        def endTime = new Date()
        println ""Feature method execution ended at: "" +  endTime
        println 'Total time taken to run the one test case: '+ (endTime.getTime() - startTime.getTime())
}

def cleanup() {
    timeEnd1 = new Date()
    println ""cleanup method execution started at : "" +  timeEnd1

    def difference = timeEnd1.time - timeStart1.time
    println ""Total time taken to run a fixture method : "" + difference
}
}
</code></pre>

<p><strong>MasterSpec</strong></p>

<pre class=""lang-java prettyprint-override""><code>package util

import com.ecw.dao.SqlTranslator
import catalog.Root
import spock.lang.Shared
import spock.lang.Specification

import javax.sql.DataSource

/**

 */
class MasterSpec extends Specification {

@Shared
Properties properties = new Properties()
@Shared
public DataSource dataSource
@Shared
protected xmlDataSource = [:]

static int timeCntr = 0;

//setup is to read xml file's content in xmlDataSource Hashmap
def setup(){

    //Get Running Class name without its package
    def className = this.class.name.substring(this.class.name.lastIndexOf('.') + 1)
    def resourceAnno = specificationContext.currentFeature.featureMethod.getAnnotation(FileResource)

    if(resourceAnno != null){
        def files = resourceAnno.xmlFiles()
        def packageName = (this.class.package.name).replaceAll('\\.','/')

        for(int i=0;i&lt; files.length;i++){
            def f = new File(""src/test/resources/""+packageName+""/""+className+""/""+files[i])
            def engine = new groovy.text.GStringTemplateEngine()
            def template = engine.createTemplate(f).make(null)
            def xmlString = template.toString()

            //load the hashmap with file name as Key and its content in form of string as Value
            xmlDataSource.put(files[i].split(""\\."")[0],xmlString)
        }
    }
}

def setupSpec() {
    Date timeStart = new Date()

    File propertiesFile = new File('src/test/webapps/myApp/conf/connection.properties').withInputStream {
        properties.load it
    }

    String strDBName = getPropertyValue(""myApp.DBName"")
    if(strDBName.indexOf('?') &gt; -1){
        strDBName = strDBName.substring(0, strDBName.indexOf('?'))
    }
    String strServerName = getPropertyValue(""myApp.DBHost"");
    if(strServerName.indexOf(':') &gt; -1){
        strServerName = strServerName.substring(0, strServerName.indexOf(':'))
    }
    String strUrl = getPropertyValue(""myApp.DBUrl"")
    String strPort = strUrl.substring(strUrl.lastIndexOf(':') + 1)

    //FOR MSSQL
    System.setProperty(""myApp.SkipJndi"", ""yes"")
    //dataSource = new JtdsDataSource()
    Object newObject = null;
    if(SqlTranslator.isDbSqlServer()){
        newObject = Class.forName(""net.sourceforge.jtds.jdbcx.JtdsDataSource"").newInstance()
    } else if(SqlTranslator.isDbMySql()){
        newObject = Class.forName(""com.mysql.jdbc.jdbc2.optional.MysqlDataSource"").newInstance()
    }

    dataSource = (DataSource)newObject
    dataSource.setDatabaseName(strDBName)
    dataSource.setUser(getPropertyValue(""myApp.DBUser""))
    dataSource.setPassword(getPropertyValue(""myApp.DBPassword""))
    dataSource.setServerName(strServerName)
    dataSource.setPortNumber(Integer.parseInt(strPort))

}
}
</code></pre>
",https://stackoverflow.com/questions/48228080/spock-with-dbunit-test-cases-slowness,"['unit-testing', 'spock', 'dbunit']",1224,TRUE,3,3
How do I integration test a Dataflow pipeline writing to Bigtable?,"<p>According to the <a href=""https://beam.apache.org/documentation/pipelines/test-your-pipeline/"" rel=""nofollow noreferrer"">Beam website</a>,</p>

<blockquote>
  <p>Often it is faster and simpler to perform local unit testing on your
  pipeline code than to debug a pipeline’s remote execution.</p>
</blockquote>

<p>I want to use test-driven development for my Beam/Dataflow app that writes to Bigtable for this reason.</p>

<p>However, following the Beam testing documentation I get to an impasse--PAssert isn't useful because the output PCollection contains org.apache.hadoop.hbase.client.Put objects, which don't override the equals method.</p>

<p>I <a href=""https://stackoverflow.com/a/41452218/2430134"">can't get the contents</a> of the PCollection to do validation on them either, since</p>

<blockquote>
  <p>It is not possible to get the contents of a PCollection directly - an
  Apache Beam or Dataflow pipeline is more like a query plan of what
  processing should be done, with PCollection being a logical
  intermediate node in the plan, rather than containing the data.</p>
</blockquote>

<p>So how can I test this pipeline, other than manually running it? I'm using Maven and JUnit (in Java since that's all the <a href=""https://cloud.google.com/bigtable/docs/hbase-dataflow-java"" rel=""nofollow noreferrer"">Dataflow Bigtable Connector</a> seems to support).</p>
",https://stackoverflow.com/questions/51162693/how-do-i-integration-test-a-dataflow-pipeline-writing-to-bigtable,"['google-cloud-dataflow', 'apache-beam', 'google-cloud-bigtable']",2281,TRUE,3,2
How to establish a websocket connection in Angular unit tests?,"<p>I'm working on an Angular (v 6.1.0) app which is communicating with a backend over a websocket. So far everything's been working fine except for the unit testing. I've created a mock backend for the purpose of testing my components but I just can't establish a connection between the mock backend and testing modules. I'm using Jasmine as an assertion library and Jest as a test runner, this is a sample test suite:</p>

<pre class=""lang-ts prettyprint-override""><code>describe('RandomComponent', () =&gt; {
  let component: RandomComponent;
  let fixture: ComponentFixture&lt;RandomComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [],
      imports: [SomeModule],
      providers: [SpecialWebSocketService, WebSocketService,
        { provide: BackendUrlService, useClass: BackendUrlMockService }
      ]
    })
      .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(RandomComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create random component', () =&gt; {
      expect(component).toBeTruthy();
  });
});
</code></pre>

<p>BackendUrlMockService is there just to provide a URL. The single test case produces the following:</p>

<pre class=""lang-bash prettyprint-override""><code> FAIL  src/app/path/to/my/random.component.spec.ts
  RandomComponent
    ✕ should create random component (603ms)

  ● RandomComponent › should create random component

    InvalidStateError: Still in CONNECTING state.
</code></pre>

<p>Application works fine both with real backend and the mocked one. Testing modules work with neither. I also noticed that if I add a timeout to the test case:</p>

<pre class=""lang-ts prettyprint-override""><code>it('should create random component', (done) =&gt; {
  setTimeout(() =&gt; {
    expect(component).toBeTruthy();
    done();
  }, 1000);
});
</code></pre>

<p>My mock backend logs a message that connection was established properly but I still get the error. Does anyone have an idea how to set up everything properly so that I could test my components?</p>
",https://stackoverflow.com/questions/52037268/how-to-establish-a-websocket-connection-in-angular-unit-tests,"['angular', 'unit-testing', 'websocket']",3684,TRUE,3,1
Asserting that TypeScript should fail to type check some example code,"<p>When I write a TypeScript library with generic constraints, I'd like to be able to specify tests of code that <em>should</em> type check and code that <em>should</em> not (because, say, I want to make sure the type checker is catching things that wouldn't satisfy a constraint correctly).</p>

<p>I haven't found a solution in conventional unit testing libraries (since the tests for failures wouldn't compile in the first place). I think I saw some examples of this deep in the TypeScript test suite where they either used file naming or comments to indicate assertions, but I can't find them now, and I couldn't unravel how the test runner worked for such a large project anyway. Googling is hard too: every combination of terms I've thought about brings back links about things like type guards or bug reports about TypeScript itself.</p>

<p>I know I could rig up a bash script that just runs <code>tsc</code> over the files and asserts that they fail, but I'd prefer the ability to match on specific compilation failures if possible. Any ideas?</p>
",https://stackoverflow.com/questions/51194259/asserting-that-typescript-should-fail-to-type-check-some-example-code,"['typescript', 'testing', 'typechecking']",1950,TRUE,11,2
How do I mock or fake behavior of a website to allow unit testing for certain JS functions,"<p><strong>Situation:</strong>
I just started to learn unit testing my JavaScript code and I am wondering if there is a way to fake the behavior of the application in order to test certain cases. I read about sinon.js spy/stub/mock. However, as usual for JS there are plenty of further scripts and combinations (i.e. with mocha, chai, karma-jasmine) and I hope that somebody can tell me about a best practice.  </p>

<p><strong>Let´s take an example:</strong> 
If I want to test a function in a test runner, which changes the background-size in dependence of the window size, it is complicated to trigger different window sizes (not element sizes) in order to see the background-size adjustment working in multiple dimensions.   </p>

<p>I already tested a few things, such as</p>

<pre><code>var resizeW = sinon.stub($.prototype, 'width').returns(600);
var resizeH = sinon.stub($.prototype, 'height').returns(1600);

// no effect - always takes the original view.height/width
viewport.setAttribute(""content"", ""height="" + viewheight + ""px, width="" + viewwidth + ""px, initial-scale=1.0""); 

// new window is not testable in the root testrunner window
window.open + window.resizeTo() / window.resizeBy() 

// shows no effect
window.innerHeight = '120'; window.innerWidth = '500';

// provides no possibility to assume different dimensions
$(window).trigger('resize');

// provides no possibility to assume different dimensions
$(document).trigger('resize');

// provides no possibility to assume different dimensions
window.dispatchEvent(new Event('resize'));
</code></pre>

<p>Using an iframe will be tedious, i.e. through conflicts with the CSS and jQuery between original HTML and testrunner HTML.</p>

<p>I hope somebody can suggest a convenient way to achieve this. </p>
",https://stackoverflow.com/questions/48366320/how-do-i-mock-or-fake-behavior-of-a-website-to-allow-unit-testing-for-certain-js,"['javascript', 'jquery', 'unit-testing', 'jasmine', 'sinon']",1327,TRUE,3,2
Mockito keeps returning Empty List,"<p>I'm working on unit testing a method in Mockito and mockito keeps sending an empty zero size list even when I have initialized the list that is to be returned.</p>

<p>This is the code to be tested. Note that nonCashIncludedPaymentPlanActive is always true ( Mocked ).</p>

<pre><code>    List&lt;DebtAccountTransaction&gt; debtAccountTransactionList = null;

    boolean nonCashIncludedPaymentPlanActive = balancingPlanService.checkNonCashIncludedPaymentPlanParameter(debtAccountId);


    if (nonCashIncludedPaymentPlanActive) {
        debtAccountTransactionList = debtAccountTransactionDao
                .getDebtAccountTransactionListByDebtAccountIdListWithCN(baseDebtIdAccountList, null);
    } 
    if (debtAccountTransactionList.isEmpty()) {
        throw new SfcException(""DISPLAY.PAYMENT_PLAN_WITH_NO_BALANCE_SERVICE_FILE_CLOSED"");
    }
</code></pre>

<p>This the statement that keeps returning a List that I have mocked in mockito and added an item to it and here it returns an emptylist.</p>

<pre><code>debtAccountTransactionList = debtAccountTransactionDao
                .getDebtAccountTransactionListByDebtAccountIdListWithCN(baseDebtIdAccountList, null);
</code></pre>

<p>which then ofcourse gets caught by this line</p>

<pre><code>if (debtAccountTransactionList.isEmpty()) {
        throw new SfcException(""DISPLAY.PAYMENT_PLAN_WITH_NO_BALANCE_SERVICE_FILE_CLOSED"");
    }
</code></pre>

<p>Thus inorder to avoid this path of execution I have done the following in Mockito:</p>

<pre><code>when(debtAccountTransactionDao.getDebtAccountTransactionListByDebtAccountIdListWithCN(baseDebtIdAccountList, null)).thenReturn(
            debtAccountTransactionList);
</code></pre>

<p>and declaration of debtAccountTransactionList is :</p>

<pre><code>DebtAccountTransaction debtAccountTransaction = spy(DebtAccountTransaction.class);
    debtAccountTransaction.setId(2L);


    List&lt;DebtAccountTransaction&gt; debtAccountTransactionList = new ArrayList&lt;DebtAccountTransaction&gt;();
    debtAccountTransactionList.add(debtAccountTransaction);
</code></pre>

<p>I tried mocking a List, tried different argument captors but nothing seems to work. When I debug it, Mockito does fill up the <em>debtAccountTransactionList</em> but with an empty List, thus it fails.</p>

<p>Any help with how I can make sure that Mockito sends a Non-Empty Non-Zero List so that it can bypass the <em>isEmpty()</em> check.</p>
",https://stackoverflow.com/questions/52497746/mockito-keeps-returning-empty-list,"['java', 'spring', 'unit-testing', 'mockito']",10889,TRUE,2,3
Default values missing for ServiceStack.XmlServiceClient response,"<p>While using TestCaseSource in unit testing for multiple ServiceStack service clients, deserialized to a string format for the XmlServiceClient does not match the deserialized for JsonServiceClient or JsvServiceClient. The serialization is using the SerializeAndFormat extension method from the ServiceStack.Text.TypeSerializer class.</p>

<p>Using the <a href=""https://stackoverflow.com/questions/11417436/default-values-for-missing-data-members-in-datacontractserializer"" title=""OnDerializing"">OnDeserializing</a> fuctionality doesn't seem to provide the same formatted string, as it is missing the default values.</p>

<p>The same JsConfig scope is used with excludeDefaultValues set to false prior to calling the SerializeAndFormat method. The Json and Jsv results match, including the default values, but the xml service client's result does not include them. The object that is not deserializing correctly is a property of a property of the response object and is decorated with this attribute [Serializable].</p>

<p>The response is decorated with [DataContract], [Serializable] and the property objects are both decorated with [Serializable].</p>

<p>How should the objects be decorated so that the serialized response is consistent for all three clients?</p>

<pre><code>[DataContract]    
[Serializable]
public class CustomResponse : IMeta, IHasResponseStatus
{
    [DataMember(Order = 5)]
    public Dictionary&lt;string, string&gt; Meta { get; set; }
    [DataMember(Order = 100)]
    public DataView Result { get; set; }
    [DataMember(Order = 1)]
    public Summary Summary { get; protected set; }
    [DataMember(Order = 8)]
    public ResponseStatus ResponseStatus { get; set; }
}


[Serializable]
public class Summary : IResponseStatus
{
    public IEnumerable&lt;HateoasLinks&gt; Links { get; set; }
    [DataMember(Order = 5)]
    public string Message { get; protected set; }

    [DataMember(IsRequired = false)]
    public int? Offset { get; set; }
    [DataMember(IsRequired = false)]
    public int? Limit { get; set; }
    public string RequestFormat { get; private set; }

    [DataMember(IsRequired = false)]
    public int? Results { get; protected set; }

    public Parameters Params { get; protected set; }
}

[Serializable]
public class Parameters
{
    [DataMember(Order = 1)]
    public string Status { get; set; } = ""OK"";
    public string Sort { get; set; } = string.Empty;
    public string Filter { get; set; } = string.Empty;
    public DateTime? StartDate { get; set; }
    public DateTime? EndDate { get; set; }
    [DataMember(EmitDefaultValue =true)]
    public int? Offset { get; set; } = 0;
    public int? Limit { get; set; } = 10;

    [OnDeserializing]
    void OnDeserializing(StreamingContext context)
    {
        if (!this.Limit.HasValue)
        {
            this.Limit = 10;
        }
        if (!this.Offset.HasValue)
        {
            this.Offset = 0;
        }
    }
}
</code></pre>

<p>results in:</p>

<pre><code> {
        summary: 
        {
        links: [],
        message: OK,
        params: 
        {
            status: OK,
            sort: """",
            filter: """",
        },
        isSuccess: False,
        status: 200,
        requestTime: 2014-03-14,
        currentPage: 1
    },
    result: 
    {
    }
}
</code></pre>

<p>but should be
params: </p>

<pre><code>{
    status: OK,
    sort: """",
    filter: """",
    offset: 0,
    limit: 10
}
</code></pre>
",https://stackoverflow.com/questions/50821811/default-values-missing-for-servicestack-xmlserviceclient-response,"['nunit', 'servicestack', 'approval-tests']",55,TRUE,2,1
JUnit - How to unit test method that reads files in a directory and uses external libraries,"<p>I have this method that I am using in a NetBeans plugin:</p>

<pre><code>public static SourceCodeFile getCurrentlyOpenedFile() {
        MainProjectManager mainProjectManager = new MainProjectManager();
        Project openedProject = mainProjectManager.getMainProject();

        /* Get Java file currently displaying in the IDE if there is an opened project */
        if (openedProject != null) {
            TopComponent activeTC = TopComponent.getRegistry().getActivated();
            DataObject dataLookup = activeTC.getLookup().lookup(DataObject.class);
            File file = FileUtil.toFile(dataLookup.getPrimaryFile());                   // Currently opened file

            // Check if the opened file is a Java file
            if (FilenameUtils.getExtension(file.getAbsoluteFile().getAbsolutePath()).equalsIgnoreCase(""java"")) {
                return new SourceCodeFile(file);
            } else {
                return null;
            }

        } else {
            return null;
        }
    }
</code></pre>

<p>Basically, using NetBeans API, it detects the file currently opened by the user in the IDE. Then, it loads it and creates a <code>SourceCodeFile</code> object out of it.</p>

<p>Now I want to unit test this method using JUnit. The problem is that I don't know how to test it.</p>

<p>Since it doesn't receive any argument as parameter, I can't test how it behaves given wrong arguments. I also thought about trying to manipulate <code>openedProject</code> in order to test the method behaviour given some different values to that object, but as far as I'm concernet, I can't manipulate a variable in JUnit that way. I also cannot check what the method returns, because the unit test will always return null, since it doesn't detect any opened file in NetBeans.</p>

<p>So, my question is: how can I approach the unit testing of this method?</p>
",https://stackoverflow.com/questions/51988014/junit-how-to-unit-test-method-that-reads-files-in-a-directory-and-uses-externa,"['java', 'unit-testing', 'junit', 'junit4']",450,TRUE,2,1
Angular Undefined,"<p>I'm trying to do some unit testing using Karma and Jasmine.</p>

<p>I followed a tutorial and I when I run karma start I get this error:</p>

<blockquote>
  <p>PhantomJS 2.1.1 (Windows 7 0.0.0) Testing Complaint UI Module Testing
  Search Page Controller should initialize the itemsPerPage FAILED
          ReferenceError: Can't find variable: inject in unit/test.js (line 9)
          unit/test.js:9:29
           PhantomJS 2.1.1 (Windows 7 0.0.0) ERROR   {
      ""message"": ""An error was thrown in afterAll\nTypeError: undefined is not a constructor (evaluating 'angular.module('ngAnimateMock',
  ['ng'])\n  .info({ angularVersion: '1.7.2' })')"",
      ""str"": ""An error was thrown in afterAll\nTypeError: undefined is not a constructor (evaluating 'angular.module('ngAnimateMock',
  ['ng'])\n  .info({ angularVersion: '1.7.2' })')""   } PhantomJS 2.1.1
  (Windows 7 0.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.003 secs /
  0.002 secs)</p>
</blockquote>

<p>I think the first error (<code>Can't find variable: inject</code> is caused by the error in angular-mock.js</p>

<p>My Files in karma.config</p>

<pre><code>    // list of files / patterns to load in the browser
files: [
    'angular.js',
    '../components/angular-mocks/angular-mocks.js',
    '../app/app.js',
    'unit/*.js'
],
</code></pre>

<p>Folder Configuration</p>

<p>In Root: app,components,test</p>

<p>Inside test is the <code>angular.js</code> and <code>karma.conf</code></p>

<p>Inside components there's <code>angular-mocks</code> folder</p>

<p>Inside App there's the app.js file</p>

<p><strong>What am I missing here??</strong></p>
",https://stackoverflow.com/questions/51264519/angular-undefined,"['javascript', 'angularjs', 'unit-testing', 'karma-jasmine']",381,FALSE,2,0
VS Unit test on database procedures inMemory that can be integrated with continuous delivery pipeline,"<p>So Im trying to figure out a way to properly unit test database procedures in visual studio so I can integrate it into our deployment pipeline.</p>

<p>what I am doing right now is create a database project and link it to our database. Then generate unit test with visual studio on the procedures. The problem is that unit testing the procedures this way will make changes to data in the actual database (which I don't want). Another problem is when someone make change to the database without updating that database project</p>

<p>I can either: </p>

<ol>
<li><p>do a rollback after every unit test (but there are some procedures that contain <code>commit</code>, so even if I <code>rollback</code> in <code>c#</code>, some part will still get committed)</p></li>
<li><p>create a testing database (not an option in my situation)</p></li>
<li><p>create a in-memory database (I prefer this option. I checked out <code>SQLite</code>. However it doesn't seem to support procedures)</p></li>
</ol>

<p>Any advises or suggestions are appreciated </p>
",https://stackoverflow.com/questions/53250748/vs-unit-test-on-database-procedures-inmemory-that-can-be-integrated-with-continu,"['sql', 'sql-server', 'unit-testing', 'tsql', 'stored-procedures']",91,TRUE,2,1
Visual Studio 2017 project reference support between .net standard and .net core,"<p>I have a .Net standard 2.0 project in a Visual Studio solution that contains some Azure functions.  In the same solution, I've created a .Net Core 2.0 Unit Test project.  I've added a project reference from the .Net Core Unit Test project to the .Net standard 2.0 library.</p>

<p>Despite the project reference, Visual Studio is behaving like I'm referencing a dll instead of the project.  For example, if I try to use F12/Go to reference, it brings me to a 'From metadata' file instead of the actual code file in the other project.  Additionally, codelens features like 'Tested by' (and even just 'referenced by') and the Live Unit testing icons in the .Net Standard project aren't working, since they don't seem to be aware of the Unit Test project at all.</p>

<p>Is there some way to get this integration working between the two projects?  My Visual Studio is up to date (15.5.3 enterprise), and I'm not using any tools like Resharper or anything like that.</p>
",https://stackoverflow.com/questions/48242945/visual-studio-2017-project-reference-support-between-net-standard-and-net-core,"['visual-studio', '.net-core', '.net-standard', 'codelens', 'live-unit-tests']",100,FALSE,2,1
JEST Test Failed - TypeError: Cannot read property &#39;fetch&#39; of undefined in CRNA Expo App,"<p>I am not unit testing a fetch function so even libraries like <a href=""https://www.npmjs.com/package/jest-fetch-mock"" rel=""nofollow noreferrer"">jest-fetch-mock</a> don't help get rid of the error. Neither does <code>axios</code> nor <code>isomorphic-fetch</code></p>

<p>Running <code>yarn test</code> yields this.</p>

<p><a href=""https://i.stack.imgur.com/6htbz.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/6htbz.png"" alt=""enter image description here""></a>
My <code>App.test.js</code> simply doesn't test fetch:</p>

<pre><code>import React from 'react'
import renderer from 'react-test-renderer'
import App from './App'

it('renders without crashing', () =&gt; {
  const rendered = renderer.create(&lt;App /&gt;).toJSON()
  expect(rendered).toBeTruthy()
})
</code></pre>

<p>Similar to:
* <a href=""https://stackoverflow.com/questions/47111767/error-cannot-read-property-fetch-using-jest-expo-with-react-native"">Error : Cannot read property fetch. Using jest-expo with react native</a> (might be duplicate but the question is not elaborated)
* <a href=""https://stackoverflow.com/questions/44045195/jest-throwing-typeerror-cannot-read-property-fetch-of-undefined"">Jest throwing TypeError: Cannot read property &#39;fetch&#39; of undefined</a></p>

<ul>
<li><p><a href=""https://github.com/react-community/create-react-native-app/issues/208"" rel=""nofollow noreferrer"">https://github.com/react-community/create-react-native-app/issues/208</a></p></li>
<li><p>facebook/jest#3499</p></li>
<li>facebook/jest#3538</li>
</ul>

<p>I have a fetch method in my screens(not in my tests). Note that the above error occurs whether or not I comment/use my fetch functions.</p>

<p>I am suspecting this has something to do with my babel or jest configs.</p>

<p>The above error happens with my <code>.babelrc</code> below. Changing <a href=""https://github.com/MattermarkStudios/react-native-skeleton/blob/dev/.babelrc"" rel=""nofollow noreferrer""><code>.babelrc</code></a>:</p>

<pre><code>   {
     ""presets"": [""babel-preset-expo"", ""react-native"", ""es2015"", ""react-native-dotenv""],
     ""env"": {
     ""development"": {
       ""plugins"": [""transform-react-jsx-source"",""module-resolver""]
      }
     }
    }
</code></pre>

<p>by removing ""es2015"" preset causes another error. Note this happens even if there is no <code>babel-preset-es2015</code> devDependency.</p>

<pre><code>({""Object.&lt;anonymous&gt;"":function(module,exports,require,__dirname,__filename,global,jest){�PNG                                                                                             
^
  SyntaxError: Invalid or unexpected token

  at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:318:17)
  at Object.&lt;anonymous&gt; (node_modules/react-navigation/src/views/Header/HeaderBackButton.js:92:223)
</code></pre>

<p>I am using <code>yarn 1.3.2</code> &amp; <code>ubuntu 17.04</code> &amp; <code>Node v9.5.0</code> &amp; <code>create-react-native-app version: 1.0.0</code></p>

<p>My App Component:</p>

<pre><code>   import React, { Component } from 'react'
   import {
      TouchableHighlight,
      Text,
      View,
      AsyncStorage
   } from 'react-native'

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      data: null
    }
  }
  componentWillMount() {
    this.setState({
      loading: true
    }, this._getData)
  }
  _getData = () =&gt; {
      fetch('localhost:1212')
      .then(() =&gt; {
        this.setState({
          data: data,
        })
      })
      .catch((error) =&gt; {
        alert('There was an error fetching the secret info.')
      })
      .done()
    }
  _renderData = () =&gt; (
    &lt;Text&gt;You are seeing&lt;/Text&gt;
  )
  render() {
    return (
      &lt;View &gt;
        {
          &lt;Text&gt;
            {this.state.secret ? this._renderData() : &lt;Text&gt;Nothing to See&lt;/Text&gt;}
          &lt;/Text&gt;
        }
      &lt;/View&gt;
    )
  }
}

export default App
</code></pre>
",https://stackoverflow.com/questions/48740977/jest-test-failed-typeerror-cannot-read-property-fetch-of-undefined-in-crna,"['react-native', 'jestjs', 'babel-jest', 'create-react-native-app']",1091,FALSE,2,0
How to mock Image object with Karma (Angular 7)?,"<p>I'm trying to mock the default DOM <code>Image</code> object for unit testing an Angular service.</p>

<p>The service is simple, it checks the ""webP"" format support :</p>

<pre><code>import {Injectable} from '@angular/core';
import {Promise} from 'es6-promise';
import {environment} from '../../../../environments/environment';

@Injectable({
  providedIn: 'root'
})
export class AppLoadService {

  constructor() {
  }

  initializeApp(): Promise&lt;any&gt; {
    return new Promise((resolve) =&gt; {
      console.log(`initializeApp:: inside promise`);
      if (typeof Image === 'undefined') {
        console.log(`initializeApp:: Image undefined`);
        resolve();
        return;
      }
      const webP = new Image();
      webP.onload = () =&gt; {
        console.log(`initializeApp:: WebP support: true`);
        environment.webP = true;
        resolve();
      };
      webP.onerror = () =&gt; {
        console.log(`initializeApp:: WebP support: false`);
        resolve();
      };
      webP.src = 'data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA';
    });
  }
}
</code></pre>

<p>I found a way to check the webP support (default in chromium where Karma is running), and a way to check fallback on <code>Image undefined</code>.</p>

<p>But I cannot find a way to checks the <code>onerror</code> fallback...</p>

<p>Here is my spec file :</p>

<pre><code>import {TestBed} from '@angular/core/testing';
import {AppLoadService} from './app-load.service';
import {environment} from '../../../../environments/environment';

describe('AppLoadService', () =&gt; {
  let service: AppLoadService;
  const originalImage = Image;

  beforeEach(() =&gt; TestBed.configureTestingModule({}));

  beforeEach(() =&gt; {
    service = TestBed.get(AppLoadService);
  });

  it('should be created', () =&gt; {
    expect(service).toBeTruthy();
  });

  it('should resolve with webP', (done) =&gt; {
    const test = () =&gt; {
      Image = originalImage;
      service.initializeApp().then(() =&gt; {
        expect(environment.webP).toBe(true);
        done();
      });
    };
    test();
  });

  it('should resolve without webP (A)', (done) =&gt; {
    const test = () =&gt; {
      Image = undefined;
      service.initializeApp().then(() =&gt; {
        expect(environment.webP).toBe(false);
        done();
      });
    };
    test();
  });

  it('should resolve without webP (B)', (done) =&gt; {
    // How to force Image to throw ""onerror"" ?
    const test = () =&gt; {
      Image = originalImage;
      service.initializeApp().then(() =&gt; {
        expect(environment.webP).toBe(false);
        done();
      });
    };
    test();
  });
});
</code></pre>

<p>The question is on <code>should resolve without webP (B)</code> test, at the end of the file..</p>

<p>Moreover, is there a better way to check undefined Image object or <code>onload</code> callback ?</p>

<p>Thanks !</p>

<hr>

<p><strong>EDIT</strong></p>

<p>Can't get it works as it is, so I change the service constructor to provide ""Image"" dependency.</p>

<pre><code>constructor(@Inject('Image') image: typeof Image) {
  this.image = image;
}
</code></pre>

<p>Have to load the module like that :</p>

<pre><code>providers: [
  AppLoadService,
  // [...]
  {provide: 'Image', useValue: Image},
]
</code></pre>

<p>And each <code>resolve()</code> now includes <code>environment.webP</code> result. Otherwise, individual test are a real pain, <code>environment</code> is randomly rewritten before being tested.</p>

<p>With a simple Mock it works like this :</p>

<pre><code>import {TestBed} from '@angular/core/testing';
import {AppLoadService} from './app-load.service';

class MockImageFail {
  public onerror: Function;
  private _src: string;

  set src(src) {
    this._src = src;
    if (this.onerror) {
      this.onerror();
    }
  }
}

describe('AppLoadService', () =&gt; {

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      providers: [{provide: 'Image', useValue: Image}]
    });
  });

  it('should be created', () =&gt; {
    const service = TestBed.get(AppLoadService);
    expect(service).toBeTruthy();
  });

  it('should resolve with webP', (done) =&gt; {
    const service = TestBed.get(AppLoadService);
    service.initializeApp().then((supportWebP) =&gt; {
      expect(supportWebP).toBe(true);
      done();
    });
  });

  it('should not resolve without webP (A)', (done) =&gt; {
    TestBed.overrideProvider('Image', {useValue: undefined});
    const service = TestBed.get(AppLoadService);
    service.initializeApp().then((supportWebP) =&gt; {
      expect(supportWebP).toBe(false);
      done();
    });
  });

  it('should not resolve without webP (B)', (done) =&gt; {
    TestBed.overrideProvider('Image', {useValue: MockImageFail});
    const service = TestBed.get(AppLoadService);
    service.initializeApp().then((supportWebP) =&gt; {
      expect(supportWebP).toBe(false);
      done();
    });
  });
});
</code></pre>

<p>I'm not really happy with that and I'm sure there is another better way :/</p>
",https://stackoverflow.com/questions/53277359/how-to-mock-image-object-with-karma-angular-7,"['angular', 'image', 'dom', 'karma-jasmine', 'angular7']",1962,FALSE,2,1
Mock file upload to test a FileReader,"<p>Hello and thank you for your time reading this!</p>

<p>I am very interested to do unit tests while developing. I am new to tests in Javascript.</p>

<p>I have written a function to read files we choose,with an input, however I do not know how to test it.</p>

<p>I have read the documentation of Jasmine, about spies: 
<a href=""https://jasmine.github.io/api/2.6/global.html#spyOn"" rel=""nofollow noreferrer"">https://jasmine.github.io/api/2.6/global.html#spyOn</a></p>

<p>And:
<a href=""https://jasmine.github.io/2.0/introduction.html"" rel=""nofollow noreferrer"">https://jasmine.github.io/2.0/introduction.html</a></p>

<p>The code:</p>

<pre><code>    function readImage() {
    if ( this.files &amp;&amp; this.files[0] ) {
        var FR= new FileReader();
        var img = new Image();
        FR.onload = function(e) {
            img.src = e.target.result;
            img.onload = function() {
                ctx.drawImage(img, 0, 0, 512, 512);
            };
        };
        FR.readAsDataURL( this.files[0] );
    }
    return [this.files, FR, img, ctx];
}

fileUpload.onchange = readImage;
</code></pre>

<p>The test I tried:</p>

<pre><code>describe('readImage', function () {
 it('should get at least one file ', function () {

        spyOn(window, 'readImage');

        fileUpload.dispatchEvent(new Event('onchange'));

        expect(window.readImage).toHaveBeenCalled();

    })

});
</code></pre>

<p>Also, fileUpload is:</p>

<pre><code>    function createUploadInput() {
    body = document.getElementsByTagName(""BODY"")[0];
    upload = document.createElement(""input"");
    upload.setAttribute(""type"", ""file"");
    upload.setAttribute(""id"", ""fileUpload"");
    body.appendChild(upload);
    return upload;
}

createUploadInput();
</code></pre>

<p>The output I get:</p>

<pre><code>        Expected spy readImage to have been called.
    Error: Expected spy readImage to have been called.
        at jasmine.Spec.&lt;anonymous&gt; (test/readImageSpec.js:42:34)
</code></pre>

<p>I think it is because of the readImage method has not been called in the test. The reason could be because             <code>fileUpload.dispatchEvent(new Event('onchange'));</code> does nothing</p>

<p>Could you help me please?</p>

<p>I have also read:
<a href=""https://stackoverflow.com/questions/2490825/how-to-trigger-event-in-javascript"">How to trigger event in JavaScript?</a></p>

<p><a href=""https://stackoverflow.com/questions/38216225/triggering-event-for-unit-testing"">Triggering event for unit testing</a></p>

<p><a href=""https://stackoverflow.com/questions/9510148/using-jasmine-to-spy-on-a-function-without-an-object"">Using Jasmine to spy on a function without an object</a></p>

<p>Thank you for your help!</p>

<p>I have tried:</p>

<pre><code>it('should get at least one file ', function () {

    spyOn(window, 'readImage');

    fileUpload.dispatchEvent(new Event('change'));

    expect(window.readImage).toHaveBeenCalled();

})
</code></pre>

<p>But output is:</p>

<pre><code>   Expected spy readImage to have been called.
        Error: Expected spy readImage to have been called.
            at jasmine.Spec.&lt;anonymous&gt; (test/readImageSpec.js:42:34)
</code></pre>

<p>Also I tried:</p>

<pre><code>it('should get at least one file ', function () {

    spyOn(window, 'readImage');

    fileUpload.onchange();

    expect(window.readImage).toHaveBeenCalled();

})
</code></pre>

<p>And output:</p>

<pre><code>Expected spy readImage to have been called.
Error: Expected spy readImage to have been called.
    at jasmine.Spec.&lt;anonymous&gt; (test/readImageSpec.js:42:34)
</code></pre>

<p>I have also read: <a href=""https://stackoverflow.com/questions/2856513/how-can-i-trigger-an-onchange-event-manually"">How can I trigger an onchange event manually?</a></p>
",https://stackoverflow.com/questions/48528236/mock-file-upload-to-test-a-filereader,"['javascript', 'unit-testing']",1323,FALSE,2,0
AioHTTPTestCase raise RuntimeError: There is no current event loop in thread &#39;MainThread&#39;,"<p>I define <code>aiohttp.Applcation</code> and <code>unittest</code> for the <code>Application</code> like the below.</p>
<pre><code># main.py

import asyncio
from aiohttp import web

async def background_task():
    await asyncio.sleep(5)

async def start_up_test(app):
    app.loop.create_task(background_task())

def get_application(bg_tasks=[]):
    app = web.Application()
    app.on_startup.append(start_up_test)
    return app
</code></pre>
<hr />
<pre><code># main_test.py

import main
from aiohttp import test_utils

class TestMain(test_utils.AioHTTPTestCase):

    async def get_application(self):
        return main.get_application()

    @test_utils.unittest_run_loop
    async def test_main(self):
        pass
</code></pre>
<hr />
<pre><code>$ python -m unittest main_test
Task exception was never retrieved
future: &lt;Task finished coro=&lt;background_task() done, defined at /home/sangmin/workspace/main.py:78&gt; exception=RuntimeError(&quot;There is no current event loop in thread 'MainThread'.&quot;,)&gt;
Traceback (most recent call last):
  File &quot;/usr/lib/python3.5/asyncio/tasks.py&quot;, line 239, in _step
    result = coro.send(None)
  File &quot;/home/sangmin/workspace/main.py&quot;, line 79, in background_task
    await asyncio.sleep(5)
  File &quot;/usr/lib/python3.5/asyncio/tasks.py&quot;, line 510, in sleep
    loop = events.get_event_loop()
  File &quot;/usr/lib/python3.5/asyncio/events.py&quot;, line 632, in get_event_loop
    return get_event_loop_policy().get_event_loop()
  File &quot;/usr/lib/python3.5/asyncio/events.py&quot;, line 578, in get_event_loop
    % threading.current_thread().name)
RuntimeError: There is no current event loop in thread 'MainThread'.
.
----------------------------------------------------------------------
Ran 1 test in 0.021s

OK
</code></pre>
<p>The <code>TestCase</code> raises an exception saying <code>There is no current event loop in thread 'MainThread'</code>.</p>
<p>Then I found <code>aiohttp</code> <a href=""https://docs.aiohttp.org/en/stable/testing.html#aiohttp-testing-writing-testable-services"" rel=""nofollow noreferrer"">DOC</a> mentioning about <code>main loop</code> while unit-testing.</p>
<blockquote>
<p>Some libraries like motor, aioes and others depend on the asyncio loop for executing the code. When running your normal program, these libraries pick the main event loop by doing asyncio.get_event_loop.</p>
<p>The problem during testing is that there is no main loop assigned because an independent loop for each test is created without assigning it as the main one.</p>
</blockquote>
<p>According to the DOC, the cause of the exception is because <code>asyncio.get_event_loop</code> is called while no <code>main loop</code> is assigned on <code>unittest</code> and I can see <code>await asyncio.sleep(1)</code> access <code>main loop</code> by calling <code>get_event_loop</code> in above <code>Trace</code>.</p>
<p>Then, I am so confused since I think <code>Application</code> should be running over <code>test loop</code> served by <code>AioHTTPTestCase</code> and all of the coroutines in the <code>Application</code> also should use the same <code>loop</code> not <code>main loop</code>.</p>
<p>What do I have missed and how do I fix it?</p>
<p>-----<strong>Edit</strong>-----</p>
<p>Tracing <code>aiohttp</code> source code, I could make the issue simplify.</p>
<pre><code>import asyncio

async def test():
    await asyncio.sleep(1)

if __name__ == '__main__':
    # setUp method of AioHTTPTestCase clear main loop and return new loop. 
    asyncio.set_event_loop(None)
    loop = asyncio.new_event_loop()
    
    # unittest_run_loop decorator run coroutine over the new loop.
    loop.run_until_complete(test())
    
    # This simple code also raises the same exception.
</code></pre>
<p>This behavior is normal for <code>asyncio</code>.</p>
",https://stackoverflow.com/questions/48600100/aiohttptestcase-raise-runtimeerror-there-is-no-current-event-loop-in-thread-ma,"['python', 'python-3.5', 'python-asyncio', 'python-unittest', 'aiohttp']",314,FALSE,2,0
Flex/Bison: cannot use semantic_type,"<p>I try to create a c++ flex/bison parser. I used <a href=""http://www.jonathanbeard.io/tutorials/FlexBisonC++"" rel=""nofollow noreferrer"">this tutorial</a> as a starting point and did not change any bison/flex configurations. I am stuck now to the point of trying to unit test the lexer.</p>

<p>I have a function in my unit tests that directly calls yylex, and checks the result of it:</p>

<pre><code>private: static void checkIntToken(MyScanner &amp;scanner, Compiler *comp, unsigned long expected, unsigned char size, char isUnsigned, unsigned int line, const std::string &amp;label) {
    yy::MyParser::location_type loc;
    yy::MyParser::semantic_type semantic; // &lt;---- is seems like the destructor of this variable causes the crash

    int type = scanner.yylex(&amp;semantic, &amp;loc, comp);
    Assert::equals(yy::MyParser::token::INT, type, label + ""__1"");

    MyIntToken* token = semantic.as&lt;MyIntToken*&gt;();
    Assert::equals(expected, token-&gt;value, label + ""__2"");
    Assert::equals(size, token-&gt;size, label + ""__3"");
    Assert::equals(isUnsigned, token-&gt;isUnsigned, label + ""__4"");
    Assert::equals(line, loc.begin.line, label + ""__5"");

    //execution comes to this point, and then, program crashes
}
</code></pre>

<p>The error message is:</p>

<pre><code>program: ../src/__autoGenerated__/MyParser.tab.hh:190: yy::variant&lt;32&gt;::~variant() [S = 32]: Assertion `!yytypeid_' failed.
</code></pre>

<p>I have tried to follow the logic in the auto-generated bison files, and make some sense out of it. But I did not succeed on that and ultimately gave up. I searched then for any advice on the web about this error message but did not find any.</p>

<p>The location indicated by the error has the following code:</p>

<pre><code>~variant (){
  YYASSERT (!yytypeid_);
}
</code></pre>

<p>EDIT: The problem disappears only if I remove the</p>

<pre><code>%define parse.assert
</code></pre>

<p>option from the bison file. But I am not sure if this is a good idea...</p>

<p>What is the proper way to obtain the value of the token generated by flex, for unit testing purposes?</p>
",https://stackoverflow.com/questions/50776052/flex-bison-cannot-use-semantic-type,"['c++', 'unit-testing', 'bison', 'flex-lexer']",924,TRUE,2,1
Where is the DLL with test to run with the nunit3 console generated?,"<p>I created a project in Visual Studio for unit testing using the nuget package of nunit. The test runs well in Visual Studio using the test explorer, but i Need to run them using the nunit3 console. </p>

<p>My project is very simple I:</p>

<ul>
<li>Created a console project in C#</li>
<li>I Installed Nunit and NUnitTestAdapter using NuGet Package Manager.</li>
<li><p>I create a  class called MyMath.cs with the next code:</p>

<pre><code>namespace NunitDemo
{
class MyMath
{
    public int add(int a, int b)
    {
        return a + b;
    }

    public int sub(int a, int b)
    {
        return a - b;
    }
}
}
</code></pre></li>
<li><p>I create a MyTestCase Class with the following code to test MyMath methods:</p>

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

namespace NunitDemo
{
    [TestFixture]
    class MyTestCase
    {
        [TestCase]
        public void Add()
        {
           MyMath math = new MyMath();
           Assert.AreEqual(31, math.add(20, 11));
        }

        [TestCase]
        public void Sub()
        {
        MyMath math = new MyMath();
        Assert.AreEqual(9, math.sub(20, 11));
        }
    }
}
</code></pre></li>
<li><p>I rebuild my solution and using The test explorer panel I can run my test in Visual Studio without problems.</p></li>
</ul>

<p>But I need to run my test using the nunit3-console prompt, So, How Can I generate (Or Where Is) a DLL file to run test from the console o using nunit-gui?  </p>

<p>I search inside C:\Users\Manuel\source\repos\ConsoleAppForNunit\ConsoleAppForNunit\bin\Debug but there is not a suitable .DLL</p>

<p>There is a Screenshot of that path: <a href=""https://i.stack.imgur.com/ivzEl.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/ivzEl.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/52559975/where-is-the-dll-with-test-to-run-with-the-nunit3-console-generated,"['c#', 'unit-testing', 'nunit', 'nunit-console']",1719,TRUE,1,1
Unit Test on a c# legacy project,"<p>I have a problem with unit tests which is as follows:</p>

<p>I'm working on a legacy project where the database has no repository or inherits an interface.</p>

<p>Basically the solution has: a project with models, a project with business rules, database queries and processing for the UI and a project for the UI.</p>

<p>The connection to the database is made by a class specially developed for this and all queries are developed manually and executed by this class.</p>

<p>The classes that have business rules in their vast majority are static with their methods also static and change that would be in the last case (the world ends by example).</p>

<p>I know I need to use MOCK to test the behavior of business rule classes, the problem that I'm kind of lost with.</p>

<p>I would like to know how I could implement unit testing on a product like this without performing a large refactor.</p>

<p>Do the masters have any tips?</p>
",https://stackoverflow.com/questions/51624742/unit-test-on-a-c-legacy-project,"['c#', 'unit-testing', 'legacy']",128,FALSE,1,0
Initialization of Mock object not being recorded,"<p>I am trying to test the successful call of my class's constructor, but it is not being recorded in my Mock object. I am using the <code>pytest</code>and <code>pytest-mock</code>libraries for unit testing and mocking, respectively.</p>

<p>Imagine I have the following class in the package <code>cryptocurrency</code>in the module <code>transaction.py</code>:</p>

<pre><code>class Transaction:
    def __init__(self, test):
        self.test = test
</code></pre>

<p>And the following test in another package <code>tests</code> in the module <code>test_transaction.py</code>:</p>

<pre><code>def test_constructor(mocker):
    mock_transaction = mocker.patch('cryptocurrency.transaction.Transaction', 
        autospec=True)
    Transaction('123')
    mock_transaction.assert_called_once()
</code></pre>

<p>Why is it that the test fails with the message:</p>

<p><code>AssertionError: Expected 'Transaction' to have been called once. Called 0 times.</code></p>

<p>Shouldn't the Mock the object be listening to the initialization of the class instance and record it?</p>

<p>EDIT: I got this question answered, but I have another similar scenario that still doesn't work. Imagine that the class <code>Transaction</code> also has the following method:</p>

<pre><code>@classmethod
def new_transaction(cls, test)
    return cls(test)
</code></pre>

<p>and that the test is:</p>

<pre><code>def test_new_transaction(mocker):
    mock_transaction = mocker.patch('cryptocurrency.transaction.Transaction', 
        autospec=True)
    Transaction.new_transaction('123')
    mock_transaction.assert_called_once()
</code></pre>

<p>I can't get it to working. I already tried changing the patch to <code>__name__ + 'Transaction'</code> like the answer suggested, but it still doesn't work. I feel like my initial solution should be the correct one since even though the test references a certain <code>Transaction</code> import, the <code>new_transaction()</code> method will interact with the original <code>Transactiion</code> at <code>cryptocurrency.transaction.Transaction</code>.</p>
",https://stackoverflow.com/questions/53688283/initialization-of-mock-object-not-being-recorded,"['python', 'unit-testing', 'mocking', 'pytest']",95,FALSE,1,0
Qt Creator: run unit test automatically before main project,"<p>I have some widget application project on Qt 5.9.3. Now for a Unit testing <a href=""https://stackoverflow.com/questions/12684152/how-can-i-set-up-my-project-hierarchy-in-qtcreator"">I've created a new root ""subdir"" project</a>, which contains my main application project and the new <a href=""http://doc.qt.io/qt-5/qtest-overview.html"" rel=""nofollow noreferrer"">Qt test project</a>:</p>

<p><img src=""https://lh3.googleusercontent.com/N-0SbBtI9SoMVS_vCI0WWkLQUK1xp46p7drSt5oyHO1IsSUw3bogqoVCIPrC2rO8CygncPs5fDc"" alt=""enter image description here""></p>

<p>Notice - how I create the root solution folder with an existing project:</p>

<ol>
<li>In Qt creator: File -> New File or Project -> Other Projects -> Subdirs Projects</li>
<li>How to add an existing project to it: in subdirs project's .pro file append my existing project name and *copy the existing project's folder to the solution folder.</li>
<li>Create new test project through File -> New File or Project -> Other Projects -> Qt Unit Test -> Next -> ... -> Add as subproject to project 'my_solution'.pro.</li>
</ol>

<p><a href=""https://i.stack.imgur.com/vd0Ih.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/vd0Ih.png"" alt="".pro SUBDIRS""></a></p>

<p><a href=""https://i.stack.imgur.com/5ioqM.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/5ioqM.png"" alt=""Folders""></a></p>

<p>Now I need to run the test project automatically before the main application start. How this can be done in <a href=""http://doc.qt.io/qtcreator/index.html"" rel=""nofollow noreferrer"">Qt Creator</a> (4.4.1)? 
What I have now in the solution project settings:</p>

<p><img src=""https://lh3.googleusercontent.com/m4ZRx-4-e-VZz3ZuxRK8gNtU12XgnbdpUXzksn3ZLtSIjGvP3ytm87x7APGomMG6dmFJP_dLyKc"" alt=""enter image description here""></p>

<p><img src=""https://lh3.googleusercontent.com/bt0Iyc_4hy6R5K87WTAEw6uT1CghuFCzybkeRLKXG4l1y47WnatbtpTlMCexCHi5jQZR2X1fH_0"" alt=""enter image description here""></p>

<p>Any ideas? Is it possible to make two such tasks sequentially? How do you make auto start for unit tests in Qt Creator?</p>
",https://stackoverflow.com/questions/48701677/qt-creator-run-unit-test-automatically-before-main-project,"['qt', 'unit-testing', 'qt-creator', 'qttest']",589,FALSE,1,0
Properly accessing imported namespaces when mocking in Python3,"<p>I'm starting a new project in Python 3. I intend to make this a PIP package, so I've started with a cookiecutter template as follows:</p>

<pre><code>cycle_calendar_generator
/cycle_calendar_generator
  __init__.py
  cycle_calendar_generator.py
/tests
  __init__.py
  test_cycle_calendar_generator.py
</code></pre>

<p>This project will be used widely in my school, so I want to do solid unit testing from the start. I'd rather stick with the Python3 included unittest modules, since they're simple and do what I want.</p>

<p>The problem is that I need to do some mocking of core API modules, like argparse and os. I've seen advice that you should mock the namespace of the core API module imported, not the module itself. (So mocking cycle_calendar_generator.argparse is correct, but importing argparse and mocking it is not, since it's a different copy of argparse.)</p>

<p>With that said, here's what I have in the test_cycle_calendar_generator.py:</p>

<pre><code>import unittest
from unittest import mock

from cycle_calendar_generator import cycle_calendar_generator


class Test_get_args(unittest.TestCase):
    """"""Tests for `cycle_calendar_generator` package.""""""

    def setUp(self):
        """"""Set up test fixtures, if any.""""""

    def tearDown(self):
        """"""Tear down test fixtures, if any.""""""

    @mock.patch('cycle_calendar_generator.argparse.parse_args')
    def test_if_arg_is_string(self, mock_parse_args):
        mock_parse_args.return_value = cycle_calendar_generator.argparse.Namespace(directory='string')
        self.assertIsInstance(cycle_calendar_generator.getArgs(), str)
</code></pre>

<p>This is giving me the error <code>AttributeError: module 'cycle_calendar_generator' has no attribute 'argparse'</code>, so it's clearly not finding the imported argparse, but I can't figure out how I might solve it. Any idea what could be happening? Thanks!</p>
",https://stackoverflow.com/questions/51816990/properly-accessing-imported-namespaces-when-mocking-in-python3,"['python-3.x', 'unit-testing']",180,TRUE,1,1
Correct way to fail a unit test from within a callback using Vertx Unit,"<p>Given the following unit test, which uses the <strong>Vertx Unit</strong> testing framework:</p>

<pre><code>@RunWith(VertxUnitRunner.class)
public class VertxUnitTest {

    private Vertx vertx;

    @Rule
    public RunTestOnContext rule = new RunTestOnContext(new VertxOptions().setClustered(false)
            .setClusterManager(new HazelcastClusterManager()).setMaxEventLoopExecuteTime(2000000000000L)
            .setMaxWorkerExecuteTime(60000000000000L).setBlockedThreadCheckInterval(1000000)
            .setEventBusOptions(new EventBusOptions().setClustered(false).setIdleTimeout(0)));

    @Before
    public void setup() throws Exception {
        io.vertx.core.Vertx v = rule.vertx();
        vertx = Vertx.newInstance(v);
    }

    private class MyVerticle extends AbstractVerticle {}

    @Test
    public void runFlow_correctMessage_stepsCalledInCorrectOrder(TestContext context) {
        Async async = context.async();

        vertx.getDelegate().deployVerticle(new MyVerticle(), new DeploymentOptions().setWorker(true), c -&gt; {
            c.cause();
            vertx.eventBus().&lt;Object&gt;send("""", new JsonObject(), new DeliveryOptions(), rpl -&gt; {
                async.complete();
                fail();

            });
        });
    }
}
</code></pre>

<p>the call to <code>fail()</code> is throwing an exception to the console, but it is not actually failing the test itself, which finishes successfully and is green.</p>

<p>The same is true when working with <strong>Mockito</strong>. I can successfully verify the behavior of the verticle and its dependencies using mocks, but even when the Mockito assertions fail, the test itself will still pass. Calling fail on the vertx TestContext object - <code>context.fail()</code> - will also not fail the test.</p>

<p>The core issue is this: any call to <code>fail()</code> after <code>async.complete()</code> will not fail the test, only the console will show the error. But without the call to <code>async.complete()</code>, the code in the verticle (called upon consuming from the event bus), will not have run before the test assertions are called.</p>

<p>Without the call to <code>async.complete()</code>, the test will it appears never complete.</p>

<p>What is the correct approach to this?</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/53379368/correct-way-to-fail-a-unit-test-from-within-a-callback-using-vertx-unit,"['asynchronous', 'junit', 'junit4', 'vert.x', 'vertx-verticle']",1347,TRUE,1,1
GoogleMaps break business logic Unit Tests,"<p>I'm writing an iOS app, that uses GoogleMaps. I've written some unit tests to test separate business logic modules. They look like this:</p>

<pre><code>func testIfStationsExistNearPoint1() {
        let comMangager = CommunicationManager()
        comMangager.getListOfStations(coordinates: Coordinates(longitude: Constants.Point1CoordinateLongitude, latitude: Constants.Point1CoordinateLatitude), distance: 50, completion: { (json) in
            if (json != nil) {
                let stations = StationWrapper.sharedStationWrapper.jsonToStations(json: json!)

                assert(stations.count &gt; 0, String(format:""%ld stations"", stations.count))
            }
            else {
                XCTFail(""json is nil"")
            }
        }) { (error) in
            XCTFail(String(format:""List of stations returned error: %@"", error))
        }
    }
</code></pre>

<p>Note, that those unit tests are completely separated from UI (Where GoogleMaps are used. Coordinates is a custom class, not GoogleMaps CLLocationCoordinate2D).</p>

<p>Also note, that application itself works ok. And I'm 100% sure, that in main app, all code, that works with map drawing, is called in main thread.</p>

<p>Yet somehow I receive this error, when trying <em>any</em> of my unit tests:</p>

<blockquote>
  <p>com.google.Maps.LabelingBehavior (15): -[UIApplication
  applicationState] must be used from main thread only</p>
</blockquote>

<p>When I set a breakpoint in the very first line of this unit test, it's not even hit. Same thing for both simulator and real device.</p>

<p>I wonder, how's that even possible, since I'm not using Google Maps anywhere in unit tests? I've tried to search for similar cases, yet haven't found any, that was related unit testing.</p>

<p>Any ideas what's wrong here because I feel completely stuck?</p>
",https://stackoverflow.com/questions/49299595/googlemaps-break-business-logic-unit-tests,"['ios', 'swift', 'google-maps', 'unit-testing']",179,FALSE,1,1
XUnit - design architecture for placing reusable tests helpers in an external shared class library with Extension Methods,"<p>Designing some XUnit tests for a very large number of business object classes (over 400). There will be a lot of repeated code so employing DRY principles we have a number of options of how to abstract and encapsulate code into shared class libraries.</p>

<ol>
<li>Traditional static helper class. A method for common tests, passing in parameters for the instance and any settings.</li>
<li>Extension Methods on the business class. As above but as an extension method on the business class/interface type itself.</li>
</ol>

<p><strong>Creating tests as Extension Methods (option 2), does this break the accepted principle of Unit Testing which prompts to test only small specific unit. As now chains of small tests can be grouped into a parent test?</strong> </p>

<p><strong>Are there other design architecture patterns which enable reuse of shared libraries for common tests to domain entities?</strong></p>

<p>The code below demonstrates the two options. Please note the Helper classes will be in another Class Lib project separate from the UnitTest class (Test_Person) project. </p>

<pre><code>using Xunit;
namespace CCTools.UnitTest.Main.XUnit.UnitTestPatterns
{

public class Test_Person
{
    /// &lt;summary&gt;
    ///     Use Extension methods, quick to code and easy to read.
    /// &lt;/summary&gt;
    [Fact]
    public static void Test_Stuff_UseExtenions_A()
    {
        Person p = new Person();
        //Do lots of other config and tests...
        p.Test_IncreaseCreditRating(187);
        p.IsManager = true;
        p.Test_CreditRating_is_valid_for_manager();
    }

    [Fact]
    public static void Test_Stuff_UseExtenions_B()
    {
        Person p = new Person();
        //Do lots of other config and tests...

        p.Test_IncreaseCreditRating(59);
        p.Test_CreditRating_is_valid_for_manager();
    }

    /// &lt;summary&gt;
    ///     Use traditional Helper methods, not as easy to read or code.
    /// &lt;/summary&gt;
    [Fact]
    public static void Test_Stuff_UseHelper_A()
    {
        Person p = new Person();
        //Do lots of other config and tests...

        PersonUniTestHelper.Test_IncreaseCreditRating(p, 10);
        p.IsManager = true;
        PersonUniTestHelper.Test_CreditRating_is_valid_for_manager(p);
    }
}
/// &lt;summary&gt;
///     Extension methods, which makes coding far easier on the eye and one is able to locate all methods
///     using intellisense at a glance.
/// &lt;/summary&gt;
public static class PersonUniTestExtensionMethods
{
    public static void Test_IncreaseCreditRating(this Person person, int creditRating)
    {
        person.IncreaseCreditRating(creditRating);
        if (creditRating &gt;= 100) Assert.Equal(100 * 1000, person.CreditLimit);
        else Assert.Equal(creditRating * 1000, person.CreditLimit);
    }

    public static void Test_CreditRating_is_valid_for_manager(this Person person)
    {
        if (person.IsManager) Assert.True(person.CreditRating &gt;= 50);
    }
}

/// &lt;summary&gt;
///     Traditional static class for helpers
/// &lt;/summary&gt;
public static class PersonUniTestHelper
{
    public static void Test_IncreaseCreditRating(Person person, int creditRating)
    {
        person.IncreaseCreditRating(creditRating);
        if (creditRating &gt;= 100) Assert.Equal(100 * 1000, person.CreditLimit);
        else Assert.Equal(creditRating * 1000, person.CreditLimit);
    }

    public static void Test_CreditRating_is_valid_for_manager(Person person)
    {
        if (person.IsManager) Assert.True(person.CreditRating &gt;= 50);
    }
}


public class Person
{
    public string FirstName { get; set; }
    public int CreditLimit { get; private set; }
    public int CreditRating { get; private set; }

    public bool IsManager { get; set; }

    /// &lt;summary&gt;
    ///     Simple action to set CreditLimit based on Rating.
    /// &lt;/summary&gt;
    public void IncreaseCreditRating(int creditRating)
    {
        CreditRating = creditRating;
        CreditLimit = creditRating &gt;= 100 ? 100 * 1000 : creditRating * 1000;
    }
}
}
</code></pre>
",https://stackoverflow.com/questions/52003110/xunit-design-architecture-for-placing-reusable-tests-helpers-in-an-external-sh,"['c#', 'unit-testing', 'xunit']",803,FALSE,1,0
Jasmine - Unable to get response of an async call,"<p>I am facing an issue when unit testing my AngularJS service using Jasmine. This is the test case which is causing the issue:</p>

<pre><code>describe( '#getData', function () {
    it( 'Gets the data', function ( done ) {
        var promise = service.getData();
        $rootScope.$apply();
        console.log( promise );

        promise.then( function ( resp ) {
            expect( resp ).toEqual( mockData );
            done();
        } ).catch( function () {
            done();
        } ).finally( function () {
            done();
        } );
    } );
} );
</code></pre>

<p>This is pretty straight forward. I'm trying to test the method <code>getData</code> of the <code>service</code>. All the variables are in-place and there are no console errors.</p>

<p>The statement <code>console.log( promise )</code> prints something like this on the console:</p>

<pre><code>Promise{$$state: Object{status: 1, value: Object{status: ..., data: ...}}}
</code></pre>

<p>Which means that <code>promise</code> is a valid Promise object. But the issue here is that I am not able to test the data returned by this promise. When I call <code>then</code> on the promise object and call <code>done</code> function in any of the handlers (<code>then</code>, <code>catch</code>, or <code>finally</code>), the control doesn't go in any one of them and the test runner times out.</p>

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

<p>I tried to increase the default timeout as well, but that makes the test skipped. On the other hand, if I try to execute this case synchronously (without using <code>done</code>), it passes successfully.</p>

<p>How can I test the response in the test case asynchronously?</p>
",https://stackoverflow.com/questions/49938541/jasmine-unable-to-get-response-of-an-async-call,"['javascript', 'angularjs', 'promise', 'jasmine', 'karma-jasmine']",537,TRUE,1,1
Injecting Dependencies into Entities with Entity Framework,"<p>Before this is marked as duplicate I have looked around to find an answer for my question, but my scenario is a little more specific than other similar questions found on SO and I don't think anwers like ""it's a bad practice"" apply.</p>

<p>I am working on some design choices for modeling the domain following the DDD approach with Entity Framework, and I am interested in a way to inject dependencies into Entities. To be precise the only dependencies I consider worth injecting are factories for domain objects that belong to the aggregate root I am working with or wrappers around static classes like the one below:</p>

<pre><code>public class CurrentTimeProvider : ITimeProvider
{
    public DateTime GetTime()
    {
        return DateTime.Now();
    }
}
</code></pre>

<p>The purpose of the wrapper is to make unit testing easier and I am not a fan of the double dispatch pattern for this case as it breaks encapsulation.</p>

<p>Sample entity:</p>

<pre><code>public class ActivationToken
{
    protected ITimeProvider TimeProvider;

    public ActivationToken(ITimeProvider timeProvider)
    {
        TimeProvider = timeProvider;
    }

    public virtual DateTime? ConsumedTime { get; protected set; }

    public virtual void Consume()
    {
        ConsumedTime = TimeProvider.GetTime();
    }
}
</code></pre>

<p>So my question is how do I get Entity Framework to provide my dependency when creating the instance?</p>
",https://stackoverflow.com/questions/48480889/injecting-dependencies-into-entities-with-entity-framework,"['c#', 'entity-framework', 'oop']",912,TRUE,1,2
Run a python unittest only if another one passes,"<p>I'm new to unit testing and I am writing a class to model the behavior of a pinhole camera.</p>

<p>I have several unit tests in Python using the unittest module, and my Camera class has a lookAt method which makes it look at a certain point, i.e it rotates the camera frame such that it points at the target.
I also have a method which projects a 3D point into the camera's picture.</p>

<p>My scenario here is that i first test the lookAt method, then if the test passes, i use the lookAt method to make my camera look at a cube and then project that cube onto my camera's picture (the projection is the thing to test here).</p>

<p>Is there a possibility in the unittest module for me to run a test in another test? Or should i just make a lookAt matrix by hand and then test the projection separately(I think this would be the best practice here)?</p>
",https://stackoverflow.com/questions/49616239/run-a-python-unittest-only-if-another-one-passes,"['python', 'unit-testing', 'camera', 'python-unittest']",1529,TRUE,1,1
How to inject a service into a constructor when creating a new instance of an object?,"<p><strong>The Setup:</strong> I've registered a configuration service that pulls data from appsettings.json and it works fine. I also have a controller that uses that service to get settings from that file, again this works like it's supposed to:</p>



<pre class=""lang-cs prettyprint-override""><code>public class ApiController : Controller
{
    private readonly string _apiUri;
    public ApiController(IOptions&lt;Configurator&gt; config)
    {
        _apiUri = config.Value.ApiSettings.ApiBaseUrl + 
                  config.Value.ApiSettings.ApiVersion;
    }
    //...
}
</code></pre>

<p>Now note, I'm new to automated unit testing and to asp.net core. What I'd like to do is to decouple the ApiController's reliance on the injected service so that I can use a separate XUnit test project to test functions inside the controller, similar to the example in <a href=""http://www.dotnetcurry.com/aspnet-core/1414/unit-testing-aspnet-core"" rel=""nofollow noreferrer"">this tutorial</a>.</p>

<p>To do this I created a model and interface representing the ApiSettings section of my appsettings.json file:</p>

<pre class=""lang-cs prettyprint-override""><code>""ApiSettings"": {
    ""ApiBaseUrl"": ""https://example.com/api/"",
    ""ApiVersion"": ""v1/""
}
</code></pre>

<p>The Model:</p>

<pre class=""lang-cs prettyprint-override""><code>public class ApiSettings : IApiSettings
{
    public string ApiBaseUri { get; set; }
    public string ApiVersion { get; set; }
}
</code></pre>

<p>The Interface:</p>

<pre class=""lang-cs prettyprint-override""><code>public interface IApiSettings
{
    string ApiBaseUri { get; set; }
    string ApiVersion { get; set; }
}
</code></pre>

<p>I then created a class that would be dependent on the service to inject the settings:</p>

<pre class=""lang-cs prettyprint-override""><code>public class ApiSettingsBuilder
{
    private readonly string _apiUri;
    public ApiSettingsBuilder(IOptions&lt;Configurator&gt; config)
    {
        _apiUri = config.Value.ApiSettings.ApiBaseUrl + 
                  config.Value.ApiSettings.ApiVersion;
    }

    public string ApiUri { get { return _apiUri; } }
}
</code></pre>

<p><strong>The Problem:</strong> How do I create an new instance of this class?</p>

<pre class=""lang-cs prettyprint-override""><code>public class ApiController : Controller
{
    private readonly string _apiUri;
    public ApiController()
    {
        ApiSettingsBuilder builder = new ApiSettingsBuilder(/*What do I do here*/);
        _apiUri = builder.ApiUri;
    }

    public ApiController(IApiSettings settings)
    {
        //For testing
        _apiUri = settings.ApiBaseUrl + settings.ApiVersion;
    }
    //...
} 
</code></pre>

<p>Also, I know this is all a bit overkill, but I would still like an answer because It would possibly be useful in other scenarios.</p>
",https://stackoverflow.com/questions/51105733/how-to-inject-a-service-into-a-constructor-when-creating-a-new-instance-of-an-ob,"['unit-testing', 'asp.net-core', 'dependency-injection', 'asp.net-core-mvc', 'asp.net-core-2.0']",331,TRUE,1,1
How to avoid jasmine throw the error: XXX has already been spied upon?,"<p><strong>Background</strong></p>

<p>I have two Case need to test</p>

<ul>
<li><p>should form valid when going to next page</p>

<ol>
<li>set form valid is true</li>
<li>call <code>goToNextPage()</code></li>
<li>expect result is truthy</li>
</ol></li>
<li><p>should form valid when filling out option info then going to next page</p>

<ol>
<li>set form valid is true</li>
<li><strong>open option info block</strong> </li>
<li><strong>ensure the form is valid</strong></li>
<li>call <code>goToNextPage()</code></li>
<li>expect result is truthy</li>
</ol></li>
</ul>

<hr>

<p><strong>Question</strong></p>

<p>In step 3 of the second test, It will throw an Error When I spy a property by <code>spyOnProperty</code> more than two times</p>

<p>spyOnProperty(myObject, 'myPropertyName').and.returnValue(...);</p>

<blockquote>
  <p>Error: 'myPropertyName' has already been spied upon</p>
</blockquote>

<p><strong>I refer to the solutions of the past few years and write a temporary solution below. Are there any easier ways to solve this now?</strong></p>

<ul>
<li><a href=""https://stackoverflow.com/q/28821511/7291379"">angular-unit-testing-with-jasmine-how-to-remove-or-modify-spyon</a></li>
<li><a href=""https://stackoverflow.com/questions/42084022/insertspyon-2-times-jquery-value-to-input-during-jasmine-tests"">insertspyon-2-times-jquery-value-to-input-during-jasmine-tests</a>

<ul>
<li><a href=""https://stackoverflow.com/questions/30707283/jasmine-spyon-with-multiple-returns"">Jasmine spyOn with multiple returns</a></li>
</ul></li>
</ul>

<hr>

<p><strong>My Temp Solution</strong></p>

<ul>
<li>set <code>jasmine.getEnv().allowRespy(true);</code></li>
<li>cache the first spy and use it later</li>
</ul>

<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>class SamplePageHelper {

  private respyHelper = new JasmineRespyHelper();

  constructor(
    public samplePage: SamplePage
  ) {

  }

  fakeValid() {
    // spyOnProperty(this.samplePage, 'isValid').and.returnValue(true);
    this.respyHelper.spyOnProperty(this.samplePage, 'isValid').and.returnValue(true);
  }



}
// helper
class JasmineRespyHelper {

  private cacheList = new Map();

  constructor() {
    jasmine.getEnv().allowRespy(true);
  }

  spyOnProperty &lt; T &gt; (object: T, property: keyof T, accessType ? : 'get' | 'set'): jasmine.Spy {
    const objectKey = object.constructor.toString().substring(0, 15);
    const cacheKey = `${objectKey}_${property}_${accessType || ''}`;
    //
    let spy = this.cacheList.get(cacheKey);
    const isNoCached = !spy;
    if (isNoCached) {
      spy = spyOnProperty(object, property, accessType);
      this.cacheList.set(cacheKey, spy);
    }
    //
    return spy;
  }
}</code></pre>
</div>
</div>
</p>

<hr>

<p><strong>Online Sample</strong></p>

<p><a href=""https://stackblitz.com/edit/jsamine-respy?file=src/test/sample.spec.ts"" rel=""nofollow noreferrer"">https://stackblitz.com/edit/jsamine-respy?file=src/test/sample.spec.ts</a></p>

<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""false"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>describe('demo (no TestBed):', () =&gt; {

  let samplePage;
  let samplePageHelper;
  
  beforeEach(() =&gt; {
    samplePage = new SamplePage();
    samplePageHelper = new SamplePageHelper(samplePage);
  })

  it('shoud valid when write option fields then go to next page', () =&gt; {
    samplePageHelper.fakeValid();
     //
    samplePage.openOptionFieldBlock();
    //  new option field value will trigger form validator

    // ensure `goToNextPage()` can be executed needs to specify isValid to true again
    // Error: isValid has already been spied upon
    samplePageHelper.fakeValid();


    const isSuccess = samplePage.goToNextPage();

    expect(isSuccess).toBeTruthy();
  })

  it('shout valid when go to next page', () =&gt; {
    samplePageHelper.fakeValid();

    const isSuccess = samplePage.goToNextPage();

    expect(isSuccess).toBeTruthy();
  })
});


class SamplePage {

  private formService = new FormServiceStub();

  get isValid() {
    // trigger form field's validator
    // real code like this : formService.validationAll(); 
    return this.formService.valiationAll();
  }

  constructor() {
  }

  openOptionFieldBlock() {
    if (this.isValid) {
      // do someting 
    }
  }

  goToNextPage() {
    if (this.isValid) {
      // do someting

      const isSuccess = true;
      return isSuccess;
    }

    return false;
  }

  showOptionFields() {
    return true;
  }


}


// stub
class FormServiceStub {
  valiationAll() {
    // it's have more codition in real code , return true for the demo
    return true;
  }
}

class SamplePageHelper {

  constructor(
    public samplePage: SamplePage
  ) {

  }

  fakeValid() {
    spyOnProperty(this.samplePage, 'isValid').and.returnValue(true);
  }



}</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/51231406/how-to-avoid-jasmine-throw-the-error-xxx-has-already-been-spied-upon,"['javascript', 'jasmine', 'karma-jasmine']",8031,FALSE,1,0
Build server + JRE Extensions,"<p>I'm looking to build a javaFX app with headless unit-testing with Monocle and Maven. I've been able to get headless testing to work locally with building the monocle jar myself and loading it into my /Extensions java folder as specified here: <a href=""https://stackoverflow.com/questions/29116819/javafx-maven-testfx-monocle-dont-work-together"">JavaFX + maven + TestFX + monocle don&#39;t work together</a>. But I don't own the build servers so it will be difficult for me to install Monocle into the Java extensions folder. I'm looking for a work around.</p>

<p>I am using Maven and tried using the tag <a href=""https://maven.apache.org/pom.html#Extensions"" rel=""nofollow noreferrer"">https://maven.apache.org/pom.html#Extensions</a> to include monocle:</p>

<pre><code>&lt;extensions&gt;
    &lt;extension&gt;
        &lt;groupId&gt;org.testfx&lt;/groupId&gt;
        &lt;artifactId&gt;openjfx-monocle&lt;/artifactId&gt;
        &lt;version&gt;8u76-b04&lt;/version&gt;
    &lt;/extension&gt;
&lt;/extensions&gt;  
</code></pre>

<p>This doesn't work, even with a separate dependency in the tag. I also tried including the monocle jar in the source code and including it with the java.ext.dirs parameter:</p>

<pre><code>&lt;argLine&gt;-Dtestfx.robot=glass -Dglass.platform=Monocle -Dmonocle.platform=Headless -Dprism.order=sw -Dheadless.geometry=1600x1200-32 -Djava.ext.dirs=:&lt;path&gt;/monocle-jars&lt;/argLine&gt;
</code></pre>

<p>But this gives me this error:</p>

<p>java.lang.NoClassDefFoundError: javafx/application/Application</p>

<p>I think that changing to a custom java.ext.dirs value causes the javafx libs to not be found.</p>

<p>Any suggestions on how to build this without having to manually install the Monocle Java extension? </p>
",https://stackoverflow.com/questions/52488128/build-server-jre-extensions,"['java', 'maven', 'javafx', 'testfx']",39,FALSE,1,0
Unity Dependency Injection and Helper functions,"<p>I have a set of services that are used to read/write to the database. These get injected into my controllers:</p>

<pre><code>ISystemSettingService _systemSettingService = null;
IStatusTypeService _statusTypeservice = null;

public MyController(
    ISystemSettingService systemSettingService,
    IStatusTypeService statusTypeservice)
{
    _systemSettingService = systemSettingService;
    _statusTypeservice = statusTypeservice;
}
</code></pre>

<p>So when I need something from <code>_systemSettingService</code> I can easily get it. Now I also have some static helper classes/functions which I call from <code>MyController</code>. In these functions I often need access to the services so I can access the DB. e.g. I have a <code>Validate(string userData, ISystemSettingService systemSettingService)</code> function that accepts some data passed in from the user.</p>

<p>So far, into the <code>Validate</code> function I have been passing in the <code>_systemSettingService</code> so I can use it. I'm not sure this is correct.</p>

<p>My question - is my approach correct or, in the <code>Validate</code> function should I be creating a unity container to <code>Resolve</code> an instance of my <code>ISystemSettingService</code> or, as I have been reading about, should my helper class NOT be static, and I should inject <code>ISystemSettingService</code> into the constructor which will apparently make unit testing easier.</p>

<p>I'm a bit confused! Thanks.</p>
",https://stackoverflow.com/questions/48597297/unity-dependency-injection-and-helper-functions,"['c#', 'dependency-injection']",75,FALSE,1,0
javax.ws.rs REST testing by target - where to get or set the server address?,"<p>Where I am unit testing a REST function created in javax.ws.rs, and using target() for URL, as in <a href=""https://stackoverflow.com/a/28726499/715269"">https://stackoverflow.com/a/28726499/715269</a>, and I don't know how to set the server part of the URL. </p>

<p>If I set it in hard way, the test will run only in one surrounding, on release server, for example. But normally, I run the application on any server, and API functions work on different servers, depending on where I had launch the application. </p>

<p>If I won't set any server for target:</p>

<pre><code>String targetUrl = ""/api/v1/documentTypes"";
try (Response response = target(targetUrl).request().post(Entity.json(simpleJson))) {
</code></pre>

<p>And look for the URI in response, I see some server part set there (<a href=""http://localhost:9998/"" rel=""nofollow noreferrer"">http://localhost:9998/</a>), but I don't know where is it from, and this imitated server does not know the API function from <code>targetUrl</code> string. </p>

<p>How should I write this part of unit test, so as to be run universally?</p>

<p>I think that maybe overrode configure() method could help, but I am not sure.</p>
",https://stackoverflow.com/questions/50076949/javax-ws-rs-rest-testing-by-target-where-to-get-or-set-the-server-address,"['java', 'rest', 'unit-testing', 'jersey', 'jersey-test-framework']",198,FALSE,1,1
How to debug Vue CLI 3 unit tests with WebStorm? Debugger doesn&#39;t hit breakpoint,"<p><strong>Question</strong></p>

<ol>
<li>What do I have to do to make WebStorm hit the breakpoint?</li>
<li>Is it necessary to set the %NODE_DEBUG_OPTION%? If yes, how do I do this in combination with vue-cli.service?</li>
</ol>

<p><strong>Steps to reproduce:</strong></p>

<ol>
<li>vue create myapp

<ul>
<li>Set options to:

<ul>
<li>? Please pick a preset: <strong>Manually select features</strong></li>
<li>? Check the features needed for your project: <strong>Babel, Unit</strong></li>
<li>? Pick a unit testing solution: <strong>Jest</strong></li>
<li>? Where do you prefer placing config for Babel, PostCSS, ESLint, etc.? <strong>In package.json</strong></li>
<li>? Save this as a preset for future projects? <strong>No</strong></li>
</ul></li>
</ul></li>
<li>Open myapp in WebStorm</li>
<li>Open npm Tool Windows</li>
<li>Set breakpoint in tests/unit/example.spec.js</li>
<li>Rightclick on test:unit->Debug test:unit</li>
</ol>

<p><strong>console output:</strong></p>

<blockquote>
  <p>To debug the ""test:unit"" script, make sure the %NODE_DEBUG_OPTION% string is specified as the first argument for the node command you'd like to debug.
  For example:</p>

<pre><code> ""scripts"": {
   ""start"": ""node %NODE_DEBUG_OPTION% server.js""  
 }
</code></pre>
  
  <p>myapp@0.1.0 test:unit C:\Users\c-jay\myapp
  vue-cli-service test:unit</p>
  
  <p>PASS  tests/unit/example.spec.js</p>
</blockquote>

<p><strong>Configuration:</strong> </p>

<ul>
<li>WebStorm 2018.2.4</li>
<li>Vue CLI v3.0.5</li>
</ul>
",https://stackoverflow.com/questions/53031642/how-to-debug-vue-cli-3-unit-tests-with-webstorm-debugger-doesnt-hit-breakpoint,"['unit-testing', 'vue.js', 'webstorm', 'jestjs', 'vue-cli-3']",1798,TRUE,1,1
Docker build output scripts ran from dockerfile,"<p>I'm running a </p>

<pre><code>docker build -t $NAME -f Dockerfile.test .
</code></pre>

<p>command.</p>

<p>In my <code>Dockerfile.test</code> I have at the end (I'm copying certain things to make everything work) </p>

<pre><code>CMD[""bin/bash"", ""-c"", ""bash /run-script.sh &amp;&amp; bash /run-another-script.sh""]
</code></pre>

<p>When I look at my build stages in Jenkins, I can only see that everything passed ok, the </p>

<pre><code>CMD /bin/bash -c bash /run-script.sh &amp;&amp; bash /run-another-script.sh
</code></pre>

<p>was executed, and since I'm running a sonarqube scan in these scripts, I can see in my sonarqube that a scan happened (which is ok).</p>

<p>But since I'm running PHP unit tests in the scripts, I'm a bit suspicious that this part, because in the Jenkins this was done very quickly (on my local computer running unit testing with coverage report takes ~20min), failed, or didn't run as it should.</p>

<p>So I'd like to see the output of these scripts (<code>run-script.sh</code> and <code>run-another-script.sh</code>) to be sure that everything works as intended.</p>

<p>I've heard that docker won't show the output of the scripts that write/delete lines in the terminal, so this might be the reason (I'm guessing ofc).</p>

<p>Is there a way to show the output?</p>
",https://stackoverflow.com/questions/53264615/docker-build-output-scripts-ran-from-dockerfile,"['docker', 'jenkins']",2300,TRUE,1,1
Callback not executed in Android unit test with injected mock object,"<p>I am new to unit testing in Android and have gone through several tutorials to get myself familiar with mockito and robolectric. </p>

<p>My app is using Dagger 2 to inject my <code>EventService</code> into my <code>MainActivity</code>. For my <code>MainActivityUnitTest</code>, I have set up a <code>TestServicesModule</code> to provide a mocked version of <code>EventService</code> so that I can use Robolectric to run unit tests against my <code>MainActivity</code></p>

<p>I'm having an issue getting the <code>ServiceCallback</code> on my <code>EventService.getAllEvents(callback: ServiceCallback)</code> to execute in the unit test. I have verified in the <code>@Setup</code> of my <code>MainActivityUnitTest</code> class that the <code>EventService</code> is being injected as a mocked object. I have gone through several tutorials and blog posts and as far as I can tell, I am doing everything correctly. The <code>refreshData()</code> function in <code>MainActivity</code> is getting called successfully, and I can see that the call to <code>eventsService.getAllEvents(callback)</code> is being executed. But the <code>doAnswer {}</code> lambda function is never getting executed. </p>

<p>Here's my relevant code:</p>

<p>AppComponent.kt</p>

<pre><code>@Singleton
@Component(modules = [
    AppModule::class,
    ServicesModule::class,
    FirebaseModule::class
])
interface AppComponent {
    fun inject(target: MainActivity)
}
</code></pre>

<p>ServicesModule.kt</p>

<pre><code>@Module
open class ServicesModule {
    @Provides
    @Singleton
    open fun provideEventService(db: FirebaseFirestore): EventsService {
        return EventsServiceImpl(db)
    }
}
</code></pre>

<p>EventsService.kt </p>

<pre><code>interface EventsService {
    fun getAllEvents(callback: ServiceCallback&lt;List&lt;Event&gt;&gt;)
    fun getEvent(id: String, callback: ServiceCallback&lt;Event?&gt;)
}
</code></pre>

<p>MainActivity.kt</p>

<pre><code>class MainActivity : AppCompatActivity() {
    @Inject lateinit var eventsService: EventsService

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        (application as App).appComponent.inject(this)
        ...
    }

    override fun onStart() {
        super.onStart()
        refreshData()
    }

    eventsService.getAllEvents(object: ServiceCallback&lt;List&lt;Event&gt;&gt; {
        override fun onCompletion(result: List&lt;Event&gt;) {
            viewModel.allEvents.value = result
            loading_progress.hide()
        }
    })
}
</code></pre>

<p>Now we get into the tests:</p>

<p>TestAppComponent.kt </p>

<pre><code>@Singleton
@Component(modules = [
    TestServicesModule::class
])
interface TestAppComponent : AppComponent {
    fun inject(target: MainActivityUnitTest)
}
</code></pre>

<p>TestServicesModule.kt </p>

<pre><code>@Module
class TestServicesModule {

    @Provides
    @Singleton
    fun provideEventsService(): EventsService {
        return mock()
    }
}
</code></pre>

<p>MainActivityUnitTest.kt</p>

<pre><code>@RunWith(RobolectricTestRunner::class)
@Config(application = TestApp::class)
class MainActivityUnitTest {

    @Inject lateinit var eventsService: EventsService

    @Before
    fun setup() {
        val testComponent = DaggerTestAppComponent.builder().build()
        testComponent.inject(this)
    }

    @Test
    fun givenActivityStarted_whenLoadFailed_shouldDisplayNoEventsMessage() {
        val events = ArrayList&lt;Event&gt;()

        doAnswer {
            //this block is never hit during debug
            val callback: ServiceCallback&lt;List&lt;Event&gt;&gt; = it.getArgument(0)
            callback.onCompletion(events)
        }.whenever(eventsService).getAllEvents(any())

        val activity = Robolectric.buildActivity(MainActivity::class.java).create().start().visible().get()
        val noEventsView = activity.findViewById(R.id.no_events) as View

        //this always evaluates to null because the callback is never set from the doAnswer lambda
        assertThat(callback).isNotNull()
        verify(callback)!!.onCompletion(events)
        assertThat(noEventsView.visibility).isEqualTo(View.VISIBLE)
    }
}
</code></pre>

<p><strong>Edit: Adding App and TestApp</strong></p>

<pre><code>open class App : Application() {
    private val TAG = this::class.qualifiedName
    lateinit var appComponent: AppComponent

    override fun onCreate() {
        super.onCreate()
        appComponent = initDagger(this)
    }

    open fun initDagger(app: App): AppComponent {
        return DaggerAppComponent.builder().appModule(AppModule(app)).build()
    }
}

class TestApp : App() {
    override fun initDagger(app: App): AppComponent {
        return DaggerTestAppComponent.builder().build()
    }
}
</code></pre>
",https://stackoverflow.com/questions/52321268/callback-not-executed-in-android-unit-test-with-injected-mock-object,"['android', 'kotlin', 'mockito', 'dagger-2', 'robolectric']",687,TRUE,1,1
Clarification on this Jasmine Error: this.http.get is not a function clarification,"<p>I keep running into this error when I try unit testing any of my functions that use a service in my component class. Here is a part of my function. </p>

<pre><code>loadUser() {
this.httpService.getData(AppConfig.URL_UserById + ""?UserID="" + this.userId)
  .catch((error: Response | any) =&gt; {
    this.showAlertWindow(this.exceptionMessage);
    console.error(error.message || error);
    return Observable.throw(error.message || error);
  })
</code></pre>

<p>This part retrieves the data from a url and throws an error if there is a problem. getData is a service that makes a get request .I am just trying to test if the method showAlertWindow is being called. Now I am pretty sure my test code is correct but I have to be missing something to be receiving this error. I am guessing that jasmine does not know what to do with the line <code>this.httpService.getData(...)</code> Thank you.</p>

<p>Test:</p>

<pre><code>  fit('should have getUsers() call showAlertWindow', () =&gt; {

 let window = spyOn(userComponent, 'showAlertWindow');

 userComponent.loadUser(); //Fails here

 expect(window).toHaveBeenCalled();
</code></pre>

<p>})</p>

<p>Full Error:</p>

<pre><code>    Error: Cannot call Promise.then from within a sync test.
Error: Cannot call Promise.then from within a sync test.
    at SyncTestZoneSpec.webpackJsonp../node_modules/zone.js/dist/zone-testing.js.SyncTestZoneSpec.onScheduleTask (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone-testing.js:365:1)
    at ZoneDelegate.webpackJsonp../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:401:1)
    at Zone.webpackJsonp../node_modules/zone.js/dist/zone.js.Zone.scheduleTask (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:232:1)
    at Zone.webpackJsonp../node_modules/zone.js/dist/zone.js.Zone.scheduleMicroTask (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:252:1)
    at scheduleResolveOrReject (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:862:1)
    at ZoneAwarePromise.then (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:962:1)
    at ApplicationInitStatus.webpackJsonp../node_modules/@angular/core/esm5/core.js.ApplicationInitStatus.runInitializers (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/esm5/core.js:3580:1)
    at TestBed.webpackJsonp../node_modules/@angular/core/esm5/testing.js.TestBed._initIfNeeded (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/esm5/testing.js:1011:1)
    at TestBed.webpackJsonp../node_modules/@angular/core/esm5/testing.js.TestBed.get (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/esm5/testing.js:1050:1)
    at Function.webpackJsonp../node_modules/@angular/core/esm5/testing.js.TestBed.get (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/esm5/testing.js:834:1)
</code></pre>

<p>If somebody can give me some insight on the meaning behind this error, that would be great. Thanks.</p>

<p>Test config:</p>

<pre><code>import { HttpService } from '../../services/http.service';
import { TestBed, async, inject, fakeAsync, ComponentFixture } from ""@angular/core/testing"";
import { UserComponent } from './user.component';
import { Observable } from 'rxjs';


    fdescribe('User Component', () =&gt; {
    let httpService: HttpService;
    let userComponent: UserComponent

beforeEach(async() =&gt; {
    TestBed.configureTestingModule({
      declarations: [
        UserComponent, 
      ],
 providers: [
  HttpService,
 ],
 }).compileComponents();
  });
   beforeEach(() =&gt; {
 userComponent = fixture.componentInstance;
 httpService = TestBed.get(HttpService);

 fit('should have getUsers() call showAlertWindow', () =&gt; {

     let window = spyOn(userComponent, 'showAlertWindow');

     userComponent.loadUser();

     expect(window).toHaveBeenCalled();


   })
</code></pre>

<p>Edit: There are two possible solutions. I solved the error by spying on my service and returning an observable. <code>spyOn(httpService, 'getData).and.returnValue(Observable.of('test'));</code> Or JanRecker's solution, which is more practical. </p>
",https://stackoverflow.com/questions/51198157/clarification-on-this-jasmine-error-this-http-get-is-not-a-function-clarificati,"['angular', 'unit-testing', 'jasmine', 'automated-tests', 'karma-jasmine']",4177,TRUE,1,1
Inner catch skipped under strange circumstances,"<p>I discovered a really strange bug in a codebase I've been working on, which I only recently was able to isolate and create something reproducible from. The bug is that the catch inside <code>simulate_container_init</code> is skipped when <code>throw_threshold</code> is even. <code>throw_threshold</code> is used in <code>ex_trigger</code> to simulate objects throwing when copied in situations such as container construction or assignment for unit testing purposes.</p>

<p>I originally thought this was a MSVC compiler bug(in 14.16 at the time of this writing), but after successfully reproducing it on GCC 7.1 &amp; Clang 3.9.1(nearly the oldest of each that supports my example), I'm not sure what to make of it anymore, as the code both appears correct and functions correctly when <code>throw_threshold</code> is odd.</p>

<pre><code>#include &lt;cstdint&gt;
#include &lt;atomic&gt;
#include &lt;memory&gt;
#include &lt;random&gt;
#include &lt;iostream&gt;
#include &lt;exception&gt;
#include &lt;type_traits&gt;

// Used to trigger an exception after a number of constructions have occurred.
struct ex_trigger
{
private:
    static std::atomic&lt;uint32_t&gt; ctor_count;
    static std::atomic&lt;uint32_t&gt; throw_threshold;

public:
    static inline void set_throw_threshold(uint32_t value) noexcept
    {
        throw_threshold.store(value, std::memory_order_release);
    }

    std::atomic&lt;uint32_t&gt; value;

    inline ex_trigger(const ex_trigger&amp; source) :
        value(source.value.load(std::memory_order_acquire))
    {
        if (ctor_count.load(std::memory_order_acquire) &gt;= 
            throw_threshold.load(std::memory_order_acquire)) {
            throw std::logic_error(""test"");
        }

        ctor_count.fetch_add(1);
    }
    inline ex_trigger(uint32_t value) noexcept :
        value(value)
    {
        ctor_count.fetch_add(1);
    }
};
std::atomic&lt;uint32_t&gt; ex_trigger::ctor_count;
std::atomic&lt;uint32_t&gt; ex_trigger::throw_threshold;

// Simulates the construction of a container by copying an initializer list.
template&lt;class T&gt;
inline void simulate_container_ctor(std::initializer_list&lt;T&gt; values) {
    // Intentionally leaked to simplify this example.
    // Alignment of T is completely ignored for simplicity.
    auto sim_data = static_cast&lt;T*&gt;(
        ::operator new(sizeof(T) * values.size()));

    for (auto value : values) {
        if constexpr (std::is_nothrow_copy_constructible_v&lt;T&gt;) {
            new (sim_data++) T(value);
        } else {
            try {
                new (sim_data++) T(value);
            } catch (...) {
                // Placeholder for cleanup code which is sometimes skipped.
                std::cout &lt;&lt; ""caught [inner]\n"";
                throw;
            }
        }
    }
}

int main()
{
    // The ""inner"" catch handler within simulate_container_init will be skipped when the argument
    // to set_throw_threshold is even, but otherwise appears to work correctly when it's odd. Note
    // that the argument must be between 10-20 for an exception to be triggered in this example.
    ex_trigger::set_throw_threshold(11);
    try {
        simulate_container_ctor({
            ex_trigger(1),
            ex_trigger(2),
            ex_trigger(3),
            ex_trigger(4),
            ex_trigger(5),
            ex_trigger(6),
            ex_trigger(7),
            ex_trigger(8),
            ex_trigger(9),
            ex_trigger(10)
        });
    } catch (const std::logic_error&amp;) {
        std::cout &lt;&lt; ""caught [outer]\n"";
    }
    std::cin.get();
    return 0;
}
</code></pre>

<p>When <code>throw_threshold</code> is even, output is(incorrectly):</p>

<p>catch [outer]</p>

<p>When <code>throw_threshold</code> is odd, output is(as expected):</p>

<p>catch [inner]<br>
catch [outer]</p>

<p>I've spent countless hours debugging and trying different approaches, yet it seems I'm missing something. Anything to help make sense of this would be much appreciated.</p>
",https://stackoverflow.com/questions/53800783/inner-catch-skipped-under-strange-circumstances,"['c++', 'try-catch', 'c++17']",44,TRUE,0,1
Can a system call be programmatically interrupted?,"<p>I am trying to write a unit test for my ZeroMQ application (which I use through the <code>cppzmq</code> C++ layer). My problem is that when I try to close my context, it sometimes (seemingly randomly) fails. I don't know why exactly, except that the error code is set to EINTR, meaning an interrupted system call.</p>

<p>To write a (failing) unit test for this behavior (which I can then try to fix), I was thinking (<a href=""https://github.com/zeromq/cppzmq/pull/271"" rel=""nofollow noreferrer"">see also this PR</a>) it would be useful if I could somehow spoof these system calls that are getting interrupted. Inside this spoofed system call, I can then first just call the regular system call, but then before returning manually set the error code to EINTR. For instance, I would like to replace <a href=""http://man7.org/linux/man-pages/man2/recvmsg.2.html"" rel=""nofollow noreferrer""><code>recv</code></a> with something like:</p>

<pre><code>ssize_t recv(int sockfd, void *buf, size_t len, int flags) {
    ssize_t result = ::recv(sockfd, buf, len, flags);
    errno = EINTR;
    return result;
}
</code></pre>

<p>Is this possible? Is this wise (could I expect problems and if so which)? Is there another way to solve my unit testing problem?</p>
",https://stackoverflow.com/questions/53119771/can-a-system-call-be-programmatically-interrupted,"['c', 'unit-testing', 'zeromq', 'system-calls', 'interrupt']",198,TRUE,0,1
C++ using getline and stringstream with multiple classes and overloaded stream operator,"<p>I'm working on a university assignment to read in data from a file and could really use some help!</p>

<p>The data file contains weather data and looks like:</p>

<p>31/03/2016 9:00,14.6,175,17,0,1013.4,1016.9,1017,0,68.2,6,512,22.7,24.1,25.5</p>

<p>The assignment requires a class to read and store the date, time and all the int/double values. I have to use a date class to read the date, a time class to read the time and the WeatherData class brings it all together using overloaded stream operator. </p>

<p>I'm unit testing the WeatherData class (which will be used in an array of WeatherData classes) with a datafile that includes the date, time and just one double variable: 31/03/2016 9:00,14.6</p>

<p>The output I get is: 31/3/2016 0:0 0 </p>

<p>I've unit tested the Date and Time classes and they work as expected. I can't see why it fails after the date. Any help would be greatly appreciated!</p>

<p>TestWeatherData.cpp</p>

<pre><code>#include &lt;iostream&gt;
#include &lt;fstream&gt;
#include &lt;sstream&gt;
#include &lt;string&gt;
#include &lt;cstdlib&gt;
#include ""../Practice/date.h""
#include ""../Practice/time.h""
#include ""../Practice/weatherdata.h""

using namespace std;

istream &amp; operator &gt;&gt;( istream &amp; input, Date &amp; D )
{
  string temp;
  string convertToInt;
  int tempDay;
  int tempMonth;
  int tempYear;

  getline(input, temp);
  stringstream ss(temp);
  getline(ss, convertToInt, '/');
  tempDay = atoi(convertToInt.c_str());
  D.SetDay(tempDay);
  getline(ss, convertToInt, '/');
  tempMonth = atoi(convertToInt.c_str());
  D.SetMonth(tempMonth);
  getline(ss, convertToInt);
  tempYear = atoi(convertToInt.c_str());
  D.SetYear(tempYear);

  return input;
}

ostream &amp; operator &lt;&lt;( ostream &amp; os, const Date &amp; D )
{

  os &lt;&lt; D.GetDay() &lt;&lt; ""/"" &lt;&lt; D.GetMonth()
     &lt;&lt; ""/"" &lt;&lt; D.GetYear();

  return os;
}

istream &amp; operator &gt;&gt;( istream &amp; input, Time &amp; T )
{
  string temp;
  string convertToInt;
  int tempHours;
  int tempMinutes;

  getline(input, temp);
  stringstream ss(temp);
  getline(ss, convertToInt, ':');
  tempHours = atoi(convertToInt.c_str());
  T.SetHours(tempHours);
  getline(ss, convertToInt);
  tempMinutes = atoi(convertToInt.c_str());
  T.SetMinutes(tempMinutes);

  return input;
}

ostream &amp; operator &lt;&lt;( ostream &amp; os, const Time &amp; T )
{

  os &lt;&lt; T.GetHours() &lt;&lt; "":"" &lt;&lt; T.GetMinutes();

  return os;
}

istream &amp; operator &gt;&gt;( istream &amp; input, WeatherData &amp; W )
{
  string temp;
  string convertToDouble;
  Date tempDate;
  Time tempTime;
  double tempDP;

  input &gt;&gt; tempDate &gt;&gt; tempTime;
  W.setDate(tempDate);
  W.setTime(tempTime);
  getline(input, temp);
  stringstream ss(temp);
  getline(ss, convertToDouble);
  tempDP = atof(convertToDouble.c_str());
  W.setDP(tempDP);

  return input;
}

ostream &amp; operator &lt;&lt;( ostream &amp; os, const WeatherData &amp; W )
{

  os &lt;&lt; W.getDate() &lt;&lt; ' ' &lt;&lt; W.getTime() &lt;&lt; ' ' &lt;&lt; W.getDP();

  return os;
}

int main()
{
    ifstream infile( ""data.txt"" );
    if( !infile ) return -1;

    WeatherData W;

    infile &gt;&gt; W;

    cout &lt;&lt; W;

    return 0;
}
</code></pre>
",https://stackoverflow.com/questions/50048475/c-using-getline-and-stringstream-with-multiple-classes-and-overloaded-stream-o,"['c++', 'getline', 'stringstream']",157,FALSE,-2,1
Extracting data from a PDF,"<p>I have a system that ultimately creates a PDF files from html file. It works very similar to a mail merge. It grabs data from a database, merge's the data into palceholders in the html document and then converts the html file to a pdf.</p>

<p>When I am unit testing the html file I can look at the values in my place holder. For example if I had a  John Smith  and I want to validate that the name is ""John Smith"" I simply look the value of the div after the merge. </p>

<p>I need to do something similar with validating the data in the pdf. Using pdfbox and itext I was able to extract text from a location as well as text from the document but I can't find anything that would let me create a ""tag/placeholder/..."" and extract information from it similar to what I do with the html file. </p>

<p>Is this possible with a pdf?</p>
",https://stackoverflow.com/questions/52842318/extracting-data-from-a-pdf,"['java', 'pdf', 'itext', 'pdf-generation', 'pdfbox']",328,FALSE,0,1
Error while starting up MiniDFSCluster,"<p>I have been running into a problem for quite a while now and i'm out of ideas to resolve it ... </p>

<p>I'm trying to develop a unit test for a java code that will be running on Hadoop. For that I'm trying to use MiniDFSCluster as according to the web, that's what is mostly used when it comes to unit testing hadoop java code. </p>

<p>As I work in a team, I wanted to create a ""mother class"", its' purpose is to set up MiniDFSCluster. Each test class that needs to use a mini cluser would extend this class and each developer can unit test hadoop code if needed. </p>

<p>For the above mentioned purpose, I wrote this ""mother class"" : </p>

<pre><code>package com.sncf.setup;

import static org.junit.Assert.assertNotNull;

import java.io.File;

import org.apache.hadoop.conf.Configuration; 
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.hdfs.DistributedFileSystem;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;


public class SetupMiniCluster {

protected static MiniDFSCluster hdfsCluster ; 

protected static File baseDir ; 

protected static DistributedFileSystem fileSystem ; 

protected static String hdfsURI ; 

@BeforeAll
private static void setUpBeforeClass() throws Exception {

    baseDir = new File(""./target/hdfs"").getAbsoluteFile();
    Configuration conf = new Configuration();
    conf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, baseDir.getAbsolutePath());
    MiniDFSCluster.Builder builder = new MiniDFSCluster.Builder(conf);
    hdfsCluster = builder.numDataNodes(3).build();
    hdfsURI = ""hdfs://localhost:""+ hdfsCluster.getNameNodePort() + ""/"";
    fileSystem = hdfsCluster.getFileSystem();
}

@Test
void testNotNull() {
    assertNotNull(hdfsURI);
    assertNotNull(baseDir);
    assertNotNull(fileSystem);
}

@AfterAll
private static void tearDownAfterClass() throws Exception {
    hdfsCluster.shutdown();
    FileUtil.fullyDelete(baseDir);
}

}
</code></pre>

<p>When I run this class as a JunitTest (with Junit 5) I end up getting the below stack trace : </p>

<pre><code>java.lang.NoSuchMethodError: org.apache.hadoop.hdfs.DFSUtil.addKeySuffixes(Ljava/lang/String;[Ljava/lang/String;)Ljava/lang/String;
at org.apache.hadoop.hdfs.MiniDFSCluster.initNameNodeAddress(MiniDFSCluster.java:1076)
at org.apache.hadoop.hdfs.MiniDFSCluster.createNameNodesAndSetConf(MiniDFSCluster.java:916)
at org.apache.hadoop.hdfs.MiniDFSCluster.initMiniDFSCluster(MiniDFSCluster.java:815)
at org.apache.hadoop.hdfs.MiniDFSCluster.&lt;init&gt;(MiniDFSCluster.java:475)
at org.apache.hadoop.hdfs.MiniDFSCluster$Builder.build(MiniDFSCluster.java:434)
at com.sncf.setup.SetupMiniCluster.setUpBeforeClass(SetupMiniCluster.java:67)
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.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:389)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:115)
at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$invokeBeforeAllMethods$5(ClassTestDescriptor.java:228)
at org.junit.jupiter.engine.execution.ThrowableCollector.execute(ThrowableCollector.java:40)
at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.invokeBeforeAllMethods(ClassTestDescriptor.java:227)
at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.before(ClassTestDescriptor.java:151)
at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.before(ClassTestDescriptor.java:61)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.lambda$execute$3(HierarchicalTestExecutor.java:80)
at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:77)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.lambda$null$2(HierarchicalTestExecutor.java:92)
at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)
at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175)
at java.util.Iterator.forEachRemaining(Iterator.java:116)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.lambda$execute$3(HierarchicalTestExecutor.java:92)
at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:77)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:51)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:43)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:170)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:154)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:90)
at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.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:538)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
Suppressed: java.lang.NullPointerException
    at com.sncf.setup.SetupMiniCluster.tearDownAfterClass(SetupMiniCluster.java:86)
    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.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:389)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$null$6(ClassTestDescriptor.java:242)
    at org.junit.jupiter.engine.execution.ThrowableCollector.execute(ThrowableCollector.java:40)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.lambda$invokeAfterAllMethods$7(ClassTestDescriptor.java:241)
    at java.util.ArrayList.forEach(ArrayList.java:1257)
    at java.util.Collections$UnmodifiableCollection.forEach(Collections.java:1080)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.invokeAfterAllMethods(ClassTestDescriptor.java:241)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.after(ClassTestDescriptor.java:162)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.after(ClassTestDescriptor.java:61)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.lambda$execute$3(HierarchicalTestExecutor.java:96)
    ... 27 more
</code></pre>

<p>If anyone has a solution or at least a clue of how to solve this, it would be much appreciated :)</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/48368737/error-while-starting-up-minidfscluster,"['java', 'unit-testing', 'hadoop']",1109,FALSE,0,1
Should all of my unit tests always pass when method is given bad input?,"<p>I am somewhat new to test driven development and am trying to determine whether I have a problem with my approach to unit testing.<br>
I have several unit tests (let's call them group A) that test whether my method's return is as expected.<br>
I also have a unit test ""B"" whose passing condition is that an <code>IllegalArgumentException</code> is thrown when my method is given invalid input.<br>
The unit tests in group A fail when the method is given invalid input since the method needs valid input to return correctly.<br>
If I catch the exception, unit test ""B"" will fail, but if I don't catch the exception, the tests in group A will fail.<br>
Is it OK to have unit tests fail in this way, or can I modify the code in some way so that all tests always pass?<br>
Am I doing TDD all wrong?<br>
Here's a notion of my code for more clarity:  </p>

<pre><code>public class Example{
    public static String method(String inputString, int value){
        if(badInput){
            throw new IllegalArgumentException();
        }
        //do some things to inputString
        return modifiedInputString;
    }
}

public class ExampleTests{
    @Test
    public void methodReturnsIllegalArgumentExceptionForBadInput(){
        assertThrows(IllegalArgumentException.class, ()-&gt;{Example.method(badInput,badValue);})
    }

    //""Group A"" tests only pass with valid input. Bad input causes IllegalArgumentException
    @Test
    public void methodReturnsExpectedType(){
        assertTrue(actual == expected);
    }

    @Test
    public void methodReturnsExpectedValue(){
        assertTrue(actual == expected);
    }

    @Test
    public void methodReturnsExpectedStringFormat(){
        assertTrue(actual == expected);
    }
}
</code></pre>
",https://stackoverflow.com/questions/49227454/should-all-of-my-unit-tests-always-pass-when-method-is-given-bad-input,"['java', 'unit-testing', 'junit', 'tdd']",292,FALSE,0,1
Sharing PHPUnit tests between test cases,"<p>I have an interface that defines a method which is meant to throw a specific exception when a condition is not met.</p>

<pre><code>interface PrizePotInterface
{
    /**
     * @throws PrizePotEmptyException
     */
    public function claimPrize(EntryInterface $entry);
}
</code></pre>

<p>I have two classes which implement this interface, both of which have similar logic to determine whether to throw the exception.</p>

<pre><code>class SequentialPrizePot implements PrizePotInterface
{
    public function claimPrize(EntryInterface $entry)
    {
        if ($this-&gt;isEmpty()) {
            throw new PrizePotEmptyException();
        }

        // prize claim logic
    }
}

class RandomPrizePot implements PrizePotInterface
{
    public function claimPrize(EntryInterface $entry)
    {
        if ($this-&gt;isEmpty()) {
            throw new PrizePotEmptyException();
        }

        // prize claim logic
    }
}
</code></pre>

<p>I need to write a unit test that checks that an empty prize pot throws <code>PrizePotEmptyException</code>, and I need this test to apply to both implementations.</p>

<p>I can see three options:</p>

<ol>
<li><p>Write the same test method in each test class to check for the
exception. Simple and easy, but not very DRY.</p></li>
<li><p>Make both test classes inherit a common (abstract) <code>PrizePotTest</code>
class which checks for the exception. (Do <code>test*</code> methods in parent
classes even get run by PHPUnit?)</p></li>
<li><p>Write the test in a trait and use it in each test class. (Again,
PHPUnit may not allow this kind of test.)</p></li>
</ol>

<p>I’m unsure which of these (if any) is considered good unit testing practice.</p>
",https://stackoverflow.com/questions/51313814/sharing-phpunit-tests-between-test-cases,"['php', 'phpunit']",427,TRUE,0,1
Scrapy: using a separate test database for integration tests,"<p>I have a scrapy project that writes the data it scrapes to a database. It was based on this great tutorial: <a href=""http://newcoder.io/scrape/part-3/"" rel=""nofollow noreferrer"">http://newcoder.io/scrape/part-3/</a></p>

<p>I have hit an issue now that I am trying to write some integration tests for the project. I am following the guidelines here: <a href=""https://stackoverflow.com/questions/6456304/scrapy-unit-testing"">Scrapy Unit Testing</a></p>

<p>It's not clear to me how best to pass in the appropriate database settings. I'd like the tests to use their own database that I can ensure is in a known state before the tests start running.</p>

<p>So just <code>import settings</code> won't do the trick as, if the project is being run in test mode then it needs to use a different settings file.</p>

<p>I am familiar with Ruby on Rails projects where you specify a RAILS_ENV environment variable, and based on this environment variable, the framework will use settings from different files. Is there a similar concept that can apply when testing scrapy projects? Or is there a more pythonic alternative approach?</p>
",https://stackoverflow.com/questions/49060681/scrapy-using-a-separate-test-database-for-integration-tests,"['python', 'scrapy']",244,TRUE,0,1
C# Deserializing dictionary contains proper keys but null values,"<p>I have a class that implements <code>ISerializable</code> and stores a <code>Dictionary</code> which holds objects. These objects have multiple levels of child objects that also contain collections and various other fields that are all serializable as well.</p>

<p>In unit testing, everything serializes and deserializes just fine when testing the underlying child objects, but in this outermost class, when I deserialize the <code>Dictionary</code> that contains all child elements (and all of their children, and so on), the keys load properly, but all of the values associated with the keys are <code>null</code>.</p>

<p>Here is how the outermost class looks:</p>

<pre><code>[Serializable]
internal class ChildCollection : ISerializable
{
  private readonly Dictionary&lt;ulong, ChildElement&gt; _children;

  protected ChildCollection( SerializationInfo info, StreamingContext context )
  {
    _childElements = new Dictionary&lt;ulong, ChildElement&gt;();

    var children = ( Dictionary&lt;ulong, ChildElement&gt; )info.GetValue( nameof( _children ), typeof( Dictionary&lt;ulong, ChildElement&gt; ) );
    children.OnDeserialization( null );

    foreach( var child in children.Values )
      Add( child ); // This throws an exception, as all values are null
  }

  public virtual void GetObjectData( SerializationInfo info, StreamingContext context )
  {
    info.AddValue( nameof( _children ), _children );
  }
}
</code></pre>

<p>I understand that C# Serialization is very messy in terms of how it's implemented, and that <code>OnDeserialization</code> needs to be called on the dictionary in order to load values. What I don't understand is that I have this exact same implementation for another class (although that class has simpler child elements). I also don't understand why serialization works at every level until this class.</p>
",https://stackoverflow.com/questions/52377858/c-deserializing-dictionary-contains-proper-keys-but-null-values,"['c#', 'serialization', 'deserialization']",209,FALSE,0,0
Disabling a Submit Button with Angular 2+ Template-Driven-Form and a child component?,"<p>Using template-driven forms in Angular 2+, I wanted to make use of child components within a form for easier unit testing of form elements. With that said, I'd like to be able to disable the submit button with template reference variables (ie) <code>button [disabled]=""!myForm.form.valid""</code>. I know something should be passed from the parent-form to the child-component, but I haven't been able to figure what that is, or the syntax that should be used.</p>

<p>Using a Stackblitz example, How would I get the submit button disabled if the input validators (specifically <code>minlength</code> in this example) are within a child component to a form?</p>

<p>Stackblitz Example <a href=""https://stackblitz.com/edit/angular-zzeton"" rel=""nofollow noreferrer"">https://stackblitz.com/edit/angular-zzeton</a></p>

<p>I've looked at the following links but they have more todo with true input-control-customization vs accessing template-reference-variables:</p>

<p><a href=""https://stackoverflow.com/questions/51897650/how-to-add-validation-in-template-driven-form-from-component-in-angular-6"">How to add validation in template driven form from component in angular 6</a>
<a href=""https://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html#demos"" rel=""nofollow noreferrer"">https://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html#demos</a></p>
",https://stackoverflow.com/questions/52630583/disabling-a-submit-button-with-angular-2-template-driven-form-and-a-child-compo,['angular'],1303,TRUE,0,1
Automation Testing with a set of data from an external source in Visual Studio 2017,"<p>I have built an application using <em>Asp.Net MVC</em>. Application is almost completed and now it is in testing phase.</p>

<p><strong>Is it possible to create automation testing using visual studio 2017 and generate report for the same ?</strong> </p>

<p>Let me explain here...</p>

<p>suppose I have a user registration page and admin needs to enter user details ( <em>First Name,Last Name , user name , email , phone</em> etc.). </p>

<ol>
<li>can I create a test case for that page and automate the testing ?</li>
<li>Is it possible to feed a set of input data like n number of records from an external source ( <em>excel , csv</em>) and test for each record.</li>
<li>And finally is it possible to generate report for that particular test case ( again for each record ) ?</li>
</ol>

<p>I have unit test project for the <em>MVC</em> project and I am using <em>nunit</em> here. But not sure how to achieve this requirement using <em>unit testing</em>. Any help will be appreciated. </p>

<p>Thanks in advance. </p>
",https://stackoverflow.com/questions/48860965/automation-testing-with-a-set-of-data-from-an-external-source-in-visual-studio-2,"['asp.net-mvc', 'unit-testing', 'automated-tests', 'nunit', 'data-driven-tests']",194,TRUE,0,1
How to include karma and jasmine to AngularJs project served with webpack,"<p>I spent the whole day trying to setup karma for my project. I went through all the tutorials and StackOverflow but couldn't integrate it into my project.</p>

<p>My project is served using web pack. I guess the problem is that I can't get the reference to my root app module.</p>

<p>Please help me with this.</p>

<p>I tried importing the module using its name, imported the whole files(js) etc but nothing helped.</p>

<p>PS: This project has tons of services, components, directives etc.
We have used js with jade. And this is the first time we are integrating unit testing for a new feature.</p>

<hr>

<p>edited</p>

<p><code>karma.config.js</code></p>

<pre><code>var webpackConfig = require('./webpack.config.js');
webpackConfig.entry = void 0;

const commonsChunkPluginIndex = webpackConfig.plugins.findIndex(plugin =&gt; plugin.chunkNames);
webpackConfig.plugins.splice(commonsChunkPluginIndex, 1);

module.exports = function(config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine'],

    reporters: ['progress'],
    port: 9876,
    colors: false,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false,
    autoWatchBatchDelay: 300,

    files: [
      './node_modules/angular/angular.js',
      './node_modules/angular-mocks/angular-mocks.js',
      ""./client/app/app.js"", ,=== root module
      ""./client/app/services/chart-type/cohortSpec.js"",  &lt;==  contains test case
    ],

    preprocessors: {
      ""./webpack.config.js"": ['babel'],
      './client/app/app.js': ['webpack'],
      ""./client/app/services/chart-type/cohortSpec.js"": ['babel']
    },
    babelPreprocessor: {
      options: {
        ""presets"": [""es2015""],
        ""plugins"": [""transform-es2015-modules-umd"",  ""transform-runtime""]
      }
    },

    webpack: webpackConfig,

    webpackMiddleware: {
      noInfo: true,
      stats: 'errors-only',
    }
  });
}
</code></pre>

<blockquote>
  <p><strike> I can't get the reference to <em>app</em> module even though I have imported all js files in the app. Note that webpack serves files at dist/, which isn't imported in karma.config</strike></p>
</blockquote>

<p>With above config, I was able to get the reference to the app.</p>

<p><strong>Is there any improvement in the config?</strong></p>
",https://stackoverflow.com/questions/49612813/how-to-include-karma-and-jasmine-to-angularjs-project-served-with-webpack,"['angularjs', 'unit-testing', 'jasmine', 'karma-jasmine', 'karma-webpack']",394,FALSE,0,0
Lambda v Cron for ebs snapshot rotation for backup/DR,"<p>What's the upside for using AWS Lambda over boto3 driven by cron for creating snapshots for backup and disaster recovery?</p>

<p>My goal is to have snapshots going back 30 days or so with one snapshot every 6 months pushed on to glacier.  This gives me a fast restoration on corruption or a botched upgrade with cheap long term storage for services like jenkins.  I've got boto3 based scripts for create-snap/restore-to-snap/mount-snap).</p>

<p><strong>Lamda</strong></p>

<ul>
<li>IAM policies linked to just that one action</li>
</ul>

<p><strong>Cron</strong></p>

<ul>
<li>instance role based IAM policies leak to the instance (which isn't idea for a jenkins server for example).</li>
<li><strong>might</strong> be easier to use my python module which can be tested via mocks etc.</li>
</ul>

<p>So, Lambda seems slightly more complex but if terraform manages it, then I should be able to combine my python scripts with unit testing and then push them to lambda for CloudWatch to execute.</p>

<p>Are there wins or costs that I'm missing?</p>
",https://stackoverflow.com/questions/50937481/lambda-v-cron-for-ebs-snapshot-rotation-for-backup-dr,"['amazon-web-services', 'aws-lambda', 'boto3', 'amazon-cloudwatch']",180,TRUE,0,1
Keeping pytest fixtures in one location and using them across submodules,"<p>I am building a python package, using <code>pytest</code> for all unit testing. My package is composed of several modules, with various submodules under each module. The unit tests are within the <code>test</code> folder of each module (e.g., <code>./tumble/tumble/math/test/test_multiply.py</code> or <code>./tumble/tumble/science/test/test_divide.py</code>)</p>

<p>I have some fixtures that I want to share across all of the modules &amp; submodules. Because of this, I want place them in a central location, <code>./tumble/tumble/test</code> in this example, and not have duplicate fixtures in each submodule (<code>math/test</code> and <code>science/test</code>). </p>

<p>If I place <code>conftest.py</code> within the <code>test</code> folder in each submodule, everything works as expected. However, I have the same fixtures in two locations, which isn't ideal.</p>

<p>When I place my fixtures in a central location, I am able to see them when I use the command <code>pytest --fixtures</code>, however, when I run <code>pytest</code>, it tells me <code>fixture not found</code> and the fixture is not listed in the <code>available fixtures</code>. </p>

<p>Do I need to move all of my unit tests under the <code>test</code> folder, or is there something that I can do to keep unit tests within the submodules, but fixtures in a central location?</p>

<pre><code>tumble
+-- setup.py
+-- README.md
+-- tumble
|   +-- math
|   |   +-- __init__.py
|   |   +-- multiply.py
|   |   +-- test
|   |   +-- __init__.py
|   |   |   +-- test
|   |   |   |   +-- __init__.py
|   |   |   |   +-- test_multiply.py
|   +-- science
|   |   +-- __init__.py
|   |   +-- divide.py
|   |   +-- test
|   |   +-- __init__.py
|   |   |   +-- test
|   |   |   |   +-- __init__.py
|   |   |   |   +-- test_divide.py
|   +-- test
|   |   +-- __init__.py
|   |   +-- conftest.py
</code></pre>

<p><strong>multiply.py</strong></p>

<pre><code>def multipy(x, y):
    return x * y
</code></pre>

<p><strong>conftest.py</strong></p>

<pre><code>import pytest

@pytest.fixture()
def numbers():
    return (1, 5, 10)
</code></pre>

<p><strong>test_multiply.py</strong></p>

<pre><code>import tumble
import pytest

assert tumble.multiply(numbers[0], numbers[1]) == 5   
</code></pre>
",https://stackoverflow.com/questions/49053928/keeping-pytest-fixtures-in-one-location-and-using-them-across-submodules,"['python', 'unit-testing', 'pytest', 'fixtures']",5395,TRUE,7,1
Ruby on Rails test coverage with simplecov,"<p><br>
I want to analyse the test coverage of our code , and therefore, installed the simplecov gem.<br>
<br>
Our testing environement has 2 seperate project: REST API test (Java+Rest-Assured) and Web UI testing (Java-Selenium).<br>
As you can see, we dont have unit testing inside the rails app, and we are testing using external projects.
<br>
<br>
I configured the simplecov gem as descriped in the tutorial and put this, in the rails script:</p>

<pre><code>require 'simplecov'
SimpleCov.start 'rails'
puts ""require simplecov""
</code></pre>

<p>When loading the app, I see the string I printed.
<br>
<br>
I ran both automation test projects, saw their printouts in the rails log, but I don't see <strong>any</strong> coverage of controllers/models, I see only small precentage of initializtion files of some gems and rails.<br>
<br>
I searched the net, and tried putting the code phrase in boot.rb or even puma.rb and it returned the same results.</p>

<p><br>
<br></p>

<p>Any ideas?<br><br></p>

<p><strong><em>EDIT</em></strong></p>

<p>Nothing helped with all the comments, but I figured out something very interesting, in all cases, I only see the name of methods marked as tested, not the content (in controllers).<br>
I tried to put the simplecov start phrase in both bin/rails, puma.rb, config.ru, environment.rb, all not given the desired results of code coverage.</p>
",https://stackoverflow.com/questions/51809678/ruby-on-rails-test-coverage-with-simplecov,"['ruby-on-rails', 'ruby', 'automated-tests', 'simplecov']",3954,TRUE,11,3
Jenkins pipeline mocking with Groovy,"<p>I'm quite new to the Jenkins pipeline stuff and I am building a small shared library in Groovy.<br>
In this context I am trying to come up with some unit tests, and then I have to mock the pipeline object.</p>

<p>Basically I am having a Groovy class containing a method that does some stuff with credentials:</p>

<pre><code>class MyClass implements Serializable {

  def pipeline

  MyClass(def pipeline) {
    this.pipeline = pipeline
  }

  void my method(String version) {
    pipeline.withCredentials([pipeline.usernamePassword(credentialsId: 'MY_ID', usernameVariable: 'MY_USER', passwordVariable: 'MY_PASSWORD')]) {
        pipeline.sh ""./release.sh complete --username ${MY_USER} --password ${MY_PASSWORD} --version '${version}'""
    }
  }
}
</code></pre>

<p>So when it comes to unit testing this method I have created a PipelineMock Groovy class to (try to) mock the <code>withCredentials</code> and <code>usernamePassword</code>.</p>

<p>The test class is like this (a bit simplified):</p>

<pre><code>class MyClassTest {

  @Test
  void callWithWithVersionShouldCallCommad() {
    def pipelineMock = new PipelineMock()
    def myClass = new MyClass(pipelineMock)
    myClass('1.0.1')
    assertTrue(pipelineMock.commandCalled.startsWith('./release.sh complete'))
  }

}
</code></pre>

<p>And the PipelineMock I came up with is:</p>

<pre><code>class PipelineMock {

  String commandCalled

  def sh(String command) {
    commandCalled = command
  }

  def usernamePassword(Map inputs) {
    inputs
  }

  def withCredentials(List args, Closure closure) {
    for (arg in args) {
        closure.setProperty(arg.get('usernameVariable'), 'the_login')
        closure.setProperty(arg.get('passwordVariable'), 'the_password')
    }
    closure()
  }

}
</code></pre>

<p>Initially I was just calling the <code>closure()</code> so to execute the code, but I got the error <code>groovy.lang.MissingPropertyException: No such property: MY_USER for class: MyClass</code> when the execution reaches the <code>pipeline.sh</code> line.<br>
So I tried to inject test values into <code>MY_USER</code> and <code>MY_PASSWORD</code> so they can be resolved with the <code>for</code> loop. I got the exact same error but this time when calling the <code>closure.setProperty</code>. I checked at debug time and the <code>arg.get('usernameVariable')</code> resolves correctly to <code>MY_USER</code>.</p>

<p>So well, I'm lost. I'm not really a Groovy expert, so I probably miss something. Any help on understanding what's happening would be appreciated!</p>
",https://stackoverflow.com/questions/49232842/jenkins-pipeline-mocking-with-groovy,"['unit-testing', 'jenkins', 'groovy', 'closures', 'jenkins-pipeline']",3865,TRUE,3,1
Jest + Istanbul: collect coverage for functions called directly from the tests only,"<h1>Problem</h1>

<p>Is there a way to configure Istanbul/Jest to collect a separate code coverage metric?</p>

<p>The metric should count the visited lines/branches of code but only when the line is executed as a part of a direct call to containing function.</p>

<h1>Motivation</h1>

<p>I want to see how well are functions tested in isolation (in a true sense of unit-testing).</p>

<h1>Example</h1>

<p>For the code below, I am interested in seeing the metric that counts every line of <code>foo()</code> function as visited once (since it is invoked directly from the test); however each <code>bar()</code>'s line to not be counted, because it's not invoked directly by the test, but rather called transitively.</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.js       
    it(`should count things well`, () =&gt; {
      expect(foo()).toEqual(3);
    });
    
    // code.js
  | function foo() {
1 |   const a = 1;
1 |   const b = bar();
1 |   return a + b;
  | }

  | function bar() {
0 |   return 2;
  | }</code></pre>
</div>
</div>
</p>

<h1>What I tried</h1>

<p>The Istanbul-generated <code>coverage-final.json</code> does not seem to contain any metadata about <em>what</em> a certain line of code is. It only tells whether certain lines/branches of code are visited or not. I wonder if there are some command flags I could use to control what coverage information is being emitted and make an analysis of the extended data.</p>
",https://stackoverflow.com/questions/53770815/jest-istanbul-collect-coverage-for-functions-called-directly-from-the-tests-o,"['javascript', 'unit-testing', 'jestjs', 'code-coverage', 'istanbul']",305,FALSE,3,0
"How to distinguish Debug, Release and Unit Test source code","<p>I would like to write a piece of source code like this:</p>

<pre><code>log(bDebug=true, bRelease=false, bUnitTesting=true, &lt;some information&gt;);
</code></pre>

<p>This piece of code should do the following:</p>

<ul>
<li>bDebug : the logging needs to be done in case this piece of code is called in ""Debug"" mode.</li>
<li>bRelease : this logging needs to be done in case this piece of code is called in ""Release"" mode.</li>
<li>bUnitTesting : this logging needs to be done in case this piece of code is called during unit testing (defined in a standard Visual Studio Native Unit Test project).</li>
</ul>

<p>I already am aware of the <code>#define Debug</code> (or capitals, I'm not sure) which I can use for switching between ""Debug"" and ""Release"" builds, but I have no idea if there are any <code>#define</code> clauses for Unit Test projects. (Or is there another way to know this?)</p>

<p>Just for giving you more information: I already have a class <code>Logger</code> which takes care of logging information, but I know that the Microsoft framework also has a <code>Logger</code> class, doing this for unit tests (<code>Microsoft::VisualStudio::CppUnitTestFramework::Logger</code>). Is there a way to switch between application logging and unit test logging?</p>
",https://stackoverflow.com/questions/48517083/how-to-distinguish-debug-release-and-unit-test-source-code,"['c++', 'visual-studio', 'unit-testing', 'visual-studio-debugging']",650,FALSE,3,0
ASP.NET Core 2.0 The default XML namespace of the project must be the MSBuild XML namespace,"<p>I have an ASP.NET Core 2.0 project developed using VS2017. I am getting the following error from our build server which uses TFS2015.</p>

<p><strong>The default XML namespace of the project must be the MSBuild XML namespace. If the project is authored in the MSBuild 2003 format, please add xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" to the  element. If the project has been authored in the old 1.0 or 1.2 format, please convert it to MSBuild 2003 format.</strong></p>

<p>I got this error when I initially setup the build, but after reading through various posts I resolved the issue by installing the VS2017 SDK and build tools on the build server. All well and good.</p>

<p>I have now added a unit testing project and getting the error again. I am also getting this warning.</p>

<p><strong>Warning MSB4078 The project file is not supported by MSBuild and cannot be built</strong></p>

<p>I get this error when the build attempts to build the solution file. I have installed the latest version of MSBUILD on the build server. What else do I need to do?</p>
",https://stackoverflow.com/questions/49383629/asp-net-core-2-0-the-default-xml-namespace-of-the-project-must-be-the-msbuild-xm,"['asp.net-core', 'msbuild', 'visual-studio-2017']",4478,FALSE,3,0
Jasmine + Karma + Istanbul testing: self and/or window is undefined,"<p>I am working with a project that needs to be tested (unit testing). Jasmine is already working fine however, we need a coverage.</p>

<p>Searched about it and Jasmine + Karma + Istanbul can do the work.</p>

<p>I am struggling with the complications between Karma (browser/client) and node (server-side). The fs, logger (log4js) node modules and the major one is the self and window.</p>

<p>Already managed to solve or ignore the two node modules (fs and logger) by using browserify and by removing logger (or switching it to console.log when testing).</p>

<p>So, for my problem (undefined window or self), here's the error message when I run <strong>""npm test""</strong>:</p>

<pre><code>09 05 2018 14:14:07.047:ERROR [config]: Error in config file!
 ReferenceError: window is not defined
    at module.exports (C:\Users\kyl.sanantonio@awsys-i.com\workspace\TougouBaseline_Call\karma.conf.js:15:21)
    at Object.parseConfig (C:\Users\kyl.sanantonio@awsys-i.com\workspace\TougouBaseline_Call\node_modules\karma\lib\config.js:410:5)
    at new Server (C:\Users\kyl.sanantonio@awsys-i.com\workspace\TougouBaseline_Call\node_modules\karma\lib\server.js:56:20)
    at Object.exports.run (C:\Users\kyl.sanantonio@awsys-i.com\workspace\TougouBaseline_Call\node_modules\karma\lib\cli.js:280:7)
    at Object.&lt;anonymous&gt; (C:\Users\kyl.sanantonio@awsys-i.com\workspace\TougouBaseline_Call\node_modules\karma\bin\karma:3:23)
    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:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3
</code></pre>

<p><strong>package.json</strong></p>

<pre><code>{
  ""name"": ""----"",
  ""version"": ""1.0.0"",
  ""main"": "".mongorc.js"",
  ""scripts"": {
    ""start"": ""node ./server.js"",
    ""test"": ""karma start karma.conf.js"",
    ""test1"": ""jasmine-node spec""
  },
  ""dependencies"": {
    ""express"": ""4.15.3"",
    ""ws"": ""3.0.0"",
    ""compression"": ""1.6.2"",
    ""body-parser"": ""1.17.2"",
    ""cookie-parser"": ""1.4.3"",
    ""express-session"": ""1.15.3"",
    ""connect-mongo"": ""1.3.2"",
    ""method-override"": ""2.3.9"",
    ""multer"": ""1.3.0"",
    ""diskspace"": ""2.0.0"",
    ""mkdirp"": ""0.5.1"",
    ""encoding-japanese"": ""1.0.23"",
    ""lockfile"": ""1.0.1"",
    ""log4js"": ""0.6.8"",
    ""async"": ""0.2.10"",
    ""mongoose"": ""3.6.11"",
    ""moment"": ""2.10.6"",
    ""rmdir"": ""1.2.0"",
    ""log4js-extend"": ""0.1.2"",
    ""jquery"": ""3.2.1"",
    ""jquery-contextmenu"": ""2.6.3"",
    ""autosize"": ""4.0.0"",
    ""request-ip"": ""2.0.2"",
    ""request"": ""^2.85.0"",
    ""log4js-node"": ""0.1.2""
  },
  ""author"": ""---"",
  ""devDependencies"": {
    ""browser-sync"": ""^2.23.7"",
    ""browserify"": ""^16.2.0"",
    ""browserify-fs"": ""^1.0.0"",
    ""eslint-config-google"": ""^0.9.1"",
    ""gulp"": ""^3.9.1"",
    ""gulp-nodemon"": ""^2.2.1"",
    ""istanbul"": ""^0.4.5"",
    ""jasmine-core"": ""^2.99.1"",
    ""jasmine-node"": ""^1.14.5"",
    ""jsdom"": ""^11.10.0"",
    ""karma"": ""^1.7.1"",
    ""karma-browserify"": ""^5.2.0"",
    ""karma-chrome-launcher"": ""^2.2.0"",
    ""karma-coverage"": ""^1.1.1"",
    ""karma-global-preprocessor"": ""0.0.2"",
    ""karma-jasmine"": ""^1.1.2"",
    ""karma-jsdom-launcher"": ""^6.1.3"",
    ""watchify"": ""^3.11.0""
  },
  ""keywords"": [],
  ""license"": ""ISC"",
  ""directories"": {
    ""test"": ""test""
  },
  ""description"": """"
}
</code></pre>

<p><strong>karma.conf.js</strong></p>

<pre><code>module.exports = function (config) {

    config.set({
        basePath: '',
        frameworks: ['jasmine', 'browserify'],
        files: [
            'spec/serverLineSpec.js',
            // 'spec/*.js',
            'serverLine.js'
        ],
        preprocessors: {
            'serverLine.js': ['coverage', 'browserify']
        },
        globals: {
            'self': window
        },
        target: ""web"",
        plugins: [
            require('browserify'),
            require('karma-browserify'),
            require('karma-jasmine'),
            require('karma-coverage'),
            require('karma-global-preprocessor'),
            require('karma-chrome-launcher'),
            require('browserify-fs')
        ],
        reporters: ['progress', 'coverage'],
        port: 9878,
        colors: true,
        logLevel: config.LOG_DEBUG,
        autowatch: true,
        browsers: ['Chrome', 'Chrome_without_security'],
        customLaunchers: {
          Chrome_without_security: {
            base: 'Chrome',
            flags: ['--disable-web-security']
          }
        },
        singleRun: false,
        concurrency: Infinity,
        coverageReporter: {
            includeAllSources: true,
            dir: 'coverage/',
            reporters: [
                { type: ""html"", subdir: ""html"" },
                { type: 'text-summary' }
            ]
        },
        browserify: {
            debug: true
        },
        webpack: { node: { fs: 'empty', } }
    });
};
</code></pre>

<p><strong>And when I use:</strong></p>

<pre><code>globals: {
            'self': global.window
        },
</code></pre>

<p>Error message is:
<strong>self is not defined</strong></p>

<p><strong>test/serverLineSpec.js</strong></p>

<pre><code>var fs = require(""fs"");
var express = require(""express"");
var https = require(""https"");
var settings = require(""../settingsServer.js"");
var serverLine = require(""../serverLine.js"");
var webRTCLib = require(""../webrtc.io"");
// HTTPSサーバ
var privateKey = fs.readFileSync(""system/newkey.pem"");
var certificate = fs.readFileSync(""system/newcert.pem"");
var passphrase = settings.getServerPassphrase();
var options = {
    key: privateKey,
    cert: certificate,
    requestCert: true,
    rejectUnauthorized: false,
    passphrase: passphrase
};
var app = express();
var port = Number(settings.getPortNumber());

var mockData = JSON.parse(""{\""room\"":\""servlet\"",\""caller\"":\""102\"",\""callee\"":[102],\""callerUsername\"":\""s1\""}"");

function MockSocket(socketId) {
    this.id = socketId;
    this.data = """";
    this.send = function(data, cb) {
        this.data = data;
        cb = cb || function() {};
        cb();
    };
}


var httpsServer;
var webRTC;

describe(""Test call_user event"", function() {

    beforeEach(function() {
        httpsServer = https.createServer(options, app).listen(port);

        // WebSocketサーバ
        webRTC = webRTCLib.listen(httpsServer);
        serverLine.initialize(webRTC);

        webRTC.rtc.rooms[""""] = [];
        webRTC.rtc.userKinds[""""] = [];
        webRTC.rtc.rooms[""servlet""] = [];
        webRTC.rtc.userKinds[""servlet""] = [];
        webRTC.rtc.sockets = [];
    });

    afterEach(function() {
        httpsServer.close();
    });

    it(""test user is not found"", function() {

        var mockSocket = new MockSocket(""laksdlaks"");

        webRTC.rtc.fire(""call_user"", mockData, mockSocket);

        var jsonData = JSON.parse(mockSocket.data);
        expect(jsonData.eventName).toMatch(""receive_call_user"");
        expect(jsonData.data.userFound[0].status).toBe(false);
        expect(jsonData.data.userFound[0].userKind).toMatch(""102"");

    });

    it(""test user found"", function() {

        webRTC.rtc.rooms[""servlet""].push(""sampleSocketId1"");
        webRTC.rtc.userKinds[""servlet""].push(""102_servlet"");


        var mockUserSocket = new MockSocket(""sampleSocketId1"");
        webRTC.rtc.sockets.push(mockUserSocket);

        var mockSocket = new MockSocket(""testSocket"");

        webRTC.rtc.fire(""call_user"", mockData, mockSocket);

        var callUserJson = JSON.parse(mockUserSocket.data);
        var rcvCallUserJson = JSON.parse(mockSocket.data);

        expect(callUserJson.eventName).toMatch(""call_user"");
        expect(callUserJson.data.roomid).toMatch(""servlet"");
        expect(callUserJson.data.caller).toMatch(""102"");
        expect(callUserJson.data.callerUsername).toMatch(""s1"");

        expect(rcvCallUserJson.eventName).toMatch(""receive_call_user"");
        expect(rcvCallUserJson.data.userFound[0].status).toBe(true);
        expect(rcvCallUserJson.data.userFound[0].userKind).toMatch(""102"");
    });
});

describe(""Test response_call_user event"", function() {

    beforeEach(function() {
        httpsServer = https.createServer(options, app).listen(port);

        // WebSocketサーバ
        webRTC = webRTCLib.listen(httpsServer);
        serverLine.initialize(webRTC);

        webRTC.rtc.rooms[""""] = [];
        webRTC.rtc.userKinds[""""] = [];
        webRTC.rtc.rooms[""servlet""] = [];
        webRTC.rtc.userKinds[""servlet""] = [];
        webRTC.rtc.sockets = [];
    });

    afterEach(function() {
        httpsServer.close();
    });

    it(""test decline call response"", function() {

        var mockDataResponse = JSON.parse(""{\""accept_call\"":\""false\"",\""callee\"":\""105_servlet\"",\""caller\"":\""101\""}"");

        webRTC.rtc.rooms[""servlet""].push(""sampleSocketId1"");
        webRTC.rtc.userKinds[""servlet""].push(""105_servlet"");

        var mockUserSocket = new MockSocket(""sampleSocketId1"");
        webRTC.rtc.sockets.push(mockUserSocket);

        webRTC.rtc.rooms[""""].push(""sampleSocketId2"");
        webRTC.rtc.userKinds[""""].push(101);

        var mockSocket = new MockSocket(""sampleSocketId2"");
        webRTC.rtc.sockets.push(mockSocket);

        webRTC.rtc.fire(""response_call_user"", mockDataResponse, mockSocket);

        var rcvRspCallUserJson = JSON.parse(mockSocket.data);

        expect(rcvRspCallUserJson.eventName).toMatch(""response_call_user"");
        expect(rcvRspCallUserJson.data.accept_call).toBe(""false"");
        expect(rcvRspCallUserJson.data.caller).toMatch(""101"");
        expect(rcvRspCallUserJson.data.callee).toMatch(""105_servlet"");

    });

    it(""test accept call response"", function() {
        var mockDataResponse = JSON.parse(""{\""accept_call\"":\""true\"",\""callee\"":\""105_servlet\"",\""caller\"":\""101\""}"");

        webRTC.rtc.rooms[""servlet""].push(""sampleSocketId1"");
        webRTC.rtc.userKinds[""servlet""].push(""105_servlet"");

        var mockUserSocket = new MockSocket(""sampleSocketId1"");
        webRTC.rtc.sockets.push(mockUserSocket);

        webRTC.rtc.rooms[""""].push(""sampleSocketId2"");
        webRTC.rtc.userKinds[""""].push(101);

        var mockSocket = new MockSocket(""sampleSocketId2"");
        webRTC.rtc.sockets.push(mockSocket);

        webRTC.rtc.fire(""response_call_user"", mockDataResponse, mockSocket);

        var rcvRspCallUserJson = JSON.parse(mockSocket.data);

        expect(rcvRspCallUserJson.eventName).toMatch(""response_call_user"");
        expect(rcvRspCallUserJson.data.accept_call).toBe(""true"");
        expect(rcvRspCallUserJson.data.caller).toMatch(""101"");
        expect(rcvRspCallUserJson.data.callee).toMatch(""105_servlet"");

    });

    it(""test calling of multiple users (2 online, 1 offline)"", function() {
        var mockDataResponse = JSON.parse(""{\""room\"":\""servlet\"",\""caller\"":\""102\"",\""callee\"":[105, 106, 107],\""callerUsername\"":\""s1\""}"");
        var expectedStat = [true, true, false];

        webRTC.rtc.rooms[""servlet""].push(""sampleSocketId1"");
        webRTC.rtc.userKinds[""servlet""].push(""105_servlet"");

        var mockCallee1Socket = new MockSocket(""sampleSocketId1"");
        webRTC.rtc.sockets.push(mockCallee1Socket);

        webRTC.rtc.rooms[""servlet""].push(""sampleSocketId2"");
        webRTC.rtc.userKinds[""servlet""].push(""106_servlet"");

        var mockCallee2Socket = new MockSocket(""sampleSocketId2"");
        webRTC.rtc.sockets.push(mockCallee2Socket);

        var mockSocket = new MockSocket(""testSocket"");

        webRTC.rtc.fire(""call_user"", mockDataResponse, mockSocket);

        var rcvCallUserJson = JSON.parse(mockSocket.data);

        var calleeArray = mockDataResponse.callee;
        for (var i = 0; i &lt; calleeArray.length; i++) {
            expect(rcvCallUserJson.eventName).toMatch(""receive_call_user"");
            expect(rcvCallUserJson.data.userFound[i].status).toBe(expectedStat[i]);
            expect(rcvCallUserJson.data.userFound[i].userKind).toMatch(calleeArray[i]);
        }

    });

    it(""test calling of multiple users (3 online)"", function() {
        var mockDataResponse = JSON.parse(""{\""room\"":\""servlet\"",\""caller\"":\""102\"",\""callee\"":[105, 106, 107],\""callerUsername\"":\""s1\""}"");
        var expectedStat = [true, true, true];

        webRTC.rtc.rooms[""servlet""].push(""sampleSocketId1"");
        webRTC.rtc.userKinds[""servlet""].push(""105_servlet"");

        var mockCallee1Socket = new MockSocket(""sampleSocketId1"");
        webRTC.rtc.sockets.push(mockCallee1Socket);

        webRTC.rtc.rooms[""servlet""].push(""sampleSocketId2"");
        webRTC.rtc.userKinds[""servlet""].push(""106_servlet"");

        var mockCallee2Socket = new MockSocket(""sampleSocketId2"");
        webRTC.rtc.sockets.push(mockCallee2Socket);

        webRTC.rtc.rooms[""servlet""].push(""sampleSocketId3"");
        webRTC.rtc.userKinds[""servlet""].push(""107_servlet"");

        var mockCallee3Socket = new MockSocket(""sampleSocketId3"");
        webRTC.rtc.sockets.push(mockCallee3Socket);

        var mockSocket = new MockSocket(""testSocket"");

        webRTC.rtc.fire(""call_user"", mockDataResponse, mockSocket);

        var rcvCallUserJson = JSON.parse(mockSocket.data);

        var calleeArray = mockDataResponse.callee;
        for (var i = 0; i &lt; calleeArray.length; i++) {
            expect(rcvCallUserJson.eventName).toMatch(""receive_call_user"");
            expect(rcvCallUserJson.data.userFound[i].status).toBe(expectedStat[i]);
            expect(rcvCallUserJson.data.userFound[i].userKind).toMatch(calleeArray[i]);
        }

    });
});
</code></pre>

<p><strong>Already tried the following:</strong></p>

<ol>
<li>Including a javascript with global variable/s -- still undefined (As
I think it loads the file before running the spec)</li>
<li>following this: <a href=""https://bryce.fisher-fleig.org/blog/setting-up-istanbul-with-jasmine/index.html"" rel=""nofollow noreferrer"">https://bryce.fisher-fleig.org/blog/setting-up-istanbul-with-jasmine/index.html</a> -- No coverage information was collected, exit without writing coverage information</li>
</ol>
",https://stackoverflow.com/questions/50246780/jasmine-karma-istanbul-testing-self-and-or-window-is-undefined,"['node.js', 'unit-testing', 'karma-jasmine', 'jasmine-node', 'karma-coverage']",524,FALSE,2,0
How to test Angular components that use Redux?,"<p>I have started working on an Angular (5) SPA that uses Redux and I also want to see if I can perform component (unit) testing.</p>

<p>I will provide a simple functionality - fetch some todos data from the server:</p>

<h3>todo.service.ts</h3>

<pre><code>  getTodos(): Observable&lt;any&gt; {
    this.ngRedux.dispatch({ type: SHOW_LOADER, message: ""Loading TODOs ..."" });

    let obs = this.http.get&lt;Array&lt;any&gt;&gt;(""api/SampleData/GetTodoList"");
      obs.subscribe(result =&gt; {
        console.log(""Got todos:"", result);
        this.ngRedux.dispatch({ type: HIDE_LOADER });
        this.ngRedux.dispatch({ type: FETCH_TODOS_SUCCESS, todos: result });
      },
      error =&gt; {
        this.ngRedux.dispatch({ type: HIDE_LOADER, message: """" });
        console.error(error);
      });
    return obs;
  }
</code></pre>

<p>Normally, it is not required to return the Observable object, since this function takes care to dispatch the message on its own subscription. However, in order to test the component, it must get this reference. </p>

<h3>todo-list.component.ts</h3>

<pre><code>  constructor(
    private ngRedux: NgRedux&lt;IAppState&gt;,
    private todoService: TodoService) {
  }

  resetTodoList() {
    this.todoService.getTodos();
  }
</code></pre>

<p>So, in order to test <code>TodoListComponent.resetTodoList</code>, I have to mock <code>TodoListComponent</code> dependencies or at least make sure that they are not called when performing the test:</p>

<h3>todo-list.component.spec.ts</h3>

<pre><code>describe('TodosComponent', () =&gt; {
  let component: TodoListComponent;
  let service: TodoService;

  beforeEach(() =&gt; {
    service = new TodoService(null, null);

    component = new TodoListComponent(null, service);
  });

  it('should set todos property with server items', () =&gt; {
    spyOn(service, ""getTodos"").and.callFake(() =&gt; {
      return Observable.of([1, 2, 3]);
    });

  // act and assert should come here
  });
});
</code></pre>

<p>Since <code>resetTodoList</code> is not returning anything, I thought of making it return the <code>Observable</code> and subscribe to it in my test:</p>

<pre><code>  resetTodoList() {
    return this.todoService.getTodos();
  }

  // act and assert part from the test
  component.resetTodoList().subscribe(v =&gt; {
      expect(v.length).toBe(3);
  });
</code></pre>

<p>This pattern seems quite simple, but that means that the developer must take care to return an Observable reference in order to make the function testable. </p>

<p>I am wondering if there are is any alternative to this approach.</p>

<p><strong>Question:</strong> How to test Angular components that use Redux?</p>

<p>P.S. I will add <code>package.json</code> relevant content here to provide a better context:</p>

<pre><code>  ""dependencies"": {
    ""@angular-redux/store"": ""^7.1.1"",
    ""@angular/animations"": ""^5.2.0"",
    ""@angular/cdk"": ""^5.2.4"",
    ""@angular/common"": ""^5.2.0"",
    ""@angular/compiler"": ""^5.2.0"",
    ""@angular/core"": ""^5.2.0"",
    ""@angular/forms"": ""^5.2.0"",
    ""@angular/http"": ""^5.2.0"",
    ""@angular/material"": ""^5.2.4"",
    ""@angular/platform-browser"": ""^5.2.0"",
    ""@angular/platform-browser-dynamic"": ""^5.2.0"",
    ""@angular/router"": ""^5.2.0"",
    ""angular-font-awesome"": ""^3.1.2"",
    ""bootstrap"": ""^4.1.0"",
    ""core-js"": ""^2.4.1"",
    ""font-awesome"": ""^4.7.0"",
    ""hammerjs"": ""^2.0.8"",
    ""jquery"": ""^3.3.1"",
    ""material-design-icons"": ""^3.0.1"",
    ""ng-block-ui"": ""^1.0.4"",
    ""ng2-select"": ""^2.0.0"",
    ""ng2-table"": ""^1.3.2"",
    ""ngx-bootstrap"": ""^2.0.3"",
    ""popper.js"": ""^1.14.3"",
    ""redux"": ""^3.7.2"",
    ""rxjs"": ""^5.5.6"",
    ""tassign"": ""^1.0.0"",
    ""zone.js"": ""^0.8.19""
  },
  ""devDependencies"": {
    ""@angular/cli"": ""~1.7.4"",
    ""@angular/compiler-cli"": ""^5.2.0"",
    ""@angular/language-service"": ""^5.2.0"",
    ""@types/jasmine"": ""~2.8.3"",
    ""@types/jasminewd2"": ""~2.0.2"",
    ""@types/node"": ""~6.0.60"",
    ""codelyzer"": ""^4.0.1"",
    ""jasmine-core"": ""~2.8.0"",
    ""jasmine-spec-reporter"": ""~4.2.1"",
    ""karma"": ""~2.0.0"",
    ""karma-chrome-launcher"": ""~2.2.0"",
    ""karma-coverage-istanbul-reporter"": ""^1.2.1"",
    ""karma-jasmine"": ""~1.1.0"",
    ""karma-jasmine-html-reporter"": ""^0.2.2"",
    ""protractor"": ""~5.1.2"",
    ""ts-node"": ""~4.1.0"",
    ""tslint"": ""~5.9.1"",
    ""typescript"": ""~2.5.3""
  }
</code></pre>
",https://stackoverflow.com/questions/49917923/how-to-test-angular-components-that-use-redux,"['angular', 'unit-testing', 'redux', 'angular5']",629,FALSE,2,0
"root cause and resolve an error returned R&#39;s &#39;lime&#39; library&#39;s, &#39;explain&#39; function","<p>I get this error when using the ""explain"" function from the ""<a href=""https://cran.r-project.org/web/packages/lime/index.html"" rel=""nofollow noreferrer"">lime</a>"" library on a h2o random forest.</p>

<pre><code>Error in elnet(x, is.sparse, ix, jx, y, weights, offset, type.gaussian,  : 
  y is constant; gaussian glmnet fails at standardization step
</code></pre>

<p>I can't find documentation online, or help about this question online.  Can you help me root-cause and resolve it?</p>

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

<pre><code>explainer_h2o_rf  &lt;- lime(x=big_df, 
                          model=fit_rf.hex, 
                          bin_continuous = FALSE,
                          use_density = T, 
                          quantile_bins = F)

# for(i in 1:25){
i &lt;- c(1,2)
explanation_rf &lt;- explain(x = x_lime[i,],
                          explainer = explainer_h2o_rf,
                          n_features = 15,
                          feature_select = ""auto"",
                          labels = ""1"")
</code></pre>

<p>Notes: </p>

<ul>
<li>I am predicting a binomial variable within the h2o model,
'fit_rf.hex'.</li>
<li>I worked through <a href=""http://uc-r.github.io/lime"" rel=""nofollow noreferrer"">this</a> and it worked, but my current approach does not</li>
<li>The ""lime"" tag does not seem to apply to this lime library, but to something that is used for unit testing.</li>
<li>The non-gaussian shouldn't be a problem, because (I think) I have set the flags that deal with non-gaussian (nearly all my data is non-Gaussian) data using kernel methods.</li>
</ul>

<p>Here are sites/questions that didn't contain my answer:</p>

<ul>
<li><a href=""https://stackoverflow.com/questions/21635508/lasso-error-in-glmnet-na-nan-inf"">Lasso error in glmnet NA/NaN/Inf</a></li>
<li><a href=""https://stackoverflow.com/questions/30717201/glmnet-training-throws-error-on-x-y-dataframe-arguments-am-i-using-it-wrong"">glmnet training throws error on x,y dataframe arguments: am I using it wrong?</a></li>
<li><a href=""https://stackoverflow.com/questions/48179423/error-error-in-lognetx-is-sparse-ix-jx-y-weights-offset-alpha-nobs"">Error - Error in lognet(x, is.sparse, ix, jx, y, weights, offset, alpha, nobs)= etc</a></li>
<li><a href=""https://stackoverflow.com/questions/47501108/error-resulting-in-using-cv-glmnet"">Error resulting in using cv.glmnet</a></li>
</ul>
",https://stackoverflow.com/questions/51084343/root-cause-and-resolve-an-error-returned-rs-lime-librarys-explain-functio,"['r', 'random-forest', 'h2o']",2528,TRUE,2,2
How to mock the data(argument) received for the callback function so that the logic in the callback function can be tested in jest? (e.g. fs.readFile),"<p>I have function want to do unit testing, for example, it contains:</p>

<pre><code>function foo (file, option) {
    return new Promise((resolve, reject) =&gt; fs.readFile(file, option, (err, content) =&gt; {
        if (err) return reject(new Error(`Failed to read the file: (${file})`));
        else {
            (...some operations, and that is the point for me to test it...)
            return resolve(...some result...);
        }
    }));
}
</code></pre>

<p>Just right at the beginning of the testing file, I have:</p>

<pre><code>jest.mock('fs', () =&gt; ({
    readFile : jest.fn(),
}));
const fs = require('fs');
</code></pre>

<p>The testing logic is something like:</p>

<pre><code>test('Should get context as string from the template file', async () =&gt; {
    const mockContent = '&lt;a&gt;Hello World&lt;/a&gt;';
    fs.readFile.mockReturnValue(mockContent);
    const result = (await foo('test', 'utf8')).then(() =&gt; 123);
    //
    expect(result).toEqual(123);
});
</code></pre>

<p>However, when I try to run the test, it shows:</p>

<pre><code>- Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.`
</code></pre>

<p>I know it is an issue due to unresolved promise from Jest website; but their suggestion is not what I have actually... I recognize my problem is due to <code>fs.readFile(...)</code> is replaced by the mocking function which returns <code>undefined</code> so that the <code>new Promise</code> is never being rejected/resolved (am I correct?!).</p>

<p>My question is how can I do a unit test like this case? I really don't want to fire a I/O event like using a empty file in oder to make it work... Any thoughts?! Thanks!</p>

<p><strong>/// UPDATE:</strong>
I think a much clear question is how are we mock the data that received by a callback function. In my example it looks like I test against it, but in my real code, what I really want to test is the logic of the callback function.</p>
",https://stackoverflow.com/questions/48493010/how-to-mock-the-dataargument-received-for-the-callback-function-so-that-the-lo,"['javascript', 'unit-testing', 'promise', 'mocking', 'jestjs']",4711,TRUE,2,1
"Python 2.x vs 3.x imports, depending on where script is called/imported from","<p>This is likely the ~1000th question on import differences between Python 2.x and 3.x, but for my specific problem/case I am still stuck after reading most of them. Consider this simple example:</p>

<p><em>Directory structure:</em></p>

<pre><code>main.py
src/
    thermo.py
    constants.py
    __init__.py  # empty
</code></pre>

<p><em>main.py:</em></p>

<pre><code>import src.thermo as thermo
thermo.calc_thermo()
</code></pre>

<p><em>src/thermo.py:</em></p>

<pre><code>from constants import cp

def calc_thermo():
    print(2*cp)

if __name__ == '__main__':
    # Just for testing `thermo.py`
    calc_thermo()
</code></pre>

<p><em>src/constants.py:</em></p>

<pre><code>cp = 1234.
</code></pre>

<p>Now, there are two ways in which I want to use <code>thermo.py</code>; calling it directly from the <code>src/</code> subdirectory (for debugging/unit-testing/.. of this specific file), or as part of the entire program by importing it into <code>main.py</code>. With the example above this all works in Python 2.7, in Python3.x I can call <code>thermo.py</code> from the <code>src/</code> directory, but importing <code>thermo</code> from <code>main.py</code> fails on the import of <code>constants</code>.</p>

<p>There are many similar questions here on SO, most suggesting to fix this with relative imports, i.e. changing <code>thermo.py</code> from:</p>

<pre><code>from constants import cp
</code></pre>

<p>to</p>

<pre><code>from .constants import cp
</code></pre>

<p>Now it works if I call <code>main.py</code>, but I lose the ability to call <code>thermo.py</code> directly from the <code>src/</code> directory! How can this best be solved, i.e. creating the possibility to both import <code>thermo.py</code> from its parent directory (<code>main.py</code>), but also to keep the possibility to call <code>thermo.py</code> directly from <code>src/</code>?</p>
",https://stackoverflow.com/questions/48643160/python-2-x-vs-3-x-imports-depending-on-where-script-is-called-imported-from,"['python', 'python-3.x', 'python-2.7', 'python-import']",84,TRUE,2,1
Testing onUpdate results in TypeError: Cannot read property &#39;val&#39; of undefined,"<p>I have recently migrated my Firebase Functions from beta to 1.0.2 and in the process wrote a bunch of unit tests using the new Firebase Test SDK for Cloud Functions. Some of my functions are responsible for mirroring data from Realtime to Firestore and as such I have used the <strong>onUpdate()</strong> Realtime Database trigger which provides <strong>change</strong> and <strong>context</strong> objects. My issue is, in testing these I get the error <strong>TypeError: Cannot read property 'val' of undefined</strong> because the <strong>after</strong> and <strong>before</strong> properties of the change object are undefined. These functions work when deployed, it's only during testing that this error crops up. One of the functions showing this issue is:</p>

<pre><code>exports.mirrorTransactionUpdates = functions.database.ref(""transactions/{id}"").onUpdate((change, context) =&gt; {
    return firestore.collection(""transactions"").doc(context.params.id).set(change.after.val());
});
</code></pre>

<p>and the unit test is:</p>

<pre><code>describe(""mirrorTransactionUpdates"", () =&gt; {
    it(""should update transactions in firestore"", () =&gt; {
        const data = {date: 1};
        const snapshot = test.database.makeDataSnapshot(data, ""transactions/test_transaction_id"");
        return test.wrap(activeFunctions.mirrorTransactionUpdates)(snapshot, {
            params: {id: ""test_transaction_id""}
        }).then(() =&gt; {
            return firestore.collection(""transactions"").doc(""test_transaction_id"").get()
                .then(mirroredDoc =&gt; {
                    assert.deepEqual(mirroredDoc.data(), data);
                });
        });
    });
});
</code></pre>

<p>I cannot find anywhere why the change.before and change.after are not defined when unit testing. I also do not see anywhere in the docs where I can/have to define them myself. It should be noted that this also happens with the <strong>onWrite()</strong> event handler. Any help would be greatly appreciated!</p>

<p>I am using firebase-admin 5.11.0 and firebase-functions 1.0.2</p>
",https://stackoverflow.com/questions/50308205/testing-onupdate-results-in-typeerror-cannot-read-property-val-of-undefined,"['firebase', 'google-cloud-functions']",259,FALSE,2,0
How to use FakeItEasy to verify FindOneAndUpdateAsync method ran Against faked MongoCollection?,"<p>I am using the <code>FakeItEasy</code> library for unit testing and trying to write a unit test for a mongo update statement and verify that the <code>FindOneAndUpdateAsync</code> method was called using <code>MustHaveHappened()</code>.</p>

<p>I have created a unit test that will fake the <code>dbcontext</code> class, use that to generate a collection, then call the method that will run the update statement against the fake collection. When I run the test in debug mode, it is hitting the <code>FindOneAndUpdateAsync</code> method, however the <code>MustHaveHappened()</code> result is showing that the method did not run against the faked collection.</p>

<p>Is there a way to use <code>FakeItEasy</code> to detect that the <code>FindOneAndUpdateAsync</code> method ran when the collection it is being run against is also being faked?</p>

<p><strong>Error Message from Failed Test</strong></p>

<blockquote>
  <p>Assertion failed for the following call:
      Any call made to the fake object.
        where x => (x.Method.Name == ""FindOneAndUpdateAsync"")
    Expected to find it once or more but didn't find it among the calls:
      1: MongoDB.Driver.IMongoCollection`1[ConsoleApp3.Fruit].WithWriteConcern(writeConcern: { w : ""majority"" })</p>
</blockquote>

<p><strong>Unit Test Using FakeItEasy</strong></p>

<pre><code>    [Fact]
    public async Task TestFruitUpdate()
    {
        IDBContext fakeDbContext = A.Fake&lt;DBContext&gt;();
        var fakeMongoCollection = A.Fake&lt;IMongoCollection&lt;Fruit&gt;&gt;();
        var fruitEntity = new Fruit()
        {
            Id = new MongoDB.Bson.ObjectId(),
            Name = ""Apple"",
            Price = 2.0,
            Quantity = 3,
        };

        A.CallTo(() =&gt; fakeDbContext.GetCollection&lt;Fruit&gt;()).Returns(fakeMongoCollection);
        A.CallTo(fakeDbContext).WithReturnType&lt;IMongoCollection&lt;Fruit&gt;&gt;().Returns(fakeMongoCollection);

        var repository = new FruitRepository(fakeDbContext);

        await repository.UpdateFruitQuantityAsync(fruitEntity);

        A.CallTo(fakeMongoCollection).Where(x =&gt; x.Method.Name == ""FindOneAndUpdateAsync"").MustHaveHappened();
    }
</code></pre>

<p><strong>Interface for DBContext</strong></p>

<pre><code>public interface IDBContext
{
    IMongoClient Client { get; }

    IMongoDatabase Database { get; }

    IMongoCollection&lt;TDocument&gt; GetCollection&lt;TDocument&gt;()
        where TDocument : Fruit;
}
</code></pre>

<p><strong>Fruit Entity</strong></p>

<pre><code>public class Fruit
{
    public ObjectId Id { get; set; }
    public string Name { get; set; }
    public double Price { get; set; }
    public int Quantity { get; set; }
}
</code></pre>

<p><strong>Fruit Repository Class</strong></p>

<pre><code>class FruitRepository
{
    private readonly IDBContext _dbContext;

    public FruitRepository(IDBContext dBContext) =&gt;
        _dbContext = dBContext;

    public virtual Task UpdateFruitQuantityAsync(Fruit fruitEntity) =&gt;
        _dbContext.GetCollection&lt;Fruit&gt;()
            .WithWriteConcern(WriteConcern.WMajority)
            .FindOneAndUpdateAsync(
                Builders&lt;Fruit&gt;.Filter.Eq(j =&gt; j.Id, fruitEntity.Id),
                Builders&lt;Fruit&gt;.Update.Set(j =&gt; j.Quantity, fruitEntity.Quantity)
             );
}
</code></pre>
",https://stackoverflow.com/questions/51404602/how-to-use-fakeiteasy-to-verify-findoneandupdateasync-method-ran-against-faked-m,"['c#', 'mongodb', 'unit-testing', 'fakeiteasy']",1182,TRUE,2,1
jest-jasmine2 env.js unhandled error,"<p>I'm getting this cryptic error message when using Jest unit testing to test my code.</p>

<blockquote>
  <p>console.error node_modules/jest-jasmine2/build/jasmine/Env.js:198
      Unhandled error</p>
  
  <p>console.error node_modules/jest-jasmine2/build/jasmine/Env.js:199
      Error
          at model.wrappedPointCut [as save] (/home/pi/dev/Group_2/node_modules/mongoose/lib/services/model/applyHooks.js:131:29)
          at /home/pi/dev/Group_2/controllers/Manager.js:80:17
          at Array.map ()
          at /home/pi/dev/Group_2/controllers/Manager.js:79:55
          at 
          at process._tickCallback (internal/process/next_tick.js:160:7)</p>
  
  <p>console.error node_modules/jest-jasmine2/build/jasmine/Env.js:198
      Unhandled error</p>
  
  <p>console.error node_modules/jest-jasmine2/build/jasmine/Env.js:199</p>
</blockquote>

<p>Here's how my test code looks like</p>

<pre><code>it.only('Adding a shift entry to DB works', () =&gt; {
  expect.assertions(3);
  return m.associateToShifts([""johnDoe""], [""Mondays""]).then(cmdResult =&gt; {
    expect(cmdResult.length).toBe(1);
    expect(cmdResult[0].employee.employeeId).toBe(""johnd"");
    expect(cmdResult[0].shift.shiftTitle).toBe(""Mondays"");
  }).catch(e =&gt; console.log(`Error: Cannot add shift to DB properly. ${e}`));
});
</code></pre>

<p>Here's how my code in Manager.js looks like on line 70 - 81, which is what jest-jasmine2 is complaining about:</p>

<pre><code>var employeeData = Promise.all(employees.map(function(emp) {
      emp.save();
}));
</code></pre>

<p><code>employees</code> is an array of employee objects based on a mongoose <code>findOne()</code> employee query.</p>

<p>The test passes despite having this error shown. </p>

<p>Here are some things I've tried: 1) Update Jest to version 22.0.6 2) Update Node JS to version 9.4.0. None of those attempts have worked.</p>
",https://stackoverflow.com/questions/48247089/jest-jasmine2-env-js-unhandled-error,"['javascript', 'node.js', 'mongodb', 'mongoose', 'jestjs']",5445,TRUE,2,1
Unit tests works locally but does not work on Jenkins,"<p>Been banging my head for hours now. I have just gotten started with Docker, and build systems. I have a PHP Codeception (unit testing framework) codebase as a repo example. Locally, I am able to successfully run the test, but when I check-in my code and it goes to the CI (Jenkins), the client program can be invoked but says no tests found.</p>

<p><strong>*note</strong> <em>I know that my build definitions could use some work, my goal is just to get a working build.</em></p>

<p><strong>Dockerfile</strong> </p>

<pre><code>FROM codeception/codeception
</code></pre>

<p><strong>Makefile</strong></p>

<pre><code>APP_NAME=codeception
ROOT_DIR=${PWD}
WORK_DIR=app

    docker_build:
        docker build -t $(APP_NAME) .

    run_test:
        docker run --rm --name ception -w /$(WORK_DIR) -v $(ROOT_DIR):/$(WORK_DIR) $(APP_NAME) run acceptance
</code></pre>

<p>Just for arguments sake, this is how it prints in the build system</p>

<pre><code>docker run --rm --name ception -w /app -v /var/jenkins_home/workspace/codeception:/app codeception run
</code></pre>

<p><strong>Build Triggers</strong></p>

<pre><code>make docker_build
make run_test
</code></pre>

<p><strong>Local Output</strong></p>

<pre><code>OK (1 test, 0 assertions)
</code></pre>

<p><strong>Jenkins Output</strong></p>

<p>*note did not fail, but..</p>

<pre><code>no tests executed!
</code></pre>

<p><strong>Jenkins Installation</strong></p>

<p>Host is a Docker machine droplet on digital ocean and I ran a Jenkins container voluming Docker sock so I can invoke Docker on build triggers</p>

<hr>

<p><strong>ANOTHER QUESTION</strong></p>

<p>Given the above preconditions with the command:</p>

<p>*note the <code>pwd</code></p>

<pre><code>docker run --rm --name ception -w /app -v /var/jenkins_home/workspace/codeception:/app codeception run; pwd
</code></pre>

<p>Jenkins output:</p>

<pre><code>/var/jenkins_home/workspace/codeception
</code></pre>

<p>I was expecting it to output <code>/app</code> because my understanding is, it invokes <code>pwd</code> from inside the docker container, so this should have outputed the <code>/app</code> directory. I am confused now</p>

<p><strong>Logs:</strong></p>

<pre><code>Started by GitHub push by edsk3o
Building in workspace /var/jenkins_home/workspace/codeception
 &gt; git rev-parse --is-inside-work-tree # timeout=10
Fetching changes from the remote Git repository
 &gt; git config remote.origin.url https://github.com/edsk3o/codeception.git # timeout=10
Fetching upstream changes from https://github.com/edsk3o/codeception.git
 &gt; git --version # timeout=10
using GIT_ASKPASS to set credentials 
 &gt; git fetch --tags --progress https://github.com/edsk3o/codeception.git +refs/heads/*:refs/remotes/origin/*
 &gt; git rev-parse refs/remotes/origin/master^{commit} # timeout=10
 &gt; git rev-parse refs/remotes/origin/origin/master^{commit} # timeout=10
Checking out Revision 1a7dd08ef1ed9e8e7b3f236c50690b65c65f37e8 (refs/remotes/origin/master)
 &gt; git config core.sparsecheckout # timeout=10
 &gt; git checkout -f 1a7dd08ef1ed9e8e7b3f236c50690b65c65f37e8
Commit message: ""laksjd""
 &gt; git rev-list --no-walk 528640c7be393aaa06f94edc80f12234a759efd6 # timeout=10
[codeception] $ /bin/sh -xe /tmp/jenkins9213645655529951332.sh
+ make docker_build
docker build -t codeception .
Sending build context to Docker daemon  3.408MB

Step 1/1 : FROM codeception/codeception
 ---&gt; 1681da57f253
Successfully built 1681da57f253
Successfully tagged codeception:latest
+ make run_test
docker run --rm --name ception -w /app -v /var/jenkins_home/workspace/codeception:/app codeception run acceptance; pwd
Codeception PHP Testing Framework v2.3.8
Powered by PHPUnit 6.5.6 by Sebastian Bergmann and contributors.

[1mAcceptance Tests (0) [22m---------------------------------------
------------------------------------------------------------


Time: 89 ms, Memory: 10.00MB

[30;43mNo tests executed![0m
/var/jenkins_home/workspace/codeception
Finished: SUCCESS
</code></pre>
",https://stackoverflow.com/questions/49049864/unit-tests-works-locally-but-does-not-work-on-jenkins,"['php', 'docker', 'jenkins', 'build', 'devops']",675,FALSE,2,0
Error of &#39;appendchild&#39; of null during running ng test in angular 6,"<p>I have an angular 6 project with typescript 2.8.0 and node version 11. 
I have a functional dev application and trying to setup a unit testing environment with jasmine karma, due to limited knowledge about these frameworks I am not able to debug the following error.</p>

<pre><code>ERROR: TypeError: Cannot read property 'appendChild' of null
TypeError: Cannot read property 'appendChild' of null
    at HtmlReporter.specDone (http://localhost:9876/base/node_modules/karma-jasmine-html-reporter/src/lib/html.jasmine.reporter.js?a380599bba71e79ed6dc82aa9a857815d894cfda:150:15)
    at dispatch (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?0b1eaf7a13cae32191eadea482cfc96ae41fc22b:4560:28)
    at ReportDispatcher.specDone (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?0b1eaf7a13cae32191eadea482cfc96ae41fc22b:4531:11)
    at Spec.specResultCallback [as resultCallback] (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?0b1eaf7a13cae32191eadea482cfc96ae41fc22b:1249:18)
    at complete (http://localhost:9876/base/node_modules/jasmine-core/lib/jasmine-core/jasmine.js?0b1eaf7a13cae32191eadea482cfc96ae41fc22b:567:12)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:421:1)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:188:1)
    at drainMicroTaskQueue (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone.js:595:1)
</code></pre>

<p>I have commented every spec in all the spec files, but still the following error resulted. But my mere concern is that the error is due to some incorrect configuration in karma.conf.ts </p>

<p>The following is my karme.config.ts file, please suggest me the correction to the environment ready.</p>

<p>// Karma configuration file, see link for more information
// <a href=""https://karma-runner.github.io/1.0/config/configuration-file.html"" rel=""nofollow noreferrer"">https://karma-runner.github.io/1.0/config/configuration-file.html</a></p>

<pre><code>module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma')
    ],
    client:{
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    coverageIstanbulReporter: {
      dir: require('path').join(__dirname, 'coverage'), reports: [ 'html', 'lcovonly' ],
      fixWebpackSourcePaths: true
    },
    angularCli: {
      environment: 'dev'
    },
    reporters: ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
  });
};
</code></pre>

<p><strong>Edit:</strong>
   The following is one of my spec files, and it has only one spec which is commented. So there are no spec methods that are running.</p>

<p>import { async, ComponentFixture, TestBed } from '@angular/core/testing';</p>

<p>import { PassbackComponent } from './passback.component';</p>

<pre><code>describe('PassbackComponent', () =&gt; {
  let component: PassbackComponent;
  let fixture: ComponentFixture&lt;PassbackComponent&gt;;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ PassbackComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(PassbackComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  // it('should create', () =&gt; {
  //   expect(component).toBeTruthy();
  // });
});
</code></pre>

<p>There are a lot of similar questions in StackOverflow but none of them solves because others are of incorrect specs but mine if of possibly some other reason</p>

<p>Thank you so much in advance.</p>
",https://stackoverflow.com/questions/53664627/error-of-appendchild-of-null-during-running-ng-test-in-angular-6,"['unit-testing', 'jasmine', 'angular6', 'karma-jasmine']",1453,TRUE,2,2
"Fake object that is created by a method, not a constructor","<p>I am trying to unit test code that uses an API, so I am trying to decouple.</p>

<p>I have created an interface for the ""Application"" class inside the API, which is sealed.</p>

<p>I then created a class that uses the interface which has one method that returns an ""Application"" type object.</p>

<p>Here is where I am having trouble, in my unit test I try to create an ""Application"" object to verify if the return value is correct. However the ""Application"" class does not have any constructors, nothing public or private(I checked with reflection). The object is created by calling static Application.Connect(AnotherTypeFromAPI arg), which returns an Application object.</p>

<p>How do I return a fake object that I cannot create?</p>

<pre><code>appMock.Connect(arg).Returns(""How do I return an Application object here?""));
</code></pre>

<p>Or am I going about this the wrong way in regards to unit testing code that relies on an API? The entire API relies on the ""Application"" type so if I cannot fake it, I am not sure yet how I can stub or mock the other methods I need.</p>

<p>I am using C#, NUnit, NSUbstitute.</p>
",https://stackoverflow.com/questions/50457644/fake-object-that-is-created-by-a-method-not-a-constructor,"['c#', 'mocking', 'nunit', 'nsubstitute']",1130,TRUE,1,2
Jest Testing Error - Invariant Violation: Target container is not a DOM element,"<p>I'm new to doing unit testing and I keep getting this error:</p>

<blockquote>
  <p>Invariant Violation: Target container is not a DOM element.</p>
  
  <p>at invariant (node_modules/fbjs/lib/invariant.js:42:15)</p>
  
  <p>at legacyRenderSubtreeIntoContainer (node_modules/react-dom/cjs/react-dom.development.js:17238:34)</p>
  
  <p>at Object.render (node_modules/react-dom/cjs/react-dom.development.js:17317:12)</p>
  
  <p>at Object. (src/client/index.js:243:73)</p>
  
  <p>at Object. (src/client/components/block/Header.js:294:40)</p>
  
  <p>at Object. (src/client/components/block/index.js:123:41)</p>
  
  <p>at Object. (src/client/containers/app.js:195:40)</p>
  
  <p>at Object. (tests/client/containers/App.test.js:13:12)</p>
</blockquote>

<p>I think it has to do with the way my app.js is structured but dont know why...</p>

<p>Here my App.js :</p>

<pre><code>const App = () =&gt; (
  &lt;Box&gt;
    &lt;Router getUserConfirmation={getConfirmation} hashType={'noslash'} basename={'/'}&gt;
      &lt;Box&gt;
        &lt;Route exact path=""/"" component={Home}/&gt;
        &lt;Route path=""/:room"" component={Room}/&gt;
      &lt;/Box&gt;
    &lt;/Router&gt;
  &lt;/Box&gt;
)

const mapStateToProps = (state) =&gt; {
  return {
    message: state.message
  }
}
export default connect(mapStateToProps, null)(App)
</code></pre>

<p>I'm using jest/enzyme/chai for unit tests</p>

<p>my App.test.js :</p>

<pre><code>import { expect } from 'chai'
import React from 'react'
import { shallow } from 'enzyme'
import App from '../../../src/client/containers/app'

jest.mock('react-router')

describe('&lt;App /&gt;', () =&gt; {
  it('renders without crashing', () =&gt; {
    const wrapper = shallow(
      &lt;App/&gt;
    ).dive()
  })
})
</code></pre>

<p>my devDependecies in package.json :</p>

<pre><code>""devDependencies"": {
    ""babel-cli"": ""^6.7.7"",
    ""babel-core"": ""^6.7.7"",
    ""babel-eslint"": ""^7.2.2"",
    ""babel-jest"": ""^23.4.0"",
    ""babel-loader"": ""^6.2.4"",
    ""babel-plugin-__coverage__"": ""^0.111111.1"",
    ""babel-preset-env"": ""^1.7.0"",
    ""babel-preset-es2015"": ""^6.6.0"",
    ""babel-preset-react"": ""^6.24.1"",
    ""babel-preset-stage-0"": ""^6.5.0"",
    ""babel-watch"": ""^2.0.2"",
    ""chai"": ""^4.1.2"",
    ""chai-enzyme"": ""^1.0.0-beta.1"",
    ""chai-jest-diff"": ""^1.0.2"",
    ""chai-jest-snapshot"": ""^2.0.0"",
    ""dirty-chai"": ""^2.0.1"",
    ""enzyme"": ""^3.3.0"",
    ""enzyme-adapter-react-16"": ""^1.1.1"",
    ""eslint"": ""^4.0.0"",
    ""eslint-plugin-babel"": ""^3.3.0"",
    ""eslint-plugin-react"": ""^7.10.0"",
    ""jest"": ""^23.4.1"",
    ""nyc"": ""^6.4.4"",
    ""react-test-renderer"": ""^16.4.1"",
    ""redux-devtools-extension"": ""^2.13.5"",
    ""webpack"": ""^1.13.0"",
    ""webpack-dev-middleware"": ""^1.6.1"",
    ""webpack-dev-server"": ""^1.14.1"",
    ""webpack-hot-middleware"": ""^2.10.0""
  },
</code></pre>

<p>and my webpack.config.js :</p>

<pre><code>var path = require('path');

module.exports = {
  entry: './src/client/index.js',

  output: {
    path: path.join(__dirname, 'build'),
    filename: 'bundle.js'
  },
  devServer: {
    compress: true,
    disableHostCheck: true,
  },

  watchOptions: {
    poll: 1000,
    aggregateTimeout:300,
  },

  module: {
    loaders: [{
      test: /\.js$/,
      exclude: /node_modules/,
      loader: 'babel',
      query:{
        presets: [""es2015"", ""react"", ""stage-0""]
      }
    }]
  }
};
</code></pre>

<p>Thank you for help :)</p>

<p>EDIT:</p>

<p>Looking for a solution, I noticed that the error occurs during the import of my components! Would it come from webpack?</p>

<p>EDIT:</p>

<p>My error was in my HEADER.JS because I use persistor for manage my user connection.
For moment I delete it</p>
",https://stackoverflow.com/questions/51337526/jest-testing-error-invariant-violation-target-container-is-not-a-dom-element,"['reactjs', 'unit-testing', 'jestjs', 'chai', 'enzyme']",2608,TRUE,1,1
Spring Boot WebMvc unit test date error: perform() returned date is earlier than expected(due to GMT assumption),"<p>I am using Spring Boot Test framework + Mockito to do controller unit testing. I find the test fails due to a strange error: when I tell Mockito to return an object with <code>java.util.Date</code> field, the response always has a date string one day earlier than expected.</p>

<p>My test is like this:</p>

<pre><code>package com.mycompany.myapp.controller;

import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import com.privalia.binlookup.model.BinInfo;
import com.privalia.binlookup.repo.BinInfoRepository;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.MOCK, properties=""classpath:test.properties"")
@AutoConfigureMockMvc(secure=false)
public class BinInfoControllerUnitTests {
    @InjectMocks
    private BinInfoController controller;

    private MockMvc mockMvc;

    @MockBean
    private BinInfoRepository repository;

    private BinInfo mockBinInfo;

    @Before
    public void init() throws ParseException{
        SimpleDateFormat fmt = new SimpleDateFormat(""dd/MM/yyyy"");
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
        this.mockBinInfo = new BinInfo();
        this.mockBinInfo.setId(new Long(42));
        this.mockBinInfo.setBin(""touhou"");
        this.mockBinInfo.setJson_full(""{is_json:true}"");
        this.mockBinInfo.setCreateAt(fmt.parse(""18/08/2018""));
    }


    @Test
    public void testBinInfoControllerSearchBIN() throws Exception {
        when(this.repository.findByBin(""touhou"")).thenReturn(mockBinInfo);

        this.mockMvc.perform(get(""/search/touhou"")
                .accept(MediaType.APPLICATION_JSON_UTF8_VALUE)
                .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
            .andDo(print())
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
            .andExpect(content().string(not("""")))
            .andExpect(jsonPath(""$.bin"", is(""touhou"")))
            .andExpect(jsonPath(""$.json_full"", is(""{is_json:true}"")))
            .andExpect(jsonPath(""$.createAt"", is(""18/08/2018"")));
    }
}
</code></pre>

<p>And my controller is:</p>

<pre><code>package com.mycompany.myapp.controller;

import java.awt.MediaTracker;
import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.ResponseEntity.BodyBuilder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.privalia.binlookup.model.BinInfo;
import com.privalia.binlookup.repo.BinInfoRepository;

@RestController
@RequestMapping(value=""/"")
public class BinInfoController {

    @Autowired
    private BinInfoRepository repository;

    @RequestMapping(value=""/search/{bin}"", method=RequestMethod.GET)
    public ResponseEntity&lt;BinInfo&gt; searchBIN(@Valid @PathVariable String bin) {
        BinInfo found = repository.findByBin(bin);
        BodyBuilder builder = ResponseEntity.status(HttpStatus.OK);
        builder.contentType(MediaType.APPLICATION_JSON_UTF8);
        return (found == null ? builder.body(null) : builder.body(found));
    }

}
</code></pre>

<p>The test fails, because the returned <code>createAt</code> string is <code>17/08/2018</code>, not <code>18/08/2018</code>.</p>

<p>I am in timezone ""Madrid/Europe (GMT +0200, CEST)"" because we are in summer and with DST(Daylight saving time), and I suspect some timezone stuff is interfering.</p>

<p>My guess:</p>

<p><strong>The mock object has a <code>java.util.Date</code> object without timezone information, and is the 00:00 of 18 of August; when passed the Spring context or Jackson or Mockito in <code>perform()</code>, the JSON parsed is considered GMT, thus is minus 2 hours, thus back to 17 of August.</strong></p>

<p>but I don't know where to find the related configuration, whether to tell Jackson, or to Spring, or Mockito <strong>not</strong> to do the conversion. </p>

<p>EDIT:</p>

<p>Cause confirmed: when I change the date string to <code>18/08/2018 02:00:00</code>, the returned date is <code>18/08/2018 00:00:00</code>. </p>
",https://stackoverflow.com/questions/51362626/spring-boot-webmvc-unit-test-date-error-perform-returned-date-is-earlier-than,"['java', 'unit-testing', 'spring-boot', 'jackson', 'mockito']",2688,FALSE,1,1
Is there any OnTimeSetUp attribute which accepts parameters in NUnit?,"<p>I have a unit testing project that contains all tests for all of my platforms. But depending on platform type I need to make checks in test cases. For example if I have something like this:</p>

<pre><code>[TestCase]
public void Do_Sth_ExpectSth()
{
    //Arrange
    //....
    //Act
    //....
    //Assert
    if(TestPlatform.IsMainLine)
    {
        Assert.That(...); //assert something based on MainLine platform
    }
    else
    {
        Assert.That(.....); // assert something else for non mainline platforms
    }
}
</code></pre>

<p>I could test for each platforms by passing PlatformType enum in <code>TestCase(...)</code> attribute but at some point I thought to configure the platform type only once globally and run every test in the project for each platform type.</p>

<p>So, I could have something like this:</p>

<pre><code>[SetUpFixture]
public class GlobalSetup
{
    [OneTimeSetUp(PlatformType.MainLine)]
    [OneTimeSetUp(PlatformType.Other)]
    public void Configure(PlatformType platform) 
    {
        TestPlatform.SetPlatform(platform);
        //other stuff
    }

    [OneTimeTearDown]
    public void Reset() 
    {
        //reset
    }
}
</code></pre>

<p>This would help me because each unit test would run under a specific platform type but in the main time I would not have to change the code for each platform type and re-run again the test project(<em>which I dont like</em>). So, I was thinking if there is a <code>OneTimeSetUp</code> kind of attribute which will accept params and then every test method is re-run again for different params. I would prefer this rather than setting <code>PlatformType</code> in each test method because I make some automapper configuration globally which is based on platform type.</p>

<p>Any help is appreciated!</p>
",https://stackoverflow.com/questions/52185708/is-there-any-ontimesetup-attribute-which-accepts-parameters-in-nunit,"['c#', 'unit-testing', 'nunit']",415,TRUE,1,1
How to use PhpUnit/DbUnit with a real Doctrine EntityManager for functional testing,"<p>I'm using <code>PhpUnit/DbUnit</code> to create a set of 5 to 10 fixture records. I use in-memory sqlite.</p>
<p>I successfully can use a <code>Doctrine\DBAL\Connection</code> to access it, so I can use methods like <code>-&gt;insert( $tableName, $data );</code> for my tests.</p>
<p>Now I want to consume the Doctrine <code>EntityManager</code> so I can create an entity and call <code>-&gt;persist()</code>.</p>
<p>In unit-testing I used to mock the <code>EntityManager</code> and asserted an expectation to call persist.</p>
<p>But for functional-testing I want to check the final result written to the DB, even go further and re-use the result of the writing.</p>
<p>I therefore need to create a real EntityManager but consuming the DbUnit connection.</p>
<p>I've seen that creting a new <code>EntityManager</code> takes 3 arguments, but still the creator is protected:</p>
<pre><code>/**
 * Creates a new EntityManager that operates on the given database connection
 * and uses the given Configuration and EventManager implementations.
 *
 * @param \Doctrine\DBAL\Connection     $conn
 * @param \Doctrine\ORM\Configuration   $config
 * @param \Doctrine\Common\EventManager $eventManager
 */
protected function __construct(Connection $conn, Configuration $config, EventManager $eventManager)
{
    [...]
</code></pre>
<p>I don't know if I'm expected to create a subclass, or maybe use an already subclassed EntityManager or how should I proceed.</p>
<h1>So question:</h1>
<p>How can I setup a real <code>Doctrine\ORM\EntityManager</code> within a <code>PhpUnit/DbUnit</code> test class using the low level <code>Doctrine\Dbal\Connection</code> that is already bound to the <code>DbUnit</code> connection?</p>
<p>Note: I'm inside a symfony3 project, so mapping files are in the expected places of symfony.</p>
",https://stackoverflow.com/questions/52864751/how-to-use-phpunit-dbunit-with-a-real-doctrine-entitymanager-for-functional-test,"['doctrine-orm', 'phpunit', 'entitymanager', 'functional-testing']",243,FALSE,1,0
Mockable Functionalities by Mixing Monad Transformers,"<p>How can I build separate functionalities in independent and mockable monads and then put them together in my main app monad?</p>

<p>For example let's assume my app has a chat feature.</p>

<p>I am following <a href=""https://lexi-lambda.github.io/blog/2017/06/29/unit-testing-effectful-haskell-with-monad-mock/"" rel=""nofollow noreferrer"">Unit testing effectful Haskell with monad-mock
</a> and I should be able to easily switch the implementation of a simple chat server in my app.</p>

<p>I tried to model the chat engine by a monad:</p>

<pre class=""lang-hs prettyprint-override""><code>class Monad m =&gt; ChatEngine m where
  login :: Username -&gt; m (S.Set User)
  publish :: Username -&gt; PostBody -&gt; m [Post]
  allPosts :: m [Post]

  default login :: (MonadTrans t, ChatEngine m', m ~ t m') =&gt; Username -&gt; m (S.Set User)
  login = lift . login

  default publish :: (MonadTrans t, ChatEngine m', m ~ t m') =&gt; Username -&gt; PostBody -&gt; m [Post]
  publish u = lift . publish u

  default allPosts :: (MonadTrans t, ChatEngine m', m ~ t m') =&gt; m [Post]
  allPosts = lift allPosts

instance ChatEngine m =&gt; ChatEngine (ExceptT e m)
-- ...
</code></pre>

<p><code>AppM m</code> is my app monad that can be the underlying monad in a any transformer stack, like a <a href=""https://stackoverflow.com/questions/48286926/using-readert-transformer-in-scottyt-vs-actiont"">Scotty Web server</a>: <code>type AppM m a = ReaderT AppConfig m a</code>.</p>

<p>I can add <code>StateT</code> or <code>MonadIO</code> to <code>AppM</code> stack and implement <code>ChatEngine</code> interface for <code>AppM</code>. But what if I want to use a default, pre-made instance of <code>ChatEngine</code>? For example this simple mock:</p>

<pre class=""lang-hs prettyprint-override""><code>data InMemoryChat = InMemoryChat {
  users :: S.Set User
, posts :: [Post]
}

newtype MockedChatEngine m a = MockedChatEngine {
  unMockChatEngine :: StateT InMemoryChat m a
} deriving (Functor, Applicative, Monad, MonadTrans, MonadIO, MonadError e, MonadReader r, MonadWriter w, MonadState InMemoryChat)

instance (MonadIO m, Monad m) =&gt; ChatEngine (MockedChatEngine m) where
  login username = MockedChatEngine $ do
    now &lt;- liftIO Clock.getCurrentTime
    users' &lt;- fmap users get
    return $ S.insert (mkUser username now) users'

  publish username body = MockedChatEngine $ do
    now &lt;- liftIO Clock.getCurrentTime
    InMemoryChat users' posts' &lt;- get
    let posts'' = mkPost username body now : posts'
    put $ InMemoryChat users' posts''
    return posts''

  allPosts = MockedChatEngine $ fmap posts get
</code></pre>

<p>I needed <code>AppM</code> to have a mix of features and functionalities, like having a chat engine.</p>

<p>So I tried this approach:</p>

<pre class=""lang-hs prettyprint-override""><code>data AppMState = AppMState {
  chatEngine :: MockedChatEngine Identity ()
-- , someOtherFeature ::
}

newtype AppM m a = AppM { unAppM :: ReaderT AppMState m a }
  deriving (Functor, Applicative, Monad, MonadTrans, MonadIO, MonadReader AppMState)

instance (Monad m, MonadIO m) =&gt; ChatEngine (AppM m) where
  allPosts = do
    engine &lt;- fmap chatEngine ask
    -- now what?
    undefined
  publish = undefined
  login = undefined
</code></pre>

<p>And I am obviously missing something.</p>

<p>Generally what is the right way of building a larger app by developing independent features with replaceable implementations and putting them together using monad transformers?</p>
",https://stackoverflow.com/questions/49141348/mockable-functionalities-by-mixing-monad-transformers,"['haskell', 'monads', 'monad-transformers']",58,FALSE,1,0
How to test Web Services with Elixir?,"<p>We have a couple of REST APIs that need to be tested. APIs are owned by some other team. Currently, we use <strong>Node.js</strong> with <strong>Ava</strong> to test our APIs.</p>

<p>We have recently started exploring Elixir as our scripting language. We would like to experiment with Elixir to test REST API. The question here is - <strong>how to test external web services/REST API with Elixir?</strong></p>

<p>Every Google search around Elixir testing refers back to ExUnit which is basically for unit testing of Elixir apps. We don't have any app written in Elixir or in Phoenix.</p>

<p>All we want to do is to test API end-to-end. How to do that with Elixir? Which libraries to use? I know I can make network calls from my tests written in ExUnit and verify the API behavior, but not sure if it is the right way.</p>

<p><em>NOTE: We already have JMeter in place for load testing of API but we wish to keep functional testing separate from load testing due to complex workflows involved with API.</em></p>
",https://stackoverflow.com/questions/51626365/how-to-test-web-services-with-elixir,"['testing', 'automated-tests', 'elixir', 'web-api-testing']",582,TRUE,1,1
How do I resolve a dependency in a Class Library from the container configured in Startup?,"<p>The objective is using IoC and being able to [mock dependencies] for unit testing.</p>

<p>The project: .NET Core Web API with multiple class libraries</p>

<p>I'm using Microsoft.Extensions.DependencyInjection for my IoC and I'd like to keep using it if it supports what I'm trying to accomplish.</p>

<p>The problem: At least one class in my assemblies (class libraries) has a dependency that needs to mocked (e.g. using Moq). I completely understand that I can use constructor injection to inject the interface but that doesn't fit the scenario. </p>

<p>What I'm simply trying to accomplish in my assembly is to resolve the dependency using the container that I initiated in my Startup class of the Web API. </p>

<p>How would I do that? And if that isn't possible, what may be another way to accomplish the same thing, i.e. mocking my printer without using dependency injection?</p>

<p>Below is some sample code which hopefully clarifies this a bit.</p>

<p>Web API's Startup.cs (has a reference to assembly which defines printer)</p>

<pre><code>public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped&lt;IPrinter, Printer&gt;();
}
</code></pre>

<p>In a different assembly, I'd like to resolve an instance of Printer using the same container.</p>

<pre><code>    public interface IPrinter
    {
        void Print(string text);
    }

    public class Printer : IPrinter
    {
        public void Print(string text)
        {
            Console.WriteLine(""Printing: "" + text);
        }
    }


    public class Task
    {
        public void PrintSomething(string text)
        {
            //do not 'new up' but resolve it from the container of Startup.cs
            var printer = new Printer(); 
            printer.Print(text);
        }
    }
</code></pre>
",https://stackoverflow.com/questions/50707105/how-do-i-resolve-a-dependency-in-a-class-library-from-the-container-configured-i,"['c#', 'unit-testing', 'asp.net-core', 'dependency-injection', 'mocking']",1466,TRUE,1,1
Testing laziness of IsString s =&gt; s -&gt; Bool function,"<p>Is there any way I can test that a function <code>p :: IsString s =&gt; s -&gt; Bool</code> evaluates its input lazily? That is, it only consumes a part of its input when determining its result. And is it possible in such a way that it's compatible with both <code>String</code> and <code>Data.Text.Lazy</code>?</p>

<p>I've looked at the Q&amp;A <a href=""https://stackoverflow.com/questions/41151927/unit-testing-the-undefined-evaluated-in-lazy-expression-in-haskell"">Unit-testing the undefined evaluated in lazy expression in Haskell</a>, which doesn't cover <code>IsString</code> specifically, and I've found the <a href=""http://hackage.haskell.org/package/StrictCheck"" rel=""nofollow noreferrer"">StrictCheck</a> package on Hackage that I'm not really sure how works. Does it apply here?</p>

<h2>Problem</h2>

<p>I've got a predicate,</p>

<pre><code>p :: IsString s =&gt; s -&gt; Bool
</code></pre>

<p>and an Hspec test,</p>

<pre><code>{-# LANGUAGE OverloadedStrings #-}

...
import Data.String (fromString)

spec_p :: Spec
spec_p =
  describe ""p"" $
    it ""is lazy"" $ p (fromString x) `shouldBe` y
      where
        x = ""foo"" ++ [undefined]
        y = True
</code></pre>

<p>that fails if <code>p (""foo"" ++ [undefined])</code> tries to consume any more than <code>""foo""</code>.</p>

<p>This works fine for my <code>String</code> implementation,</p>

<pre><code>import qualified Data.List as L

p :: String -&gt; Bool
p = (""foo"" `L.isPrefixOf`)
</code></pre>

<p>But it does not work so fine on my <code>Data.Text.Lazy</code> implementation,</p>

<pre><code>{-# LANGUAGE OverloadedStrings #-}
import qualified Data.Text.Lazy as T
import           Data.Text.Lazy (Text)

p :: Text -&gt; Bool
p = (""foo"" `T.isPrefixOf`)
</code></pre>

<p>because <code>fromString</code> does not convert the lazy <code>String</code> into a lazy <code>Text</code> in a way that preserves the <code>undefined</code> unevaluated. I can test that the lazy version does work by writing a specialized test,</p>

<pre><code>pTest :: Bool
pTest = p (T.fromChunks [ ""foo"", undefined ]) -- True
</code></pre>

<p>but I can't control how <code>fromString</code> chunks.</p>

<hr>

<h2>Attempted solution:</h2>

<p>I tried to write my own wrapper to control the chunking of <code>fromString</code>,</p>

<pre><code>import qualified Data.Text      as T
import qualified Data.Text.Lazy as LT

newtype LazyChunkyText = LazyChunkyText LT.Text deriving (Show)
instance IsString LazyChunkyText where
  fromString = LazyChunkyText . LT.fromChunks . map (T.pack . return)
</code></pre>

<p>But because <code>fromChunks</code> takes a <code>[T.Text]</code>, I need to <code>T.pack</code>.</p>

<p>Meaning my <code>[undefined]</code> gets evaluated.</p>
",https://stackoverflow.com/questions/53784627/testing-laziness-of-isstring-s-s-bool-function,"['haskell', 'text', 'lazy-sequences']",92,FALSE,1,0
H2 - duplicate key not throwing exception in Spring boot test when Persistable&lt;ID&gt; isNewObject set to true,"<p>I am using H2 as test DB in a Java Spring Boot application, but when I want to catch a ""duplicate key"" exception when trying to insert an duplicate ID/PK, H2 does not throw anything.</p>

<p>With Postman all is fine and nice, I just cannot pass the test.</p>

<p>The real DB is PostgreSQL, and it does throw exception when I integration test with Postman. But when unit testing I think it is not necessary to load real DB so I chose H2. </p>

<p>H2 config:</p>

<pre><code>spring.datasource.url=jdbc:h2:mem:tesdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;mode=MySQL
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

spring.datasource.testWhileIdle=true
spring.datasource.validationQuery=SELECT 1

spring.jpa.datasource.show-sql=true
spring.h2.console.enabled=true # if you need console
</code></pre>

<p>Bean definition:</p>

<pre><code>@Entity
@Data
@JsonComponent
@Table(name=""bin_info"")
public class BinInfo implements Serializable, Persistable&lt;String&gt;{ //with Persistable we can check ID duplicate
    @Id
    @Size(min=6, max=8)
    @Column(name=""bin"")
    @JsonProperty(""bin"")
    private String bin;

    ...

    /**
     * Property for identifying whether the object is new or old,
     * will insert(new) or update(old)
     * If is new and id/bin is duplicate, org.hibernate.exception.ConstraintViolationException will be thrown.
     * If is old and id/bin is duplicate, just updates. Hibernate save() will upsert and no complain.
     */
    @Transient
    private boolean isNewObject;

    @Override
    public String getId() {
        return this.bin;
    }

    @Override
    public boolean isNew() {
        return isNewObject;
    }
    @Override
    public String getId() {
        return this.bin;
    }

    @Override
    public boolean isNew() {
        return isNewObject;
    }
</code></pre>

<p>The controller <code>insert</code> method:</p>

<pre><code>@RequestMapping(value=""/insert"", method=RequestMethod.POST)
public ResponseEntity&lt;Object&gt; insertBIN(@Valid @RequestBody BinInfo bin_info, HttpServletResponse response) throws JsonProcessingException {
    Map&lt;String, Object&gt; errors = new HashMap&lt;String, Object&gt;();
    try {
        OffsetDateTime now = OffsetDateTime.now();
        bin_info.setCreatedAt(now);
        bin_info.setUpdatedAt(now);
        bin_info.setNewObject(true); //if set to true, bin duplicate -&gt; exception and return 200; then we avoid ""select to check duplicate first""
        BinInfo saved = repository.save(bin_info);
        // if is new, created(201); if not, updated(status OK, 200)
        return ResponseEntity.status(HttpStatus.CREATED)
                .contentType(MediaType.APPLICATION_JSON_UTF8).body(saved);
    } catch (DataIntegrityViolationException e0) {
        log.warn(""Update BIN due to duplicate"", e0); // exception details in log
        //if duplicate, change newObject to false and save again. And return.
        bin_info.setNewObject(false);
        BinInfo saved = repository.save(bin_info);
        return ResponseEntity.ok()          // &lt;&lt;&lt;&lt;&lt;&lt; here I define ""save duplicate=update=200, OK""
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .body(saved);
    } catch (Exception e) {
        log.error(""Cannot save BinInfo. "", e); // exception details in log
        errors.put(""error"", ""Cannot save BIN""); // don't expose to user
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .body(Utilities.jsonBuilder(errors));
    }
</code></pre>

<p>The test:</p>

<pre><code>@Test
public void testBinInfoControllerInsertBIN() throws Exception {
    when(this.repository.save(any(BinInfo.class))).thenReturn(mockBinInfo);
    String content_double_quotes = ""{\""bin\"":\""123456\"", ""
                    + ""\""json_full\"":\"""" + this.json_full + ""\"", ""
                    + ""\""brand\"":\"""" + this.brand + ""\"", ""
                    + ""\""type\"":\"""" + this.type + ""\"", ""
                    + ""\""country\"":\"""" + this.country + ""\"", ""
                    + ""\""issuer\"":\"""" + this.issuer + ""\"", ""
                    + ""\""newObject\"":true, ""
                    + ""\""new\"":true, ""
                    + ""\""createdAt\"":\""18/08/2018 02:00:00 +0200\"", ""
                    + ""\""updatedAt\"":\""18/08/2018 02:00:00 +0200\""}"";
    log.info(""JSON input: "" + content_double_quotes);

    //save the entity for the first time(newObject==true, new=true) and should return 201
    this.mockMvc.perform(post(""/insert"")
            .content(content_double_quotes) //json cannot have single quote; must be double
            .accept(MediaType.APPLICATION_JSON_UTF8_VALUE)
            .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
            )
        .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
        .andExpect(status().isCreated())
        .andDo(print())
        .andExpect(jsonPath(""$.bin"", is(this.bin)))
        .andExpect(jsonPath(""$.json_full"", is(this.json_full)))
        .andExpect(jsonPath(""$.brand"", is(this.brand)))
        .andExpect(jsonPath(""$.type"", is(this.type)))
        .andExpect(jsonPath(""$.country"", is(this.country)))
        .andExpect(jsonPath(""$.issuer"", is(this.issuer)))
        .andExpect(jsonPath(""$.createdAt"", is(""18/08/2018 02:00:00 +0200"")))
        .andExpect(jsonPath(""$.updatedAt"", is(""18/08/2018 02:00:00 +0200"")));

    //save the same entity, new == true, and should return 200
    this.mockMvc.perform(post(""/insert"")
            .content(content_double_quotes) //json cannot have single quote; must be double
            .accept(MediaType.APPLICATION_JSON_UTF8_VALUE)
            .contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
        .andDo(print())
        .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
        .andExpect(status().isOk());   //&lt;&lt;&lt;&lt;&lt; here I always get 201, not 200. With Postman I get 200 instead.
}
</code></pre>

<p>Note that <code>mockBinInfo</code> has <code>isNewObject</code> always set to <code>true</code>, meaning that it should throw exception when finding duplicate PK in the second insertion, but it is not happening. This is required by <code>Persistable&lt;ID&gt;</code> interface, which will tell DB whether or not to persist when ID is duplicate or not. </p>

<ul>
<li>if <code>isNew()</code> returns <code>true</code>, will throw exception when ID is duplicate</li>
<li>otherwise, will update silently</li>
</ul>

<p>See <a href=""https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.repositories"" rel=""nofollow noreferrer"">here</a> for more information(searching ""Persistable"").</p>

<p>EDIT:</p>

<p>I also noticed that H2 seems not to support Spring <code>Persistable&lt;ID&gt;</code> and always return <code>new=false</code> in the saved entity. </p>

<p>Log details:</p>

<pre><code>MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /insert
       Parameters = {}
          Headers = {Content-Type=[application/json;charset=UTF-8], Accept=[application/json;charset=UTF-8]}
             Body = {""bin"":""123456"", ""json_full"":""{'brand':'visa', 'type':'credit', 'country':'USA', 'issuer':'BigBank'}"", ""brand"":""visa"", ""type"":""credit"", ""country"":""USA"", ""issuer"":""BigBank"", ""newObject"":""true"", ""new"":""true"", ""createdAt"":""18/08/2018 02:00:00 +0200"", ""updatedAt"":""18/08/2018 02:00:00 +0200""}
    Session Attrs = {}

Handler:
             Type = com.xxxxx.binlookup.controller.BinInfoController
           Method = public org.springframework.http.ResponseEntity&lt;java.lang.Object&gt; com.xxxxx.binlookup.controller.BinInfoController.insertBIN(com.xxxxx.binlookup.model.BinInfo,javax.servlet.http.HttpServletResponse) throws com.fasterxml.jackson.core.JsonProcessingException

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 201
    Error message = null
          Headers = {Content-Type=[application/json;charset=UTF-8]}
     Content type = application/json;charset=UTF-8
             Body = {""id"":""123456"",""newObject"":false,""new"":false,""bin"":""123456"",""json_full"":""{'brand':'visa', 'type':'credit', 'country':'USA', 'issuer':'BigBank'}"",""brand"":""visa"",""type"":""credit"",""country"":""USA"",""issuer"":""BigBank"",""createdAt"":""18/08/2018 02:00:00 +0200"",""updatedAt"":""18/08/2018 02:00:00 +0200""}
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
</code></pre>
",https://stackoverflow.com/questions/51818627/h2-duplicate-key-not-throwing-exception-in-spring-boot-test-when-persistablei,"['java', 'spring', 'spring-boot', 'h2']",1160,FALSE,1,2
Unit Test for content of PyQt.QTableView,"<p>My GUI (PyQt5, Python3.6) displays data from an SQLite database, mostly using QTableViews.</p>

<p>I'm unit-testing the application using defined input files, and I want to check whether everything is shown in the GUI at the right place. Now, all the data is in the model attached to the QTableView, not the QTableView itself. And I sometimes use <code>QTableView.hideRow()</code> to hide some of the columns which are present in the raw data but not desired to be shown in this particular view.</p>

<p><strong>How can I test that everything is displayed in the expected place <em>in the QTableView</em>?</strong></p>

<p>Here's a mini example class I'd like to write unit tests for:</p>

<pre><code>#!/usr/bin/python3
# -*- coding: utf-8 -*-

from PyQt5 import QtSql
from PyQt5.QtWidgets import (QWidget, QTableView, QApplication, QHBoxLayout)
import sys

class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(400, 150)

        self.createConnection()
        self.fillTable()
        self.createModel()
        self.initUI()

    def createConnection(self):
        self.db = QtSql.QSqlDatabase.addDatabase(""QSQLITE"")
        self.db.setDatabaseName(""test.db"")
        if not self.db.open():
            print(""Cannot establish a database connection"")
            return False

    def fillTable(self):
        self.db.transaction()
        q = QtSql.QSqlQuery()

        q.exec_(""DROP TABLE IF EXISTS Cars;"")
        q.exec_(""CREATE TABLE Cars (Company TEXT, Model TEXT, Year NUMBER);"")
        q.exec_(""INSERT INTO Cars VALUES ('Honda', 'Civic', 2009);"")
        q.exec_(""INSERT INTO Cars VALUES ('VW', 'Golf', 2013);"")
        q.exec_(""INSERT INTO Cars VALUES ('VW', 'Polo', 1999);"")

        self.db.commit()

    def createModel(self):
        self.model = QtSql.QSqlTableModel()
        self.model.setTable(""Cars"")
        self.model.select()

    def initUI(self):
        layout = QHBoxLayout()
        self.setLayout(layout)

        view = QTableView()
        layout.addWidget(view)

        view.setModel(self.model)
        view.hideRow(1)

    def closeEvent(self, e):
        if (self.db.open()):
            self.db.close()


def main():
    app = QApplication(sys.argv)
    ex = Example()
    ex.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
</code></pre>

<p>I can test the data in the model, of course:</p>

<pre><code>self.assertEqual(model.headerData(0, Qt.Horizontal, Qt.DisplayRole), ""Company"")
self.assertEqual(model.data(model.index(0, 0), Qt.DisplayRole), ""Honda"")
</code></pre>

<p>etc.</p>

<p>But the <em>model</em> contains 3 rows, whereas my QTableView only has 2 (as the VW Golf row is hidden).</p>

<p><strong>So, is there a way to test the data as shown in the QTableView rather than the data in the model?</strong> (In the example class, I want tests to assert that the view only contains 2 rows, and that the Polo row is the second.)</p>
",https://stackoverflow.com/questions/51842371/unit-test-for-content-of-pyqt-qtableview,"['python', 'unit-testing', 'pyqt', 'pyqt5', 'qtableview']",404,TRUE,1,1
"When class is instantiated by Unit Test, System.IO exception is triggered for image in instantiated class","<p>I have a windows form application that is working without errors (compilation creates .exe in bin\debug along with a folder called 'Images'.  This 'Images' folder is in my project solution folder and is set to ""always copy"".  </p>

<p>When the code is compiled, all is well and there are no System.IO exceptions.  </p>

<p>However, if that class that refers to the images is instantiated without compiling and through a unit test harness, I see the following:</p>

<p>System.Drawing.Image.FromFile(String filename, Boolean useEmbeddedColorManagement)
   at System.Drawing.Image.FromFile(String filename)
   at YahtzeeApplication.GameBoard..ctor() in E:\workspaces\visual studio projects\Yahtzee\YahtzeeApplication\YahtzeeApplication\GameBoard.cs:line 124
   at UnitTestProject.GameBoardTest.GameBoardElements() in E:\workspaces\visual studio projects\Yahtzee\YahtzeeApplication\UnitTestProject\GameBoardTest.cs:line 37
Result Message: System.IO.FileNotFoundException : Images\1.dice.GIF</p>

<p>Here is the code that loads the image:</p>

<pre><code>diceImageArray[0] = Image.FromFile(""Images\\1.dice.GIF"");
</code></pre>

<p>I was seeing if the test class or the instantiated class was not seeing the images. but when I put a folder called 'Images' in either location relative to call the error didn't go away.  </p>

<p>What do you do for this scenario in Unit testing?</p>
",https://stackoverflow.com/questions/53798404/when-class-is-instantiated-by-unit-test-system-io-exception-is-triggered-for-im,"['c#', 'visual-studio', 'unit-testing', 'nunit']",183,TRUE,0,1
Why doesn&#39;t Akka.Net warn if the user tries to go to an undefined state in a FSM?,"<p>I'm now learning Akka.Net and trying to write a simple FSM actor. Yesterday I spent the whole day trying to solve the following mystery. Here's a simplified version of my code so far:</p>

<pre><code>public MyFSMActor()
{
    StartWith(State.A, MyData.Empty);

    When(State.A, e =&gt; condition0 ? GoTo(State.B) : Stay());
    When(State.B, e =&gt; condition1 ? condition2 ? Goto(State.C) : GoTo(State.D) : Stay());
    When(State.C, e =&gt; NotImplementedException());
}
</code></pre>

<p>I was unit testing my class and checking that the FSM behave according to the specifications, except when I tried to check the case in which the FSM should go to <code>State.D</code>. The test always failed because the FSM was staying in <code>State.B</code>. It took me quite a while to understand that I had not specified that the FSM had a <code>State.D</code> by writing the corresponding</p>

<pre><code>When(State.D, e =&gt; Whatever());
</code></pre>

<p>But that really puzzled me, because I would have expected the implementation of the Akka.Net FSM to warn me somehow (by throwing an exception or whatever) that I was trying to go to an undefined state. Instead, the FSM just stayed in the current state and I could not understand why.</p>

<p>So my question is: shouldn't Akka.Net warn if the user tries to go to an undefined state in a FSM? Why doesn't do that?</p>
",https://stackoverflow.com/questions/52384026/why-doesnt-akka-net-warn-if-the-user-tries-to-go-to-an-undefined-state-in-a-fsm,"['c#', 'akka', 'akka.net', 'fsm']",110,TRUE,0,2
How to stop NUnit TestRunner?,"<p>I am unit testing a C# solution using <strong>NUnit</strong> Version 3.9.0.0 (Runtime Version v4.0.30319, tried different versions up to 3.10.0.1) from within VS 2017 Enterprise, TestDriven.Net V 4.1-Alpha, OS Windows 10 Pro.
The project's assemblies target .Net 4.0.</p>

<p>In most cases it works fine, but sometimes the behavior of <strong>NUnit</strong> becomes unpredictable, so that the system is no longer to work with. What actually happens is, I am starting a very simple unit test, and it gets through. Then I am starting the same test again, and the system gets stuck. You cannot stop the testing thread, as in the image below (the red rocket icon does not react on right mouse click):</p>

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

<p>I was also unable to find the relevant process in the process manager to manually kill it. 
The NUnit items in the context menu remain gray and there is no way to stop/restart the test from within it, see below:</p>

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

<p>The only possibility is to restart VS completely, then you can carry out exactly one test, and everything starts again. What can be possibly wrong?</p>
",https://stackoverflow.com/questions/49597012/how-to-stop-nunit-testrunner,"['visual-studio-2017', 'nunit', 'testdriven.net']",1094,TRUE,0,1
Testing generated crystal report with Coded UI,"<p>One of my test cases requires me to test a Crystal Report generated by the application. I am using Coded UI. The UIMap recorder detects the whole page in the report as an UITextItem, but the text in the report is in some child controls (I can click on them, but the recorder does not detect them).</p>

<p>The asnwers to this question <a href=""https://stackoverflow.com/questions/555805/unit-testing-a-report"">Unit testing a report</a> explain that I can only export the data into another file, and test against that. The answers are from 2009. I was hoping that maybe soemthing has improved in the meantime. </p>

<p>Is there a way to test the valeus in a generated Crystal Reports report using Coded UI, besides exporting it to another file and testing against that file?</p>

<p><strong>EDIT per AdrianHHH's comment:</strong></p>

<p>When moving the arrows, it appears to iterate through the controls in the report. It shows something like: SectionX -> UIFieldTextX (where X is a number, of order I think). All the elements have the field <em>DisplayText</em> empty.</p>

<p>All elements have the <em>ControlType</em> set to <em>Text</em>.</p>
",https://stackoverflow.com/questions/53225492/testing-generated-crystal-report-with-coded-ui,"['crystal-reports', 'coded-ui-tests']",410,FALSE,0,1
Enforce concurrent modification of a variable (C++),"<p>I'm trying to unit test an atomic library (I am aware that an atomic library is not suitable for unit testing, but I still want to give it a try) </p>

<p>For this, I want to let X parallel threads increment a counter and evaluate the resulting value (it should be X).</p>

<p>The code is below. The problem is that is it never breaks. The <code>Counter</code> always nicely ends up being 2000 (see below). What I also notice is that the <code>cout</code> is also printed as a whole (instead of being mingled, what I remember seeing with other multithreaded <code>couts</code>)</p>

<p>My question is: why doesn't this break? Or how can I let this break?</p>

<pre><code>#include &lt;iostream&gt;
#include &lt;thread&gt;
#include &lt;vector&gt;
#include &lt;mutex&gt;
#include &lt;condition_variable&gt;

std::mutex m;
std::condition_variable cv;
bool start = false;

int Counter = 0;

void Inc() {

    // Wait until test says start
    std::unique_lock&lt;std::mutex&gt; lk(m);
    cv.wait(lk, [] {return start; });

    std::cout &lt;&lt; ""Incrementing in thread "" &lt;&lt; std::this_thread::get_id() &lt;&lt; std::endl;
    Counter++;
}

int main()
{
    std::vector&lt;std::thread&gt; threads;

    for (int i = 0; i &lt; 2000; ++i) {
        threads.push_back(std::thread(Inc));
    }

    // signal the threads to start
    {
        std::lock_guard&lt;std::mutex&gt; lk(m);
        start = true;
    }
    cv.notify_all();

    for (auto&amp; thread : threads) {
        thread.join();
    }

    // Now check whether value is right
    std::cout &lt;&lt; ""Counter: "" &lt;&lt; Counter &lt;&lt; std::endl;
}
</code></pre>

<p>The results looks like this (but then 2000 lines)</p>

<pre><code>Incrementing in thread 130960
Incrementing in thread 130948
Incrementing in thread 130944
Incrementing in thread 130932
Incrementing in thread 130928
Incrementing in thread 130916
Incrementing in thread 130912
Incrementing in thread 130900
Incrementing in thread 130896
Counter: 2000
</code></pre>

<p>Any help would be appreciated</p>

<p>UPDATE: Reducing the nr of threads to 4, but incrementing a million times in a for loop (as suggested by @tkausl) the <code>cout</code> of thread id appear to be sequential..</p>

<p>UPDATE2: Turns out that the lock had to be unlocked to prevent exclusive access per thread (<code>lk.unlock()</code>). An additional <code>yield</code> in the for-loop increased the race condition effect.</p>
",https://stackoverflow.com/questions/53414039/enforce-concurrent-modification-of-a-variable-c,"['c++', 'multithreading', 'atomic', 'googletest']",65,TRUE,0,1
How to unit test using a shim and a static factory method?,"<p>I have a class (with a protected constructor) that contains multiple static factory methods. I use these to make clear what parameters refer to. For example:</p>

<pre><code>MyClass.FromFile(string filename);
MyClass.FromString(string filename);
MyClass.FromParameterSet(...);
</code></pre>

<p>I use these to give the different construction methods a name/meaning (I know there will be people telling me not to do this but please let's just discuss it this way, for the sake of the argument). </p>

<p>However, I am running into trouble when unit testing <code>MyClass</code>. I want to check if <code>MyClass</code> properly initializes its internal values because it does complex stuff. Of course it does not expose them. Usually a shim would solve the problem but with the static factory method I cannot create an instance in the very same way I will be in me ""real code"" because it will create an instance of <code>MyClass</code> and not <code>MyShimmedClass</code>.</p>

<p>The obvious answer is to not use static factory methods. I could do that but I am wondering if there is a way to <em>fix this</em>.</p>

<p>(I am using C# in case anyone is wondering.)</p>
",https://stackoverflow.com/questions/52559062/how-to-unit-test-using-a-shim-and-a-static-factory-method,"['c#', 'unit-testing', 'shim', 'factory-method']",245,FALSE,0,0
Mocking object instantiation with new in Java using PowerMock not working,"<p>I am trying to Unit Test a class in Java.</p>

<p>Code for this class: <code>ToBeTested</code></p>

<pre><code>public class ToBeTested {
    private Collaborator collaborator;

    public ToBeTested() {
        System.out.println(""ToBeTested: Constructor"");
    }

    public void start() {
        System.out.println(""ToBeTested: Start"");
        collaborator = new Collaborator();
    }
}
</code></pre>

<p>This class <code>ToBeTested</code> depends on another class, <code>Collaborator</code>.</p>

<p>Code for class: <code>Collaborator</code></p>

<pre><code>public class Collaborator {

    Collaborator() {
        System.out.println(""Collaborator: Constructor"");
    }
}
</code></pre>

<p>While testing the class <code>ToBeTested</code>, I want to stub instantiation of <code>Collaborator</code>. That's a dependency I want to mock and I don't want it's constructor to be called.</p>

<p>I'm using Junit (v4.12) and PowerMock (v1.6.1).</p>

<p>Code for Test Class: <code>TestToBeTested</code></p>

<pre><code>import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.annotation.Mock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.powermock.api.easymock.PowerMock.*;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ToBeTested.class, Collaborator.class})
public class TestToBeTested {

    @Mock
    private Collaborator collaborator;

    private ToBeTested toBeTested;

    @Before
    public void setUp() throws Exception {
        collaborator = createMock(Collaborator.class);
        expectNew(collaborator.getClass()).andReturn(null);
        toBeTested = new ToBeTested();
    }

    @Test
    public void test() {
        replayAll();

        toBeTested.start();

        verifyAll();
    }

}
</code></pre>

<p>My understanding is that this will mock or stub out Collaborator and it's constructor should not be called. However, when I run the test, I notice that original constructor of Collaborator is called. </p>

<p>Output of test run:</p>

<pre><code>ToBeTested: Constructor
ToBeTested: Start
Collaborator: Constructor
</code></pre>

<p><em>I'm very new to Java and Unit Testing in Java, so I apologize if I'm doing a very fundamental mistake here.</em> </p>

<p>During my quest to find out the root cause, I have referred to following SO questions:</p>

<ul>
<li><a href=""https://stackoverflow.com/questions/12360555/powermocks-expectnew-isnt-mocking-a-constructor-as-expected"">PowerMock&#39;s expectNew() isn&#39;t mocking a constructor as expected</a></li>
<li><a href=""https://stackoverflow.com/questions/18480796/powermock-expectnew-how-to-specify-the-type-of-the-parameters"">PowerMock expectNew how to specify the type of the parameters</a></li>
<li><a href=""https://stackoverflow.com/questions/29818830/not-able-to-mock-constructor-using-powermock"">Not able to mock constructor using PowerMock</a></li>
<li><a href=""https://dzone.com/articles/using-powermock-mock"" rel=""nofollow noreferrer"">https://dzone.com/articles/using-powermock-mock</a></li>
</ul>

<p>Thank you very much in advance for help/suggestions/feedback.</p>
",https://stackoverflow.com/questions/49291136/mocking-object-instantiation-with-new-in-java-using-powermock-not-working,"['java', 'unit-testing', 'junit', 'powermock']",769,FALSE,0,1
Using Redux with vanilla JS how can I reach it without passing it to every component?,"<p>I'm using Redux in a vanilla JS project. I have a bunch of small modular UI files and controllers and such. In those UI files I might have code like:</p>

<pre><code>const ExampleForm = function (StoreInstance) {
  return $('&lt;form /&gt;', {
    submit: () =&gt; {
      StoreInstance.dispatch({
        type: 'EXAMPLE_DISPATCH',
        post: {
          message: $TextareaComponent.val()
        }
      })
      return false
    }
  })
}
</code></pre>

<p>The issue is I have a lot of simple view files like this and many of them are nested and I'm finding it to be ugly and error prone to have the store passed as a param to everything.</p>

<p>For example, I trimmed it for brevity but the form component has form element components such as a textarea. Currently I see two options of managing the Store:</p>

<ol>
<li><p>Setting it to <code>window</code> when creating it in my entry file (index.js) and then just accessing <code>Store</code> globally. This seems the nicest, although not ""best practice"" and makes unit testing and server side rendering a bit harder.</p></li>
<li><p>Passing it to <em>every</em> component tediously. This is my example above. This I'd consider as ""best practice"" but it's pretty annoying to do for every file you make almost. </p></li>
</ol>

<p>I'm wondering if there's any alternatives or tricks to passing the store instance. I'm leaning towards just making it global.</p>
",https://stackoverflow.com/questions/51237226/using-redux-with-vanilla-js-how-can-i-reach-it-without-passing-it-to-every-compo,"['javascript', 'redux']",287,TRUE,0,1
Python: Call a method with a given list of arguments,"<p>I am unit-testing my software with PyUnit and find it unfortunate that the assertions provided by mock objects (e.g. <em>mock.assert_called_with</em>) don't seem to provide a way to set a message in case the assertion fails. That's why I want to use a wrapper like this:</p>

<pre><code>def wrap_mock_msg(mock_method, *args, msg):
try:
    mock_method(&lt;args here!&gt;)
except AssertionError as e:
    raise AssertionError(e.args, msg)
</code></pre>

<p>It takes the assertion method of a given mock object as <em>mock_method</em>, the message to be displayed upon failure as <em>msg</em>, and a series of arguments to be passed to the <em>mock_method</em> as <em>args</em>.
I need it to be a variable <em>args</em> list, since <em>mock.assert_called_with(arg1, arg2, .., arg_n)</em> can also take any number of arguments, depending on the method I'm trying to mock. </p>

<p>Unfortunately, I can't just pass a list of arguments to the <em>mock_method</em>, since it will of course be taken as a single argument. Now, this leads me to the challenge of having to pass the list of arguments to the <em>mock_method</em> as if I had hard-typed it. For example:</p>

<pre><code>args = ['an', 'example']
</code></pre>

<p>..should result in the following call:</p>

<pre><code>mock_method('an', 'example')
</code></pre>

<p>Is there any way to achieve this?</p>
",https://stackoverflow.com/questions/51792853/python-call-a-method-with-a-given-list-of-arguments,"['python', 'function-call']",107,TRUE,0,2
PHPUnit Testing Json Always Responds With 404,"<p>I'm trying to test a few things within Laravel unit testing with my API. I want to be able to test things such as if users are able to succsufully be created, logged in, deleted, etc.. The problem I am facing is that no matter what Json I send to my API, I always get this message from PHPUnit:</p>

<blockquote>
  <p>Expected status code xxx but received 404</p>
  
  <p>Failed asserting that false is true</p>
</blockquote>

<p>I have been recieveing a 404 error with everythingI try to post it seems like. But what is really no making sense at this point is that even this returns a 404 error: </p>

<pre><code>/** @test */
public function 404ErrorMessageCheck()
{
  $response = $this-&gt;get('/api/user');

  $response-&gt;assertStatus(200);
}
</code></pre>

<p>I wrote the above code to check if it even wants to load at all and apparently it doesn't. I was thinking something may be wrong with my auth headers or something but from my understanding, a 404 message means that it isn't even loading. </p>

<p>Here is one of the things that I was origianlly trying to test:</p>

<pre><code>  /** @test */
  function results_get_created_correctly()
  {

    $user = factory(User::class)-&gt;create();
    $token = $user-&gt;generateToken();

    $response = $this-&gt;withHeaders([
          'Authorization' =&gt; 'Bearer' . $token
        ])-&gt;json('POST', '/api/results', [
        'FirstName' =&gt; FirstName,
        'LastName' =&gt; LastName,
        'City' =&gt; 'Houston',
        'State' =&gt; 'Texas',
    ]);

    $response
      -&gt;assertStatus(201)
      -&gt;assertJson([
        'FirstName' =&gt; FirstName,
        'LastName' =&gt; LastName,
        'City' =&gt; 'Houston',
        'State' =&gt; 'Texas',
      ]);

    }
</code></pre>

<p>Same error with the above code though.</p>
",https://stackoverflow.com/questions/51389974/phpunit-testing-json-always-responds-with-404,"['json', 'laravel', 'phpunit', 'http-status-code-404']",238,FALSE,0,0
Unit of Work with Repository having Generic methods,"<p>We are using EF with DB first, and we are not planning to create Repository classes per table. Instead, we will have repository classes representing modules, which internally might interact with multiple tables.</p>

<p>The code which I have started writing is something like this:</p>

<pre><code>public class ModuleRepository
{
    public void GetModules()
    {
        using (IUnitOfWork uow = new UnitOfWork())
        {
            //Get the specific DBSet
            var dbTable = uow.GetDbSet&lt;Customer&gt;();
            var dbTable1 = uow.GetDbSet&lt;Supplier&gt;();
            //do whatever you want to do.

            //call save changes to commit
            uow.SaveChanges();
        }
    }
}


class UnitOfWork: IUnitOfWork
{
    private DbContext _context;

    public UnitOfWork()
    {
        _context = new DbContext("""");
    }

    public void Dispose()
    {
        throw new NotImplementedException();
    }

    public void SaveChanges()
    {
        throw new NotImplementedException();
    }

    public DbSet&lt;T&gt; GetDbSet&lt;T&gt;() where T:class
    {
        DbSet&lt;T&gt; entities = _context.Set&lt;T&gt;();
        return entities;
    }
}


public interface IUnitOfWork: IDisposable
{
    void SaveChanges();
    DbSet&lt;T&gt; GetDbSet&lt;T&gt;() where T : class;
}
</code></pre>

<p>In SaveChanges I will have the <code>_context.SaveChanges()</code> to commit the changes to the DB.</p>

<p>This is I guess one way to do this. </p>

<p>Another possible way could be:</p>

<ol>
<li>create a generic base repository class. Each module repository will have a list of these repository classes.</li>
<li>uow class</li>
<li>UOW Manager -> will pass list of base repositories to say a method Setup. This UOW Manager will create a UOW with a context, and this UOW will be passed to each repository - effectively all repository having the same context.</li>
</ol>

<p>I think code wise it will work, though not sure which one is the right approach or there could be some better approach.</p>

<p>Also in any of these two scenarios, how to achieve unit testing? Any ideas around this?</p>
",https://stackoverflow.com/questions/50282930/unit-of-work-with-repository-having-generic-methods,"['asp.net', 'entity-framework-6']",47,FALSE,0,0
Java scalable frameworks usage on Google App Engine,"<p>We are using Google App Engine for back-end development. <strong>We're considering the scalability, change of server and data movement to another cloud platform in future, as well the robustness in application</strong>. Please suggest the frameworks that can be used in Google App Engine (Java based).</p>

<ol>
<li>End point exposure/Rest web services</li>
<li>ORM/database connection</li>
<li>Service and db layer integration</li>
<li>Logging</li>
<li>Unit testing</li>
<li>etc</li>
</ol>

<p>Please add any points that I may have missed.</p>

<p><strong>Update</strong>: The reason behind asking this question is that when we start development we will get a hell lot of samples, for example:</p>

<ol>
<li><p>Rest web services - we have Spring Boot/Spring rest web services</p></li>
<li><p>DB - we have JDO, Google Datastore, etc.</p></li>
<li><p>For easy access we can use Spring Core.</p></li>
</ol>

<p>If we browse through information on Google App Engine Java development, we're unable to find a list of advantages/disadvantages. It's correct that we have many options. While answering please also consider the bolded words. The question definitely looks simple from an angle, but it's a serious issue for the fresh development. </p>
",https://stackoverflow.com/questions/49503179/java-scalable-frameworks-usage-on-google-app-engine,"['java', 'google-app-engine', 'google-cloud-platform']",373,FALSE,-1,1
cant find sequelize n:m relation tables,"<p>Im working with typescript and sequelize, and I have the following tables: <strong>Prophet</strong>, <strong>Model</strong> and <strong>Task</strong>, and they all have an n:m relation with each other, so sequelize automatically creates 3 other tables: <strong>modelProphets</strong>, <strong>modelTasks</strong> and <strong>prophetTasks</strong>.
Ive got a simple repository for each one of them, and models and tasks have an extra function in the repo:</p>

<pre><code>public findWithoutProphet(): Promise&lt;any&gt; {
    const query = `SELECT models.name FROM models WHERE NOT EXISTS
        (SELECT modelProphets.modelName FROM modelProphets WHERE models.name = modelProphets.modelName);`;
    return this.database.rawQuery(query);
}
</code></pre>

<p>im unit testing every repository function, but the thing is, when I run using the sequelize dialect 'sqlite', everything works fine, but if I change it to my local docker postgres and run it again, an error is thrown during that query, saying 'modelProphets' doesnt exist (or prophetTasks if I run the task one first instead of model). All other repo functions like creating, deleting, updating, finding, everything works fine. I even checked the DB using pgAdmin4 and all the relation tables are there, so...</p>

<p>why sequelize gives me this error with postgresql, when sqlite runs fine? Are the automatic relation tables different for each DB? Should I have a different repository for each DB Im testing?</p>
",https://stackoverflow.com/questions/52766868/cant-find-sequelize-nm-relation-tables,"['javascript', 'postgresql', 'typescript', 'sqlite', 'sequelize.js']",249,TRUE,0,1
Proper way of using and testing generated mapper,"<p>Recently we encountered some conflict during the development of our system. We discovered, that we have 3 different approaches to testing in our team, and we need to decide which one is best and check if there is nothing better than this.</p>

<p>First, let's face some facts:<br>
 - we have 3 data layers in the system (DTOs, domain objects, tables)<br>
 - we are using mappers generated with mapstruct to map objects of each layer to another<br>
 - we are using mockito<br>
 - we are unit-testing each of our layers<br></p>

<p>Now the conflict: Let's assume that we want to test <code>ExampleService</code> which is using <code>ExampleModelMapper</code> to map <code>ExampleModel</code> to <code>ExampleModelDto</code> and doing some additional business logic which needs testing. We can verify the correctness of returned data in three different ways:</p>

<p>a) We can manually compare each field of a returned object to an expected result:<br></p>

<pre><code>assertThat(returnedDto)
                .isNotNull()
                .hasFieldOrPropertyWithValue(""id"", expectedEntity.getId())
                .hasFieldOrPropertyWithValue(""address"", expectedEntity.getAddress())
                .hasFieldOrPropertyWithValue(""orderId"", expectedEntity.getOrderId())
                .hasFieldOrPropertyWithValue(""creationTimestamp"", expectedEntity.getCreationTimestamp())
                .hasFieldOrPropertyWithValue(""price"", expectedEntity.getPrice())
                .hasFieldOrPropertyWithValue(""successCallbackUrl"", expectedEntity.getSuccessCallbackUrl())
                .hasFieldOrPropertyWithValue(""failureCallbackUrl"", expectedEntity.getFailureCallbackUrl())
</code></pre>

<p>b) We can use real mapper (same as in normal logic) to compare two objects:<br></p>

<pre><code>assertThat(returnedDto).isEqualToComparingFieldByFieldRecursivly(mapper.mapToDto(expectedEntity)))
</code></pre>

<p>c) And finally, we can mock mapper and its response:</p>

<pre><code>final Entity entity = randomEntity();
final Dto dto = new Dto(entity.getId(), entity.getName(), entity.getOtherField());
when(mapper.mapToDto(entity)).thenReturn(dto);
</code></pre>

<p>We want to make tests as good as possible while keeping them elastic and change-resistant. We also want to keep to DRY principle.</p>

<p>We are happy to hear any pieces of advice, comments, pros, and cons of each method. We are also open to see any other solutions.</p>

<p>Greetings.</p>
",https://stackoverflow.com/questions/52255896/proper-way-of-using-and-testing-generated-mapper,"['java', 'unit-testing', 'mocking', 'mapping', 'mapstruct']",31629,TRUE,15,2
How to improve the performance of a Django application across different geographic regions?,"<p>I have a Django application that is hosted on an AWS box located in the <a href=""https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Concepts.RegionsAndAvailabilityZones.html"" rel=""nofollow noreferrer"">us-east-1</a> geographic region using Nginx and django-channels. Recently, I have had some users in the <a href=""https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Concepts.RegionsAndAvailabilityZones.html"" rel=""nofollow noreferrer"">ap-southeast-1</a> region complain that my app is not very responsive. The app runs fine for me as I am using us-east-1.</p>

<ol>
<li>How can I detect poor performance in a region is happening before a user complains? </li>
<li>What can I do to improve the app performance and user experience in the ap-southeast-1 timezone? </li>
<li>Is there any way to test the performance in another geographic region as part of unit-testing or something similar? </li>
</ol>

<p>I have a feeling the answer for #2 will have something to do with: (A) Adding another web server in ap-southeast-1 and (B) caching, but I'm keen to hear if there are additional things I should be doing. </p>

<p>However, I have no clue how to detect slow performance for other regions is happening in the first place or to test to ensure it does not happen again in the future.</p>
",https://stackoverflow.com/questions/51101660/how-to-improve-the-performance-of-a-django-application-across-different-geograph,"['django', 'amazon-web-services', 'webserver']",174,TRUE,0,1
How to call one object file from another using c,"<p>I've been writing some simple console application in c and on linux and came across a problem. I need to run one object file from another.  </p>

<p>When i want to open a text or binary file i would do something like this:</p>

<pre><code>FILE* fp = fopen(path, mode);
</code></pre>

<p>and then just write to that file or read from it. But when it comes to object files i don't even know what to start with.  </p>

<p>Globally, the situation is that there is a compiled object file which functionality needs to be tested (lets call it ""target""). The test is driven by another compiled object file (let's call it ""tester""). So, when i run the ""tester"" it queries for path to ""target"". When path is acquired, ""tester"" tests ""target"".  </p>

<p>So, what i ask here is what this whole situation (coding of object files interaction) is called so i could go and rtfm? I lurked a bit and found some concepts like unit testing and APIs but brief view didn't give me strong impression that those things are what i'm looking for.  </p>

<p>Thank you!</p>
",https://stackoverflow.com/questions/48477693/how-to-call-one-object-file-from-another-using-c,['c'],44,FALSE,0,0
Spring MockMvc not taking roles into account,"<p>I have API endpoints which require a user to hold a specific role. Therefore, in some of my tests I attempt to reach these endpoints and expect a 401 error, however I get 200. I am using MockMvc to perform the calls. </p>

<p>The following are some snippets of the controller class with one of the methods that I am testing: </p>

<pre><code>@RestController
public class MyController {


    @GetMapping(""/getcurrentuser"")
    public User getCurrent() {
         ...code
    }

}
</code></pre>

<p>The following is my test class (only showing the respective test method and variables):</p>

<pre><code>@RunWith(SpringRunner.class)
@WebMvcTest(MyController.class)
@ContextConfiguration(classes = MyController.class)
public class MyControllerTest {

    @Autowired
    private MockMvc mockMvc;
@Test
    public void testGetCurrentFailedDueToIncorrectRole() throws Exception {
        mockMvc.perform(get(""/api/getcurrentuser"")
                        .with(user(USER_NAME).password(PASSWORD)))
               .andExpect(status().isUnauthorized());
    }
}
</code></pre>

<p>I have also have a spring security config class, however I'm not sure if it's being brought into context in this test (sorry I'm still fairly new to spring and unit testing). Inside this class I have the following line of code: </p>

<pre><code>.antMatchers(""/api/**"").hasAnyRole(""ADMIN"", ""READ_ONLY"")
</code></pre>

<p>The test showed previously fails, as I said I get 200. Now at this point I think that I'm doing something wrong in the configuration of this test and that is why roles are not being accounted for. Or maybe I am confused on how the "".with"" part works. </p>

<p>Any form of help would be appreciated.</p>
",https://stackoverflow.com/questions/51327293/spring-mockmvc-not-taking-roles-into-account,"['spring', 'testing', 'spring-security', 'authorization', 'mockmvc']",512,FALSE,0,1
Visual Studio 2017 + .Net Core 2 Tests not executable,"<p>I'm trying to set up some unit tests for a private project. Since I don't mind the exact runner, I tried NUnit, XUnit and MStest, but none worked so far.</p>

<p>After some research, I cloned the official Microsoft repository here :<a href=""https://github.com/dotnet/docs/blob/master/samples/core/getting-started/unit-testing-using-nunit/PrimeService.Tests/PrimeService_IsPrimeShould.cs"" rel=""noreferrer"">https://github.com/dotnet/docs/blob/master/samples/core/getting-started/unit-testing-using-nunit/PrimeService.Tests/PrimeService_IsPrimeShould.cs</a> 
But these tests can't be executed as well. When doing so, I get the following error in the output:</p>

<blockquote>
  <p>System.ArgumentException: Illegal characters in path.    at
  System.IO.Path.CheckInvalidPathChars(String path, Boolean
  checkAdditional)    at System.IO.Path.Combine(String path1, String
  path2)    at
  Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Helpers.DotnetHostHelper.TryGetExecutablePath(String
  executableBaseName, String&amp; executablePath)    at
  Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Helpers.DotnetHostHelper.GetDotnetPath()
  at
  Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Hosting.DotnetTestHostManager.GetTestHostProcessStartInfo(IEnumerable<code>1
  sources, IDictionary</code>2 environmentVariables, TestRunnerConnectionInfo
  connectionInfo)    at
  Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Client.ProxyOperationManager.SetupChannel(IEnumerable`1
  sources, CancellationToken cancellationToken)    at
  Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Client.ProxyDiscoveryManager.DiscoverTests(DiscoveryCriteria
  discoveryCriteria, ITestDiscoveryEventsHandler2 eventHandler)</p>
</blockquote>

<p>I also checked out several SO answers like <a href=""https://stackoverflow.com/questions/42861930/unit-tests-not-discovered-in-visual-studio-2017"">Unit Tests not discovered in Visual Studio 2017</a> or <a href=""https://stackoverflow.com/questions/43007761/how-to-run-nunit-tests-in-visual-studio-2017"">How to run NUnit tests in Visual Studio 2017?</a>, but none of them fixed the problem.</p>

<p>My Visual Studio 2017 Version is currently 15.6.0 and I'm also using ReSharper. It seems like this is a local environmental problem, unfortunately, I didn't find any hints regarding that problem. Has anyone a idea, how that problem could be solved?</p>
",https://stackoverflow.com/questions/49337947/visual-studio-2017-net-core-2-tests-not-executable,"['c#', 'visual-studio', 'visual-studio-2017']",1372,TRUE,7,4
Is grouping multiple @Service and @Repository classes into wrappers an anti-pattern?,"<p>Question is a bit rhetorical. I've had an argument with my colleagues regarding the following pattern:</p>

<pre><code>@Component
public class MetaService {

    public static UserService userService;
    public static GroupService groupService;   
    public static PermissionService permissionService;            
    // ...more fields

    @Autowired
    public MetaService(UserService userService,
                       GroupService groupService
                       PermissionService permissionService) {

        MetaService.userService = userService;
        MetaService.groupService = groupService;
        MetaService.permissionService = permissionService;           
    }
}
</code></pre>

<p>Basically, <code>MetaService</code> is an entry point/wrapper for multiple Spring beans <code>@Service</code> classes. And there's one more similar <code>MetaDao</code> wrapper for <code>@Repository</code> beans class:</p>

<pre><code>@Component
public class MetaDao {

    public static UserDao userDao;
    public static GroupDao groupDao;
    public static PermissionDao permissionDao;
    // ...more fields   

    @Autowired
    public MetaDao(UserDao userDao,
                   GroupDao groupDao,
                   PermissionDao permissionDao) {

        MetaDao.userDao = userDao;
        MetaDao.groupDao = groupDao;
        MetaDao.permissionDao = permissionDao;
    }
}
</code></pre>

<p>The idea of having such a Meta-class is to reduce code base within <code>@RestController</code> and <code>@Service</code> classes, by providing concise API to call <code>@Service</code> and <code>@Repository</code> methods, for example:</p>

<pre><code>@RestController
public class UserController {

    @PostMapping
    public UserCreateResponse createUser(UserCreateRequest request) {
        MetaService.userService.createAndReturn(userEntity);
        // other service calls
    }
}
</code></pre>

<p>In other words, this is an alternative to having <code>@Autowired</code> fields/constructors for each <code>@Service</code> within each <code>@Controller</code> etc. In my opinion this approach greatly reduces boilerplate repetitive code a lot.</p>

<p>Well, my colleagues are saying that: such an approach makes the code harder to understand/maintain since combining <code>@Service</code> components in one place hides dependency model of other components which use them. In other words, if there were fields declared for <code>UserController</code> class. It would've been easier to quickly find out which components <code>UserController</code> depends upon. In addition, it's harder to mock such dependencies doing unit testing. And the most important
that such approach is <strong>super-anti-pattern</strong>. Whereas I can agree with mocking part, everything else seems ridiculous to me.</p>

<p>Question is, is this truly an anti-pattern in any way?</p>
",https://stackoverflow.com/questions/50699781/is-grouping-multiple-service-and-repository-classes-into-wrappers-an-anti-patt,"['java', 'spring', 'design-patterns', 'dependency-injection', 'anti-patterns']",576,TRUE,7,3
integration tests for react redux redux-saga,"<p>I have a project structure like this: </p>

<pre><code>app/
  global/
    styles/
    components/
  scenes/
    Home/
      actions.js
      constants.js
      index.jsx
      reducer.js
      sagas.js
      styles.styl
      index.spec.jsx
    some-other-scene/
      actions.js
      constants.js
      index.jsx
      reducer.js
      sagas.js
      styles.styl
      index.spec.jsx
</code></pre>

<p>so I have no problem with unit test with this structure, but I'm pretty confused as to how to structure integration test. For my unit tests I am exporting each scene component as a class </p>

<pre><code>export class SomeComponent extends Component {}
</code></pre>

<p>and as a redux connected component</p>

<pre><code>export default connect(
  mapStateToProps,
  mapDispatchToProps
)(SomeComponent)
</code></pre>

<p>So for the fist style of export (the class) I am unit testing it, but for the second way (the connected component way) I am unsure how to approach this specifically how to do integration testing in react/redux. I've searched the internet about this, but nothing that is close to this structure.</p>

<p>So:</p>

<ol>
<li>is integration testing in react/redux/middleware (in this case redux saga) how one component integrates with redux and middleware.</li>
<li>Or is it about how the whole app works with all the components mounted?</li>
<li>if it's #1 does that mean each component should have a single integration test file that tests how the component integrates with redux and middleware or if it's #2 then is it one test file that tests all components as one app?</li>
</ol>

<p>also, if it's #1 then how should I test routes via react router?</p>
",https://stackoverflow.com/questions/51295853/integration-tests-for-react-redux-redux-saga,"['reactjs', 'redux', 'react-redux', 'integration-testing', 'redux-saga']",1025,TRUE,7,3
Azure Functions Application Insights Context,"<p>We've a bunch of azure functions log metrics against the execution context... you don't seem to be able to do this using the OOTB <code>TraceWriter</code>, or <code>ILogger</code> (at least in what i have seen) as there isn't an equivalent to what i assume would be named <code>log.LogEvent()</code>..</p>

<p>So.. this url (<a href=""https://learn.microsoft.com/en-us/azure/azure-functions/functions-monitoring#custom-telemetry-in-c-functions"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/azure/azure-functions/functions-monitoring#custom-telemetry-in-c-functions</a>) shows a pattern for leveraging a <code>TelemetryClient()</code> inside of Azure Function to do the same, with examples for rolling your own for <code>EventTelemetry()</code> etc, however to ensure the correlation works you have to set the context for each thing you log:</p>

<pre><code>var evt = new EventTelemetry(""Function called"");
evt.Context.Operation.Id = executionContext.InvocationId.ToString();
telemetryClient.TrackEvent(evt);
</code></pre>

<p>This all seems fairly logical, except i have a shared class (<code>TelemetryManager</code>) that helps creation of <code>TelemetryClient()</code> - so we don't have to repeat code in every, single, function that just news up a client with a series of additional settings.. this also implements a logging interface <code>ITelemetry</code> so that we have an interface later to unit test against, and lets you do.. (here using trace for simplicity):</p>

<pre><code>static CustomTelemetryManager logger = new CustomTelemetryManager();
logger.Trace($""thing i want to trace: {x.value}"");
</code></pre>

<p><code>logger.Trace()</code> method simply does is call the <code>telemetryClient.TrackTrace()</code> method in the <code>CustomTelemetryManager()</code> class - some other methods are more complex.</p>

<p>Anyway, the interface is there so that when unit testing we can just do:</p>

<pre><code> // gets all the app insights key, and sets various other properties.        
static DebugLogger logger = new DebugLogger();
logger.Trace($""thing i want to trace: {x.value}"");
</code></pre>

<p>and it will just <code>Debug.WriteLine()</code> instead of attempting to call out to AI</p>

<p><strong>Question 1</strong>: Is there a ""better"" way to swap out Application Insights code for unit tests, as this is the only reason that we have this <code>ITelemetry</code> interface at all... to facilitate a dummy logger for unit tests.</p>

<p>Ultimately though, what i need to do, is give the <code>telemetryClient.TrackTrace()</code> the context of the invocation that is being executed, and the only way i have found to do that right now is, similar to the track event code above..</p>

<pre><code>var trace = new TraceTelemetry($""i am a trace."");
trace.Context.Operation.Id = context.InvocationId.ToString();
logger.Trace(trace);
</code></pre>

<p>Because the <code>TelemetryClient</code> is shared over all functions, i need to apply the context to the metric directly before sending it to log..</p>

<p><strong>Question 2</strong>: Is the only way i can do this.. something like:</p>

<pre><code>public void TrackTrace(string msg, ExecutionContext ctx)
{
    var trace = new TraceTelemetry(msg);
    trace.Context.Operation.Id = ctx.InvocationId.ToString();
    client.TrackTrace(trace);
}
</code></pre>

<p>As this will mean modifying the interface, and then also mean for unit testing i shall also need to supply some sort of dummy context to the debug logger, which feels a bit clunky..</p>

<p>Somewhere in here, i think there is a simple tweak to simplify this needlessly confusing problem.. but i can't quite see the wood for the trees!</p>
",https://stackoverflow.com/questions/50819905/azure-functions-application-insights-context,"['azure-functions', 'azure-application-insights']",1008,TRUE,0,1
action-cable-testing with Devise,"<p>My Ruby on Rails application is working as desired. Things are getting broadcast and received as I want. However, I want to add unit testing to channels using <code>action-cable-testing</code> gem. My user registration is done using <code>Devise</code>. 
Here is my <code>connection.rb</code> file: </p>

<pre><code>module ApplicationCable
  class Connection &lt; ActionCable::Connection::Base
    identified_by :current_user

    def connect
      self.current_user = find_verified_user
    end

    private
    def find_verified_user
      if verified_user = env['warden'].user
        verified_user
      else
        reject_unauthorized_connection
      end
    end
  end
end
</code></pre>

<p>I have a <code>message_notifications_channel.rb</code> like this: </p>

<pre><code>class MessageNotificationsChannel &lt; ApplicationCable::Channel
  def subscribed
    # stream_from ""some_channel""
    if current_user&amp;.account_id
      stream_from ""message_notifications_channel_#{current_user.account_id}""
    end
  end

  def unsubscribed
    # Any cleanup needed when channel is unsubscribed
  end
end
</code></pre>

<p>This channel allows a user, when signed in, to stream from <code>message_notifications_channel_accountID</code> where accountID is id of the account to which the user belongs. </p>

<p>My <code>cable.js</code> file is the same as shown in the ruby guide: </p>

<pre><code>// Action Cable provides the framework to deal with WebSockets in Rails.
// You can generate new channels where WebSocket features live using the `rails generate channel` command.
//
//= require action_cable
//= require_self
//= require_tree ./channels

(function() {
  this.App || (this.App = {});

  App.cable = ActionCable.createConsumer();

}).call(this);
</code></pre>

<p>I'm having trouble with the following rspec test: </p>

<pre><code>require 'rails_helper'

RSpec.describe MessageNotificationsChannel, type: :channel do
  let(:authorized_senders) {['11111']}
  let(:common_user_phone){'17777777777'}
  let(:account) {FactoryGirl.create(:account, authorized_senders: authorized_senders)}
  let(:user){FactoryGirl.create(:user, account: account, admin: true)}
  context 'when user is authenticated' do
    describe '#connect' do
      it 'accepts connection' do
        sign_in user
        subscribe(account_id: user.account_id)
      end
    end
  end
end
</code></pre>

<p>The error I got is: 
Failure/Error: if current_user&amp;.account_id</p>

<pre><code> NameError:
   undefined local variable or method `current_user' for #&lt;MessageNotificationsChannel:0x000000000721d890&gt;
</code></pre>

<p>The location of the error is in my <code>message_notifications_channel.rb</code> file. I put a <code>byebug</code> before <code>self.current_user = find_verified_user</code> in the <code>connect</code> method in <code>connection.rb</code>, the test would not hit that byebug at all. And no surprise, I would get that error later. </p>

<p>When I'm running in development environment that byebug will get hit and things will run normally. </p>

<p>This is my <code>cable.yml</code>:</p>

<pre><code>redis: &amp;redis
  adapter: redis
  url: redis://localhost:6379/1

production: *redis
development: *redis
test:
 *redis
</code></pre>

<p>I've looked at <a href=""https://github.com/palkan/action-cable-testing/issues/26#issuecomment-392481619"" rel=""nofollow noreferrer"">https://github.com/palkan/action-cable-testing/issues/26#issuecomment-392481619</a> 
That person's code does not really use Devise. It's crucial that all parts of my app uses devise for user authentication.
Thanks! </p>
",https://stackoverflow.com/questions/52561373/action-cable-testing-with-devise,"['ruby-on-rails', 'rspec', 'devise', 'channel', 'actioncable']",829,TRUE,4,1
Doesn&#39;t Dependency Injection simply move the issue elsewhere?,"<p>So Dependency Injection is recommended usually to help with unit testing, to solve the problem of having a class dependent on other classes. This sounds great, but let me walk through the issue I'm facing.</p>

<p>Here is a regular implementation without DI:</p>

<pre><code>class Upper{
    Middle middle = new Middle();
}

class Middle{
    Lower lower = new Lower();
}

class Lower{
}
</code></pre>

<p>Now let's start at the bottom. Middle depends on Lower, we don't really want that, so we'll create a redundant interface for Lower and pass that to the constructor of Middle instead:</p>

<pre><code>class Middle{
    Lower lower;
    public Middle(ILower lower){
        this.lower = lower;
    }
}

interface ILower{
}

class Lower : ILower{
}
</code></pre>

<p>Well this sounds great, right? Well not really. Most examples I've seen stop here, forgetting that something needs to use the class Middle. Now we have to update Upper to be compatible:</p>

<pre><code>class Upper{
    Middle middle = new Middle(new Lower());
}
</code></pre>

<p>This doesn't seem very useful... All that we've done is moved the problem up a level, and created an unusual dependency: Upper depends on Lower now? That's definitely not an improvement.</p>

<p>I must be missing the benefit, but it seems like DI just moved the issue rather than solved it. In fact, it also makes the code harder to understand.</p>

<p>Also, here is a ""full"" implementation:</p>

<pre><code>interface IUpper {
}

class Upper : IUpper {
    Middle middle;
    public Upper(IMiddle middle){
        this.middle = middle;
    }
}

interface IMiddle {
}

class Middle : IMiddle {
    Lower lower;
    public Middle(ILower lower){
        this.lower = lower;
    }
}

interface ILower {
}

class Lower : ILower {
}
</code></pre>

<p>But again, I'm just moving the problem. To use Upper, I need:</p>

<pre><code>new Upper(new Middle(new Lower()));
</code></pre>

<p>and now I depend on 3 classes!</p>
",https://stackoverflow.com/questions/48981858/doesnt-dependency-injection-simply-move-the-issue-elsewhere,"['c#', 'dependency-injection']",240,TRUE,3,2
How do I prevent Pester Mocked Read-Host from prompting for input during Code Coverage,"<p>I have a Pester test where I mock up a Read-Host call for my function, which follows the format in this question here:</p>

<p><a href=""https://stackoverflow.com/questions/41284810/how-do-i-mock-read-host-in-a-pester-test"">How do I mock Read-Host in a Pester test?</a></p>

<pre><code>Describe ""Test-Foo"" {
    Context ""When something"" {
    Mock Read-Host {return ""c:\example""}

        $result = Test-Foo

        It ""Returns correct result"" { # should work
            $result | Should Be ""c:\example""
        }
         It ""Returns correct result"" { # should not work
            $result | Should Be ""SomeThingWrong""
        }
    }
}
</code></pre>

<p>My tests run perfectly when using this format, and calling the test directly. However, when I run the file that contains my test using Invoke-Pester ""MyTestFile"" -CodeCoverage ""MyFileUnderTest"", I am being prompted to enter a Read-Host value for my test.</p>

<p>My intent is that the test will run automatically without having to enter a Read-Host value. This would be both when calling the test directly (which works currently), and when calling my test file with the CodeCoverage command.</p>

<p>Does anyone know of a way to achieve this?</p>

<p>Edit:</p>

<p>To the first comment I received, I have reviewed Pester's documentation, including this link <a href=""https://github.com/pester/Pester/wiki/Unit-Testing-within-Modules"" rel=""nofollow noreferrer"">https://github.com/pester/Pester/wiki/Unit-Testing-within-Modules</a>. I haven't seen any official documentation from Pester regarding using Read-Host however, and used the solution I found in the StackOverflow link at the top of my question.</p>

<p>Source Code for Module Test-Foo function:</p>

<pre><code>function Test-Foo
{
    return (Read-Host ""Enter value-&gt;"");
}
</code></pre>
",https://stackoverflow.com/questions/50297499/how-do-i-prevent-pester-mocked-read-host-from-prompting-for-input-during-code-co,"['unit-testing', 'powershell', 'mocking', 'code-coverage', 'pester']",365,TRUE,3,1
QUnit stubbing out methods on a dependency breaks tests against that dependency,"<p>In Google Apps Script, I'm unit-testing an app that I'm working on, <a href=""https://github.com/simula-innovation/qunit/tree/gas/gas"" rel=""nofollow noreferrer"">using QUnit</a>, using test-driven-development.</p>

<p><strong>The code under test</strong></p>

<p>I am, right now, working on fully testing, and then developing, the following function:</p>

<pre><code>/**
 * 
 *  Creates a Sheet from a long string of data
 *  @param { string } data : the long string of data
 *  @returns { Sheet } the newly-created Sheet
 **/
function createSheetFrom(data) { 
  // if data is not in the form of a string, we've got a problem
  if (data !== data.toString())
    throw TypeError(""Data must be in the form of a string"")
  // parse the data into SheetData
  sheetData = SheetData.parse(data);
  // create a new Sheet
  newSheet = SPREADSHEET.insertSheet(sheetData.projectName)
  // create title rows for it
  createTitleRow(sheet)

  return newSheet
}
</code></pre>

<p>where <code>SPREADSHEET</code> is the <code>Spreadsheet</code> the script is attached to, saved as a global variable for convenience. </p>

<p>That function depends on, among a few others, the one right below it, which has been successfully fully tested and developed: </p>

<pre><code>/** 
 *  Creates a title row for the spreadsheet
 *  
 *  @param { Sheet } sheet : the spreadsheet to create a title row for
 *  @returns { Sheet } the sheet for chaining purposes
 **/
function createTitleRow(sheet) { 
  // declare the titles
  var titles = [""File"", ""Total Cyclomatic Complexity"", ""Already unit-tested?"", ""Status Date""];
  // insert a row right at the beginning
  sheet.insertRows(1);
  var titleRow = sheet.getRange(1, 1, 1, titles.length);
  // set some values on titleRow
  titleRow.setValues(titles);
  titleRow.setHorizontalAlignment(CENTER)
  return sheet;
}
</code></pre>

<p><strong>The tests:</strong></p>

<p>My test against createSheetFrom is thus: </p>

<pre><code>function testCreateSheetFrom() { 
  var globalSpreadsheet // for storing the state of SPREADSHEET
  var sheet // a stub Sheet

  var createTitleRowCalls = []
  var titleRowFunction


  QUnit.test(""testing createSheetFrom with 'file contents' that is simply one line of output"",
             function() { 
               throws(function() { 
                 val = createSheetFrom(""3 blah funcName c:/blah/foo/bar"");
               }, ""Exception caught successfully"")  
             })


}
</code></pre>

<p>...and the one against createTitleRow is thus:</p>

<pre><code>function testCreateTitleRow() { 
  var sheet // spy for the Sheet object from the Google Spreadsheet API


  QUnit.testStart(function() { 
    // create a sheet spy
    sheet = {
      insertRowsCalls : [],
      insertRows : function(idx) { 
        Logger.log(""insertRows called"")
        this.insertRowsCalls.push({ args : idx });
      },
      getRangeCalls : [],
      range : {
        setValuesCalls : [],
        setValues : function(arr) { 
          if (!Array.isArray(arr)) return;
          // simply record the args that this was called with
          this.setValuesCalls.push({ args : arr });
        },
        setHorizontalAlignment: function(setting) {} 
      },
      // method stub
      getRange : function(r0,c0,r1,c1) { 
        Logger.log('getRange called')
        this.getRangeCalls.push({ args : Array.prototype.splice.call(arguments, 0) });
        return this.range;
      }
    };

  })

  QUnit.test(""testing createTitleRow"",
             function() { 

               // hit the method under test
               val = createTitleRow(sheet);
               // the methods better have been hit
               equal(sheet.insertRowsCalls.length, 1, ""sheet.insertRows only got invoked once"")
               ok(sheet.getRangeCalls, ""sheet.getRange() got invoked at least once"")
               ok(sheet.getRangeCalls.length)
               deepEqual(sheet.getRangeCalls[0].args.filter(function(val, key) { return key &lt; 3 }), [1,1,1], ""the right arguments got sent to sheet.getRange()"")
               setValuesCalls = sheet.range.setValuesCalls
               ok(setValuesCalls.length, ""A call was made to sheet.range.setValues"")
               equal(setValuesCalls[0].args.length, 4, ""The call was made with four args, as we expect"")
               // sheet better have been returned
               equal(val, sheet, ""createTitleRow() returns the sheet for testing, as promised"")
             })

}
</code></pre>

<p>The tests all pass:</p>

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

<p>However, when I add to the tests against <code>createSheetFrom</code> the following sanity test, stubbing out <code>createTitleRow</code> in the setup, reverting it back to its real self in the teardown, both the tests against <code>createSheetFrom</code> and <code>createTitleRow</code> break!</p>

<p>The code for that breaking test:</p>

<pre><code>QUnit.testStart(function() { 
        // create a spy out of sheet


    sheet = {

    }
    // replace SPREADSHEET with a spy
    globalSpreadsheet = SPREADSHEET
    SPREADSHEET = {
      insertSheetCalls : [],
      insertSheet : function(str) { 
        this.insertSheetCalls.push({ args: str })
        return sheet
      }

    }
    // stub out the dependencies
    titleRowFunction = createTitleRow
    createTitleRow = function(sheet) { 
      createTitleRowCalls.push({ args : sheet })
      return sheet
    }

  })

  QUnit.test(""SanityTesting createSheetFrom"", 
             function() { 
               projectName = ""main""

               complexity = 3
               packageName = ""main""
               funcName = ""SetContext""
               filename = ""main.go""

               fileContents = createFileContents(projectName,
                                                 createLineOfTextFrom(complexity, packageName, funcName, ""C:/Users/mwarren/Desktop/"" + filename))

               sheet = createSheetFrom(fileContents)
               ok(SPREADSHEET.insertSheetCalls.length, ""SPREADSHEET.insertSheet got called"")
             })

  QUnit.testDone(function() { 
    // set SPREADSHEET back
    SPREADSHEET = globalSpreadsheet
    // set the dependencies back 
    createTitleRow = titleRowFunction
  })
</code></pre>

<p>Screenshots of the test regressions:</p>

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

<p>I don't know why these regressions are happening, especially since I set back the changes I made in setup...</p>

<p><strong>The states of the objects used are carrying over to other test cases in other test functions, despite me using <code>testDone</code> to set the states of the objects back. This is now happening in other test cases, too</strong></p>
",https://stackoverflow.com/questions/52561975/qunit-stubbing-out-methods-on-a-dependency-breaks-tests-against-that-dependency,"['javascript', 'unit-testing', 'google-apps-script', 'tdd', 'qunit']",90,FALSE,3,0
Create Moq for Epplus Excel file,"<p>My first question here. I have looked my query but could not find a helpful answer. </p>

<p>My task is to write unit test case for my excel file. The issue I am facing is that we using Epplus for excel files and I am not sure how can we write unit test cases for this. I looked up and found that we can also use MOQ to mock up. But again I could not find any helpful links for mocking an excel file that uses Epplus. I found this link <a href=""https://stackoverflow.com/questions/24703971/unit-testing-classes-that-use-epplus"">Unit testing classes that use EPPlus</a> but I am not sure how I can implement this .</p>

<p>I would appreciate if someone can provide a sample of how to write a simple unit test for the excel file. The test can be to check if file uploaded is an excel file or not, checking if the excel is empty or not etc.</p>

<p>Sorry at this moment I dont have any sample. What I can share is the code where I am reading the excel file:</p>

<pre><code>public class MyController : Controller
{
  [HttpPost(""upload"")]
  public async Task&lt;IActionResult&gt; UploadFile(IFormFile file)
  {
   JArray data = new JArray();
    using (ExcelPackage package = new ExcelPackage(file.OpenReadStream()))
    {
      ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
      //Check if excel is empty.
      if (worksheet.Dimension == null)
      {
         return BadRequest(""File is blank."");
      }
     data = Helper.CreateJson(worksheet);
                }
     return Ok(data);
  }
}
</code></pre>

<p>I had created a helper class as:</p>

<pre><code>public static JArray CreateJson(ExcelWorksheet worksheet)
{
  JArray data = new JArray();
  JObject jobject = new JObject();

  int rowCount = worksheet.Dimension.End.Row;
  int colCount = worksheet.Dimension.End.Column;

    for (int row = 1; row &lt;= rowCount; row++)
    {
       for (int col = 1; col &lt;= colCount; col++)
        {
          var value = worksheet.Cells[row, col].Value;
          //Excel has 2 columns and I want to create a json from that.
          if (col == 1)              
          {
             jObject.Add(""ID"", rowValue.ToString());
          }
          else
          {
             jObject.Add(""Name"", rowValue.ToString());
          }
        }
         data.Add(jObject);
         jObject= new JObject();
     }
   return data;
}
</code></pre>

<p>This is the Test Class i have so far.</p>

<pre><code>public class TestClass
{
    private MyController _controller;
    public TestClass()
    {
      _controller = new MyController (); 
    }

      [Fact]
    public void Upload_WhenCalled()
    {
        //var file = new FileInfo(@""C:\myfile.xlsx"");
        //...what next?

        var file = new Mock&lt;IFormFile&gt;();
        var content = File.OpenRead(@""C:\myfile.xlsx"");

        var result = _controller.UploadFile(file.Object);
        //When I debug it throws error ""Object reference not set to an instance of an object.""
    }
}
</code></pre>
",https://stackoverflow.com/questions/53618704/create-moq-for-epplus-excel-file,"['c#', 'asp.net-core', 'moq', 'epplus']",3179,TRUE,3,2
BigDecimal : HALF_UP rounding with setScale,"<p>We have the following code:</p>

<pre><code>BigDecimal net = price
.divide(taxCumulative, RoundingMode.HALF_UP)
.setScale(2, BigDecimal.ROUND_UP); 
</code></pre>

<p>We are unit testing this and getting different results depending on if we use <code>@Transactional</code> on the test classes or not.</p>

<p>I just want to know if we should expect the application of the <code>HALF_UP</code> to be considered along with the <code>setScale</code> or before it.</p>

<p>In example: </p>

<p>Say that : </p>

<p><strong>price = 4.00</strong></p>

<p><strong>taxCumulative = 1.20</strong></p>

<p>Would you expect the calculation to be like : </p>

<p>a) <code>4.00 / 1.20 = 3.33333333... --&gt; HALF_UP --&gt; 3 --&gt; setScale --&gt; 3</code></p>

<p>or </p>

<p>b) <code>4.00 / 1.20 = 3.33333333... --&gt; HALF_UP with setScale 2 --&gt; 3.33</code></p>

<p>Like I said, we have unit tests against this code that behaves differently when we have the <code>@Transactional</code> or not. So we could not conclude. In real world, the result is <em>b</em>. But <em>a</em> also makes sense.</p>

<p>Any thoughts?</p>

<p><strong>UPDATE</strong>: </p>

<p>Following @Mark's suggestions, I ve created a test outside the spring context. (but i guess there is no way to share it online like codepen). </p>

<pre><code>package com.company;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class Main {

    public static void main(String[] args) {
        BigDecimal price = new BigDecimal(""4.00"");
        BigDecimal taxCumulative = new BigDecimal(""1.20"");
        BigDecimal net = price.divide(taxCumulative, RoundingMode.HALF_UP).setScale(2, BigDecimal.ROUND_UP);
        System.out.println(""With String constructor, the net =  "" + net.toString());
        // prints 3.33
        price = new BigDecimal(4.00);
        taxCumulative = new BigDecimal(1.20);
        net = price.divide(taxCumulative, RoundingMode.HALF_UP).setScale(2, BigDecimal.ROUND_UP);
        System.out.println(""With doubles, the net =  "" + net.toString());
        // prints 3.00
    }
}
</code></pre>

<p>So, as pointed out by @gtgaxiola the String constructor makes the difference. </p>

<p>And as for the question for the use of setScale for the divide operation. I have done some more tests :</p>

<pre><code>price = new BigDecimal(""4.000000"");
taxCumulative = new BigDecimal(""1.2000000"");
net = price.divide(taxCumulative, RoundingMode.HALF_UP).setScale(2, BigDecimal.ROUND_UP);
// 3.34

price = new BigDecimal(""4.000000"");
taxCumulative = new BigDecimal(""1.2000000"");
net = price.divide(taxCumulative, RoundingMode.HALF_UP);
// 3.333333

price = new BigDecimal(""4"");
taxCumulative = new BigDecimal(""1.2"");
net = price.divide(taxCumulative, RoundingMode.HALF_UP);
// 3
</code></pre>

<p>So the result highly depends on the precision of the string input and the setScale is applied <em>after</em> the divide yields its result.</p>
",https://stackoverflow.com/questions/51618140/bigdecimal-half-up-rounding-with-setscale,"['java', 'bigdecimal']",1635,TRUE,3,1
Testing a library that changes DOM directly,"<p>I wrote a tiny library that manipulates DOM directly, using <code>window</code> and <code>document</code> to search and change the DOM. And now I'm trying to figure out how to test it.</p>

<p>So far I have tried a combination of <a href=""https://github.com/facebook/jest"" rel=""nofollow noreferrer"">jest</a> + <a href=""https://github.com/jsdom/jsdom"" rel=""nofollow noreferrer"">jsdom</a>:</p>

<pre><code>const jsdom = require('jsdom');
const {JSDOM} = jsdom;

const dom = new JSDOM('&lt;!DOCTYPE html&gt;&lt;p&gt;Hello world&lt;/p&gt;');

// these two lines do not seem to do anything useful:
global.window = dom.window;
global.document = dom.window.document;

test('can globally access and search the DOM', () =&gt; {
    // this doesn't work
    expect(global.document.querySelectorAll('p').length).toBe(1);
});
</code></pre>

<p>Am I doing something wrong here, or am I entirely wrong with the testing approach? And if so, what would be the right way to approach such testing?</p>

<p>I feel a bit lost here, between what's called e2e testing and Unit testing, because in my case this seems to be something right in between.</p>

<p>Ideally, I would want to end up with this thing tested against multiple browsers, and to get some sort of test coverage. But that's more like the next step. Right now I cannot get it to work at all.</p>

<p>I know how fast things are moving in the Web world, so if I'm wrong completely, I appreciate if you can point me at what's the right way to do it today.</p>

<hr>

<p><strong>UPDATE</strong></p>

<p>Here's my complete code, after a few suggestions from @duxfox, since with this approach my library is now missing event <code>DOMContentLoaded</code> which is supposed to trigger its DOM processing.</p>

<pre><code>const jsdom = require('jsdom');
const {JSDOM} = jsdom;

const { document } = (new JSDOM('&lt;!DOCTYPE html&gt;&lt;p&gt;Hello world&lt;/p&gt;')).window;
global.document = document;

global.window = document.defaultView;
window.console = global.console;

Object.keys(document.defaultView).forEach((property) =&gt; {
    if (typeof global[property] === 'undefined') {
        global[property] = document.defaultView[property];
    }
});

global.navigator = {
    userAgent: 'node.js'
};

// Here I'm trying to follow a suggestion from Luis:
// https://stackoverflow.com/questions/36803733/jsdom-dispatchevent-addeventlistener-doesnt-seem-to-work
window.addEventListener('DOMContentLoaded', function (ev) {
    console.log('DOMContentLoaded called!'); // this is not called.
    /*
    console.log('window click', ev.target.constructor.name,
        ev.currentTarget.constructor.name);*/
});

// loading my library here:
// const root = require('../src');

test('something', () =&gt; {

    // This now works, but my library is missing
    // event DOMContentLoaded to start processing the DOM

    expect(document.querySelectorAll('p').length).toBe(1);
});
</code></pre>
",https://stackoverflow.com/questions/51540912/testing-a-library-that-changes-dom-directly,"['javascript', 'testing', 'jestjs', 'ui-testing', 'jsdom']",1081,TRUE,2,1
unittest blacklist namespace and fail any attempt to reference it,"<p>in the case of unit testing a wrapper library, testing the wrapper without depending/exercising the upstream library is a goal; In a known case, all calls to the upstream library can be mocked and that's what I've done, but I've been frustrated by changes to the wrapper that introduce more calls to the upstream library being missed by the mock tools;</p>

<p>How can I best fail any test that tries to use a given namespace?</p>

<p>My idea currently is to change all the unittest methods to have a monkey patch like</p>

<pre><code>@unittest.mock.patch('wrapper_namespace.upsteam_namespace')
</code></pre>

<p>and reply the upstream library with a mock that can be asserted untouched; I'm hoping for an option that works globally, so that I </p>

<ul>
<li>don't have to add a monkeypatch to every test method, though this level of granularity is acceptable; but also don't have to perform the assertion that the mock was never used in the test methods (or make a decorator to do all that either)</li>
<li>prohibits access to the upstream library from any part of the software
(e.g, Wrapper calls B calls Upstream, B's call to upstream might not be caught)</li>
</ul>
",https://stackoverflow.com/questions/52617206/unittest-blacklist-namespace-and-fail-any-attempt-to-reference-it,"['python', 'unit-testing', 'python-unittest', 'isolation']",94,TRUE,2,1
Java - Mocking soap call with SOAPMessage request,"<p>I am trying to mock a soap call which is returning null as response.</p>

<p>I have a java class where I am making a call to fedex web services to get the parsed address validated. Till here everything is fine, but when it comes to unit testing the issue arises. 
In test I am trying to mock the soap call by passing the same request parameters that is getting passed in actual java class but the mock is returning the response as null because of the request what I am passing is not same as what the soap call is expecting in java class.</p>

<p>Java class code (abc.java)-</p>

<pre><code>SOAPMessage payload = getAddressRequestPayload();
SOAPMessage responseMessage = soapConnection.call(payload, settings.addressUrl());
</code></pre>

<p>Test code (junit4)-</p>

<pre><code>SOAPMessage testResponse = getMockResponse();
SOAPMessage testPayload =  abc.getAddressRequestPayload();

when(mockSoapConnection.call(testPayload, settings.addressUrl())).thenReturn(testResponse);
</code></pre>

<p>Also I have tried getting the string xml request payload from java class and appending the new timestamp using fakeclock in test class to match both payloads but it seems to be different.
One way is give generic soapmessage class in when call like -</p>

<pre><code>when(mockSoapConnection.call(any(SOAPMessage.class), anyString())).thenReturn(testResponse)
</code></pre>

<p>Then the test is passing, but that is not the correct way of checking a specific call.So how do I get to know the differnce between the payloads or is there any other way to mock the soap call??</p>

<p>Any help is appreciated.</p>

<p>Saurabh</p>
",https://stackoverflow.com/questions/50396905/java-mocking-soap-call-with-soapmessage-request,"['java', 'unit-testing', 'soap', 'mockito', 'junit4']",4272,TRUE,1,1
Angular forms cannot be tested,"<p>I am a beginner tester in Angular and I am using Jasmine for unit testing.
I have a <a href=""https://angular.io/guide/forms"" rel=""nofollow noreferrer"">template driven form</a> like this:</p>

<pre class=""lang-html prettyprint-override""><code>&lt;form name=""editForm"" role=""form""  novalidate (ngSubmit)=""save()"" #editForm=""ngForm""&gt;

    &lt;div class=""modal-header""&gt;
       .....
    &lt;/div&gt;
    &lt;div class=""modal-body""&gt;

        &lt;div class=""half-block""&gt;
            &lt;div class=""form-group half-item""&gt;
                &lt;label class=""form-control-label"" jhiTranslate=""oncosupApp.paciente.nombre"" for=""field_nombre""&gt;Nombre&lt;/label&gt;
                &lt;input type=""text"" class=""form-control"" name=""nombre"" id=""field_nombre""
                    [(ngModel)]=""paciente.nombre"" required/&gt;
                &lt;div [hidden]=""!(editForm.controls.nombre?.dirty &amp;&amp; editForm.controls.nombre?.invalid)""&gt;
                    &lt;small class=""form-text text-danger""
                       [hidden]=""!editForm.controls.nombre?.errors?.required"" jhiTranslate=""entity.validation.required""&gt;
                       This field is required.
                    &lt;/small&gt;
                &lt;/div&gt;
            &lt;/div&gt;


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

<p>Now I want to unit test it, but the probem is that I do not find any tutorial on how to test template driven forms. According to angular <a href=""https://codecraft.tv/courses/angular/unit-testing/model-driven-forms/"" rel=""nofollow noreferrer"">Testing Model Driven Forms</a> these kind of forms cannot be unit tested: </p>

<blockquote>
  <p>TIP:With template driven forms the state is in the view and unless the component has a reference to the template form with a ViewChild
  decorator there is no way to test the form using a unit test. We would
  have to perform a full E2E test simulating button clicks and typing in
  values into forms.</p>
</blockquote>

<p>I would appreciate if somebody that has had the same problem would share the solution with me, on how to test the validation of this form. Not very detailed but I only want to check if th efields really apear and if the submit button saves the data.</p>

<p>I have this model.ts that has its own imports and this code:</p>

<pre class=""lang-html prettyprint-override""><code>export class Paciente implements BaseEntity {
    constructor(

        public nombre?: string,
        ....
</code></pre>

<p>And one of teh specs where I want to create a new object is here:</p>

<pre class=""lang-html prettyprint-override""><code>  it('Should call create service on save for new entity',
                inject([],
                    fakeAsync(() =&gt; { //assync is used to let all the assync code to finish before continuing
                        // GIVEN
                        const entity = new Paciente('anna');//here is a NOMBRE THAT i WANT TO CHECK IF ITS FIELD APPEARS IN TEH FORM OR NOT
                        spyOn(service, 'create').and.returnValue(Observable.of(new HttpResponse({body: entity})));
                        comp.paciente = entity;
                        // WHEN
                        comp.save();
                        tick(); // simulate async

                        // THEN
                        expect(service.create).toHaveBeenCalledWith(entity);
                        expect(comp.isSaving).toEqual(false);
                        expect(mockEventManager.broadcastSpy).toHaveBeenCalledWith({ name: 'pacienteListModification', content: 'OK'});
                        expect(mockActiveModal.dismissSpy).toHaveBeenCalled();
                    })
                )
            );
</code></pre>
",https://stackoverflow.com/questions/49916701/angular-forms-cannot-be-tested,"['javascript', 'html', 'angular', 'testing']",228,FALSE,1,0
DynamicExpresso.SetFunction not working with method overload,"<p>I'm using <a href=""https://github.com/davideicardi/DynamicExpresso"" rel=""nofollow noreferrer"">Dynamic Expresso</a> for expression evaluation and works like a charm. Actually setting up custom functions, but seems like there is a something wrong with a method overload.</p>

<p>I've actually got two <code>Round</code> methods:</p>

<p>First one with one argument:</p>

<pre><code>public static decimal Round(decimal userNumber)
{
    return Math.Round(userNumber);
}
</code></pre>

<p>Second one with two arguments:</p>

<pre><code>public static decimal Round(decimal userNumber, int decimals)
{
    return Math.Round(userNumber, decimals);
}
</code></pre>

<p>Delegates got declared and <code>Interpreter.SetFunction</code> is called with no errors as well:</p>

<pre><code>Func&lt;decimal, decimal&gt; roundFunction1 = (userNumber) =&gt; Round(userNumber);
Func&lt;decimal, int, decimal&gt; roundFunction2 = (userNumber, decimals) =&gt; Round(userNumber, decimals);

interpreter.SetFunction(""ROUND"", roundFunction1);
interpreter.SetFunction(""ROUND"", roundFunction2);
</code></pre>

<p>Variables are correctly passed and I've checked many times already that the parameter I'm passing is, in fact, a <code>decimal</code>.</p>

<p>The evaluation expression I pass, finally contains the following string, which has nothing wrong since the <code>Interpreter.SetVariable(property.Key, property.Value)</code> is inserting an <code>""ImporteTotal""</code> and a <code>666.66</code>:</p>

<pre><code>ROUND(ImporteTotal)
</code></pre>

<p>So, the exception I get when the evaluation gets done is:</p>

<blockquote>
  <p>Argument list incompatible with delegate expression (at index 0).</p>
</blockquote>

<p>Note that <strong>I'm actually setting lots of functions which uses even <code>DateTime</code>s, <code>int</code>, <code>string</code>s and so on even combined, overloads as well</strong>! All of them work perfectly, but seems that deleting any of those overloads helps it working. In case both of them are ""imported"" on Dynamic Expresso, it complains.</p>

<p>Any ideas?</p>

<p>Many thanks.</p>

<p><strong>UPDATE-EDIT:</strong> </p>

<p>I reviewed the <code>UnitTesting</code> <a href=""https://pastebin.com/pgDbZS7K"" rel=""nofollow noreferrer"">Davide provided through pastebin</a> and seems I got it failing.</p>

<p>This unit testing seems that is failing.</p>

<pre><code>[Test]
public static void TestInterpreter()
{
    var interpreter = new Interpreter();

    Func&lt;decimal, decimal&gt; roundFunction1 = (userNumber) =&gt; Round(userNumber);
    Func&lt;decimal, int, decimal&gt; roundFunction2 = (userNumber, decimals) =&gt; Round(userNumber, decimals);
    Func&lt;string, string, int&gt; charindexFunction1 = (toFind, userString) =&gt; Charindex(toFind, userString);
    Func&lt;string, string, int, int&gt; charindexFunction2 = (toFind, userString, offset) =&gt; Charindex(toFind, userString, offset);

    interpreter.SetFunction(""ROUND"", roundFunction1);
    interpreter.SetFunction(""ROUND"", roundFunction2);
    interpreter.SetFunction(""CHARINDEX"", charindexFunction1);
    interpreter.SetFunction(""CHARINDEX"", charindexFunction2);

    var importe = 666.66M;
    interpreter.SetVariable(""ImporteTotal"", importe);

    var textoAlbaran = ""ALBARAN-01"";
    interpreter.SetVariable(""Albaran"", textoAlbaran);

    Assert.AreEqual(Round(importe), interpreter.Eval(""ROUND(ImporteTotal)""));
    Assert.AreEqual(Round(importe, 1), interpreter.Eval(""ROUND(ImporteTotal, 1)""));
    Assert.AreEqual(Charindex(""BARAN"", textoAlbaran), interpreter.Eval(""CHARINDEX(\""BARAN\"", Albaran""));
    Assert.AreEqual(Charindex(""BARAN"", textoAlbaran, 2), interpreter.Eval(""CHARINDEX(\""BARAN\"", Albaran, 2)""));
}

public static decimal Round(decimal userNumber)
{
    return Math.Round(userNumber);
}

public static decimal Round(decimal userNumber, int decimals)
{
    return Math.Round(userNumber, decimals);
}

public static int Charindex(string toFind, string userString)
{
    return userString.IndexOf(toFind);
}

public static int Charindex(string toFind, string userString, int offset)
{
    return userString.IndexOf(toFind, offset);
}
</code></pre>
",https://stackoverflow.com/questions/50967956/dynamicexpresso-setfunction-not-working-with-method-overload,"['c#', 'expression-evaluation', 'dynamic-expresso']",781,TRUE,1,1
Unit Test Duo Security &quot;Duo Verify&quot;,"<p>We are using the duo_web sdk for nodejs to implement 2FA into our backend. We have an initial login endpoint that makes the sign_request and this portion is working as expected and unit testable. It also returns a token for the user logging in.</p>

<p>The second portion involves the sign_response from duo. When the sign_request goes to the front end, the duo iframe is initialized with that sign_request. The response from this iframe is a sign_response that is then sent to the backend with the authorization token. The sign_response is sent to duo via the duo.verify_response function on the duo_web sdk.</p>

<p>The problem here arises when unit testing. There isn't a mock sdk for DUO for me to work with (as there is with something like the aws sdk) and there isn't a way from the backend to generate a sign_response. I was tempted to use something like nock to mock the http call, but the duo sdk is built on top of websockets.</p>

<p>If anyone has experience with this and can help it would be greatly appreciated. I'll try and clarify anything that's unclear.</p>

<p>For Reference here is the sdk: <a href=""https://www.npmjs.com/package/duo_web"" rel=""nofollow noreferrer"">https://www.npmjs.com/package/duo_web</a></p>
",https://stackoverflow.com/questions/52011393/unit-test-duo-security-duo-verify,['node.js'],109,FALSE,1,0
C# - Connecting to database and inserting data with SQL Server stored procedure,"<p>I'm in the process of trying to teach myself some C# (used to code in C++ in the late 90's if that tells you anything). So anyway, I keep running into a test failure in Visual Studio 2017 when attempting to test one of my classes. </p>

<p>The setup is as follows:</p>

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

<p>And within my ErrorLog.cs file:</p>

<pre><code>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using System.Configuration;

namespace ManagementLibrary {
    public class ErrorLog {
        private int log_id { get; set; }
        private string logException {get; set;}
        private string error { get; set; }
        private string date_time { get; set; }
        private string logObject { get; set; }

        public ErrorLog(string logException, string error, string date_time, string logObject) {
            this.logException = logException;
            this.error = error;
            this.date_time = date_time;
            this.logObject = logObject;
        }

        public int LogError() {
            using (SqlConnection connection = new System.Data.SqlClient.SqlConnection(Helper.CnnVal(""DataConnection""))) {

                SqlCommand command = new SqlCommand(""InsertErrorLog"", connection);
                command.CommandType = CommandType.StoredProcedure;

                SqlParameter p1 = new SqlParameter();
                p1.ParameterName = ""@Exception"";
                p1.SqlDbType = SqlDbType.VarChar;
                p1.Direction = ParameterDirection.Input;
                p1.Value = this.logException;

                SqlParameter p2 = new SqlParameter();
                p2.ParameterName = ""@Error"";
                p2.SqlDbType = SqlDbType.VarChar;
                p2.Direction = ParameterDirection.Input;
                p2.Value = this.error;

                SqlParameter p3 = new SqlParameter();
                p3.ParameterName = ""@DateTime"";
                p3.SqlDbType = SqlDbType.VarChar;
                p3.Direction = ParameterDirection.Input;
                p3.Value = this.date_time;

                SqlParameter p4 = new SqlParameter();
                p4.ParameterName = ""@logObject"";
                p4.SqlDbType = SqlDbType.VarChar;
                p4.Direction = ParameterDirection.Input;
                p4.Value = this.logObject;

                command.Parameters.Add(p1);
                command.Parameters.Add(p2);
                command.Parameters.Add(p3);
                command.Parameters.Add(p4);

                connection.Open();
                var identity = command.ExecuteNonQuery();
                return identity;
            }

        }

    }
}
</code></pre>

<p>Essentially I'm trying to create an audit trail for when an error is encountered it simply adds a record to the database. So not only am I attempting to teach myself some C#, but I'm trying to learn how to do unit testing within Visual Studio. I've followed some of the tutorials on setting up and doing unit tests, but when I do I keep getting the following failure:</p>

<blockquote>
  <p>Message: Test method
  ManagementLibrary.Tests.ErrorLogTests.LogErrorTest threw exception: 
  System.NullReferenceException: Object reference not set to an instance
  of an object.</p>
</blockquote>

<p>And when I ""debug"" the failure it ""goes to"" my Helper.cs file. Now this class simply reads the App.config file and returns the connection string.</p>

<pre><code>namespace ManagementLibrary {
    public static class Helper {
        public static string CnnVal(string name) {
            return ConfigurationManager.ConnectionStrings[name].ConnectionString;
        }
    }
}
</code></pre>

<p>And shows the error: 'Object reference not set to an instance of an object'.</p>

<p>I don't even know what this means.</p>

<p>Thoughts?</p>
",https://stackoverflow.com/questions/52609055/c-connecting-to-database-and-inserting-data-with-sql-server-stored-procedure,"['c#', 'unit-testing', 'database-connection']",483,TRUE,1,1
Can I call a method without using .simulate() - Jest Enzyme,"<p>I'm unit testing for a React flight seat selecting app using Jest/Enzyme. Is there a way I can test a method within my class based component which would run after a button is clicked, but without actually simulating the button click? This is because the button is within a child of a child component and the method is being passed down as a prop.</p>

<p>Albeit a very simple function, I'd still like to test it</p>

<pre><code>inputSeats(chosenSeats) {
    this.setState({
        chosenSeats: chosenSeats
    })
}
</code></pre>

<p>This is in a parent component called FlightSeats, with a child of SeatMaps, and SeatMaps has 2 children of SeatMap (inbound/outbound). </p>

<p>Within each of these SeatMap components there is the 'Reserve Seats' button which when clicked it performs some validation tests, calls another method in SeatMap and eventually calls inputSeats() from within SeatMaps component. I'm struggling to simulate the button click since it is deep within the app.</p>

<p>Ideally, in my unit test, I'd just to like to call it with something like</p>

<pre><code>    FlightSeats.inputSeats(chosenSeats)
</code></pre>

<p>and pass in my mock data as chosenSeats... Or would I have to import the child components and mount them and use .simulate('click') on the button?</p>

<p>My test so far:</p>

<pre><code>let chosenSeats = {
    outbound: [{
        seatNo: ""11A"",
        seatPrice: ""11.11"",

    }, {
        seatNo: ""12A"",
        seatPrice: ""12.12""
    }],
    inbound: [{
        seatNo: ""14A"",
        seatPrice: ""14.14"",

    }, {
        seatNo: ""15A"",
        seatPrice: ""15.15""
    }]
};

let wrapper, buildEmptySeats, clearSeats, comp;

beforeEach(() =&gt; {
            comp = ( &lt; FlightSeats seats = {
                    seatsArr
                }
                party = {
                    partyArr
                }
                flights = {
                    flightArr
                }
                /&gt;);

                wrapper = shallow(comp); component = mount(comp);
            });

        test('should handle inputSeats correctly', () =&gt; {
            // what to call here??  
            expect(component.state().chosenSeats.outbound[1].seatNo).toEqual(""12A"");
            expect(component.state().chosenSeats.outbound[1].seatPrice).toEqual(12.12);

        });
</code></pre>
",https://stackoverflow.com/questions/49235411/can-i-call-a-method-without-using-simulate-jest-enzyme,"['javascript', 'reactjs', 'jestjs', 'enzyme']",3152,TRUE,1,1
How to mock IServiceProvider and still allow CreateInstance of generic types?,"<p>I'm attempting to unit test a bit of code that uses a combination of <code>IServiceProvider</code> and reflection to create an instance of each class that extends an abstract class <code>BaseCommand</code>:</p>

<pre><code>IEnumerable&lt;BaseCommand&gt; commandsInAssembly = typeof(BaseCommand)
    .Assembly.GetTypes()
    .Where(t =&gt; t.IsSubclassOf(typeof(BaseCommand)) &amp;&amp; !t.IsAbstract)
    .Select(t =&gt; (BaseCommand)ActivatorUtilities.CreateInstance(_serviceProvider, t))
    .ToList();
</code></pre>

<p>The tricky part here is that <code>_serviceProvider</code> is injected and need's to be mocked (I think), to allow this bit of code to run successfully and in isolation. Each command needs access to DI to resolve its dependencies. Most commands look similar to:</p>

<pre><code>public SomeCommand(IAppState appState, ILoggerAdapter&lt;SomeCommand&gt; logger) : base(appState)
</code></pre>

<p>I'm able to Mock <code>IServiceProvider</code> well enough to resolve <code>IAppState</code>, but I am having difficulty with <code>ILoggerAdapter&lt;&gt;</code>. Here is my current setup:</p>

<p><em>Unit Test Constructor</em></p>

<pre><code>var serviceProvider = new Mock&lt;IServiceProvider&gt;();

serviceProvider
    .Setup(x =&gt; x.GetService(typeof(IAppState)))
    .Returns(new AppState());

serviceProvider
    .Setup(x =&gt; x.GetService(typeof(ILoggerAdapter&lt;&gt;)))
    .Returns(typeof(LoggerAdapter&lt;&gt;));

var serviceScope = new Mock&lt;IServiceScope&gt;();
serviceScope
    .Setup(x =&gt; x.ServiceProvider)
    .Returns(serviceProvider.Object);

var serviceScopeFactory = new Mock&lt;IServiceScopeFactory&gt;();
serviceScopeFactory
    .Setup(x =&gt; x.CreateScope())
    .Returns(serviceScope.Object);

serviceProvider
    .Setup(x =&gt; x.GetService(typeof(IServiceScopeFactory)))
    .Returns(serviceScopeFactory.Object); var mocker = new AutoMocker();

_commandDispatcher = new CommandDispatcher(serviceProvider.Object, _mockAppState.Object, _mockLogger.Object);
</code></pre>

<p>Which generates the following error:
<strong>System.InvalidOperationException : Unable to resolve service for type 'ILoggerAdapter`1[SomeCommand]' while attempting to activate 'SomeCommand'.</strong></p>

<p>If I try to be more explicit with my setup (which I would like to avoid, it makes the test much more brittle) and use:</p>

<pre><code>serviceProvider
    .Setup(x =&gt; x.GetService(typeof(ILoggerAdapter&lt;SomeCommand&gt;)))
    .Returns(typeof(LoggerAdapter&lt;SomeCommand&gt;));
</code></pre>

<p>But that generates an error as well: <strong>System.ArgumentException : Object of type 'System.RuntimeType' cannot be converted to type 'ILoggerAdapter`1[SomeCommand]'.</strong></p>

<p>I'm reading that either using AutoMocking containers or a Fixture may be more appropriate, but I'm unsure of where to start. I'm fairly new to unit testing in C#.</p>

<p><strong>How do I mock/provide <code>IServiceProvider</code> to my SUT without <code>ActivatorUtilities.CreateInstance(IServiceProvider, type)</code> blowing up?</strong></p>
",https://stackoverflow.com/questions/52059180/how-to-mock-iserviceprovider-and-still-allow-createinstance-of-generic-types,"['c#', 'unit-testing', 'asp.net-core', 'moq', 'xunit']",12119,TRUE,1,2
Creating SQL Agent job is failing with no errors,"<p>I am trying to create a SQL Agent job with a command line step using C#. The web API is calling a class which contains the method, when stepping through the code no errors are thrown and all variables have values but the job is not created when looking at my SQL instance (I'm running a local instance of SQL Server 2016). I have 2 methods in the same class that I call; CreateJob() and AddCommandLineStep(). The source code looks like this at the moment: </p>

<p>The class methods</p>

<pre><code>public SQLAgentJobHelper CreateJob(string JobName)
    {
        // Create Job 
        foreach (Job job in jobServer.Jobs)
        {
            if (job.Name.Equals(JobName))
            {
                job.Drop();
                break;
            }
        }
        server.ConnectionContext.BeginTransaction();
        job = new Job(jobServer, JobName);

        job.Create();
        job.ApplyToTargetServer(server.Name);

        server.ConnectionContext.CommitTransaction();           

        return this;
    }

public void AddCommandLineStep(string StepName, string Executable, string CommandLine, List&lt;NameValue&gt; paramList, bool isLast = false)
    {
        try
        {
            if (job == null)
                throw new Exception(""First call CreateJob before adding steps"");

            var jobStep = new JobStep(job, StepName);

            var paramString = CommandLine;
                paramList.ForEach(param =&gt; paramString += $""/{param.Name} {param.Value} "");
                jobStep.Command = $""\""{Executable}\"" {paramString}"";

            jobStep.SubSystem = AgentSubSystem.CmdExec;
            if (isLast)
                jobStep.OnSuccessAction = StepCompletionAction.QuitWithSuccess;
            else
                jobStep.OnSuccessAction = StepCompletionAction.GoToNextStep;

            jobStep.OnFailAction = StepCompletionAction.QuitWithFailure;

            jobStep.Create();

            lastJobStep = jobStep;
        }
        catch (Exception ex)
        {

        }
    } 
</code></pre>

<p>The API calls</p>

<pre><code>jobHelper.CreateJob(jobName)
jobHelper.AddCommandLineStep(""Step 1"", @""C:\Program Files\Microsoft SQL Server\130\DTS\Binn\DTEXEC.exe"", @""C:\SSIS\CopyDataView.dtsx"", Enumerable.Empty&lt;NameValue&gt;().ToList());
</code></pre>

<p>I know about the empty catch and the paths will be replaced by variables, this is just a rough attempt at getting the code to function as required.</p>

<p><strong>[UPDATE]</strong></p>

<p>I can definitely say that the methods work, when doing unit testing I am able to create a job on the same SQL instance. After taking a more detailed look at this issue, I saw that there is approx. 30 projects in the solution. Is it possible that there is some dll referenced in another project that is causing the job creation to fail?</p>
",https://stackoverflow.com/questions/49505919/creating-sql-agent-job-is-failing-with-no-errors,"['c#', 'api', 'sql-server-2016', 'sql-agent-job', '.net-4.7']",139,TRUE,0,1
problems with code coverage on sonarqube and azure devops with Angular 6,"<p>Hi all and thanks in advance for reading this.</p>

<p>I have some problems with the manual execution of unit testing on local and also for running these ones on azure devops and the reporting of the results on sonarqube.</p>

<p>When I run <code>ng test</code> I get these errors:</p>

<pre><code>Chrome 71.0.3578 (Windows 10.0.0) ERROR
  {
    ""message"": ""Uncaught TypeError: Cannot read property 'fn' of undefined\nat http://localhost:9876/_karma_webpack_/scripts.js:122:12\n\nTypeError: Cannot read property 'fn' of undefined\n    at setTransitionEndSupport (http://localhost:9876/_karma_webpack_/scripts.js:122:12)\n    at http://localhost:9876/_karma_webpack_/scripts.js:200:5\n    at http://localhost:9876/_karma_webpack_/scripts.js:202:4\n    at http://localhost:9876/_karma_webpack_/scripts.js:9:4\n    at http://localhost:9876/_karma_webpack_/scripts.js:10:2"",
    ""str"": ""Uncaught TypeError: Cannot read property 'fn' of undefined\nat http://localhost:9876/_karma_webpack_/scripts.js:122:12\n\nTypeError: Cannot read property 'fn' of undefined\n    at setTransitionEndSupport (http://localhost:9876/_karma_webpack_/scripts.js:122:12)\n    at http://localhost:9876/_karma_webpack_/scripts.js:200:5\n    at http://localhost:9876/_karma_webpack_/scripts.js:202:4\n    at http://localhost:9876/_karma_webpack_/scripts.js:9:4\n    at http://localhost:9876/_karma_webpack_/scripts.js:10:2""
  }

Chrome 71.0.3578 (Windows 10.0.0) ERROR
  {
    ""message"": ""Uncaught TypeError: Cannot read property 'fn' of undefined\nat http://localhost:9876/_karma_webpack_/scripts.js:122:12\n\nTypeError: Cannot read property 'fn' of undefined\n    at setTransitionEndSupport (http://localhost:9876/_karma_webpack_/scripts.js:122:12)\n    at http://localhost:9876/_karma_webpack_/scripts.js:200:5\n    at http://localhost:9876/_karma_webpack_/scripts.js:202:4\n    at http://localhost:9876/_karma_webpack_/scripts.js:9:4\n    at http://localhost:9876/_karma_webpack_/scripts.js:10:2"",
    ""str"": ""Uncaught TypeError: Cannot read property 'fn' of undefined\nat http://localhost:9876/_karma_webpack_/scripts.js:122:12\n\nTypeError: Cannot read property 'fn' of undefined\n    at setTransitionEndSupport (http://localhost:9876/_karma_webpack_/scripts.js:122:12)\n    at http://localhost:9876/_karma_webpack_/scripts.js:200:5\n    at http://localhost:9876/_karma_webpack_/scripts.js:202:4\n    at http://localhost:9876/_karma_webpack_/scripts.js:9:4\n    at http://localhost:9876/_karma_webpack_/scripts.js:10:2""
</code></pre>

<p>I cannot see the execution of these test on the terminal, but get the browser window for debugging.</p>

<p>You can find package.json and karma.conf.js below:</p>

<p><strong>package.json</strong></p>

<pre><code>  ""scripts"": {
    ""ng"": ""ng"",
    ""start"": ""ng serve"",
    ""build"": ""ng build"",
    ""test"": ""ng test --code-coverage --watch=false"",
    ""lint"": ""ng lint"",
    ""e2e"": ""ng e2e""
  },
  ""private"": true,
  ""dependencies"": {
    ""@angular/animations"": ""6.0.4"",
    ""@angular/common"": ""6.0.4"",
    ""@angular/compiler"": ""6.0.4"",
    ""@angular/core"": ""6.0.4"",
    ""@angular/forms"": ""6.0.4"",
    ""@angular/http"": ""6.0.4"",
    ""@angular/platform-browser"": ""6.0.4"",
    ""@angular/platform-browser-dynamic"": ""6.0.4"",
    ""@angular/platform-server"": ""6.0.4"",
    ""@angular/router"": ""6.0.4"",
    ""@nguniversal/module-map-ngfactory-loader"": ""^5.0.0-beta.5"",
    ""bootstrap"": ""4.1.1"",
    ""core-js"": ""^2.4.1"",
    ""ngx-bootstrap"": ""^3.0.0"",
    ""ngx-markdown"": ""^6.1.0"",
    ""rxjs"": ""^6.3.2"",
    ""rxjs-compat"": ""^6.2.1"",
    ""zone.js"": ""^0.8.26""
   },
   ""devDependencies"": {
    ""@angular-devkit/build-angular"": ""^0.11.3"",
    ""@angular/cli"": ""6.2.2"",
    ""@angular/compiler-cli"": ""6.0.4"",
    ""@angular/language-service"": ""6.0.4"",
    ""@types/jasmine"": ""~2.8.3"",
    ""@types/jasminewd2"": ""~2.0.2"",
    ""@types/node"": ""~6.0.60"",
    ""codelyzer"": ""^4.0.1"",
    ""jasmine-core"": ""~2.8.0"",
    ""jasmine-spec-reporter"": ""~4.2.1"",
    ""karma"": ""^3.1.3"",
    ""karma-chrome-launcher"": ""~2.2.0"",
    ""karma-coverage-istanbul-reporter"": ""^1.2.1"",
    ""karma-jasmine"": ""~1.1.0"",
    ""karma-jasmine-html-reporter"": ""^0.2.2"",
    ""karma-junit-reporter"": ""^1.2.0"",
    ""protractor"": ""^5.4.1"",
    ""ts-node"": ""~4.1.0"",
    ""tslint"": ""~5.9.1"",
    ""typescript"": ""2.7.2""
  },
</code></pre>

<p><strong>karma.conf.js</strong></p>

<pre><code>module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    files: [
      { pattern: 'src/**/*.ts' }
    ],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma'),
      require('karma-junit-reporter'),
      require('karma-coverage'),
    ],
    client:{
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    coverageIstanbulReporter: {
      dir: require('path').join(__dirname, 'coverage'),
      reports: [ 'html', 'lcov', 'cobertura' ],
      fixWebpackSourcePaths: true
    },
    coverageReporter: {
      dir: 'coverage',
      reporters: [
        { type: 'html', subdir: 'report-html' },
        { type: 'cobertura', subdir: 'cobertura-html' },
        { type: 'lcov', subdir: 'coverage' }
      ]
  },
    reporters: ['progress', 'coverage-istanbul', 'junit', 'coverage'],
    junitReporter: {
      outputDir: '',
      outputFile: 'test.xml',
    },
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
  });
};
</code></pre>

<p>Also regarding with this problem, I'm also getting the lcov.info file empty, so I'm completely lost on this way.</p>

<p>Is there a bug between versions or something like that? Or I'm doing something bad?</p>

<p>Thanks!</p>

<p><strong>EDIT: FIRST PROBLEM SOLVED</strong></p>

<p>It was a problem in the bootstrap.js. I just install jquery library and put in my angular.json file the reference to jquery before the bootstrap one.</p>

<p><strong>angular.json</strong></p>

<pre><code>""test"": {
     ""builder"": ""@angular-devkit/build-angular:karma"",
     ""options"": {
       ""main"": ""src/test.ts"",
       ""karmaConfig"": ""./karma.conf.js"",
       ""polyfills"": ""src/polyfills.ts"",
       ""tsConfig"": ""src/tsconfig.spec.json"",
       ""scripts"": [
         ""node_modules/jquery/dist/jquery.min.js"", //this one
         ""node_modules/bootstrap/dist/js/bootstrap.min.js""
       ],
</code></pre>

<p>I still have the problem with the file I have to generate for the code coverage.</p>

<p>I tried, karma-coverage, karma-typescript, karma-coverage-istanbul-reporter and I'm having problems and errors with all of them. I'm going to share my tsconfig.json just in case. </p>

<p><strong>tsconfig.json</strong></p>

<pre><code>    {
  ""compileOnSave"": false,
  ""compilerOptions"": {
    ""baseUrl"": ""."",
    ""outDir"": ""./dist/out-tsc"",
    ""sourceMap"": true,
    ""declaration"": false,
    ""moduleResolution"": ""node"",
    ""emitDecoratorMetadata"": true,
    ""experimentalDecorators"": true,
    ""target"": ""ES5"",
    ""module"": ""commonjs"",
    ""typeRoots"": [
      ""node_modules/@types""
    ],
    ""lib"": [
      ""es2017"",
      ""dom""
    ]
  },
  ""exclude"": [""node_modules""]
}
</code></pre>
",https://stackoverflow.com/questions/53812863/problems-with-code-coverage-on-sonarqube-and-azure-devops-with-angular-6,"['typescript', 'sonarqube', 'azure-devops', 'code-coverage', 'lcov']",1375,TRUE,0,1
Deserializing serialized objects with gsoap in order to validate web service output,"<p>Out of the box, gsoap does not provide any means for output validation (ensure schema validity of object serializations sent to the client).  We already had some validation issues in the past so at least I'd like to  validate our web service output through unit testing.</p>

<p>The idea is pretty simple.  Put together an arbitrary object tree using gsoap-mapped C++ types and pass it to a generic function</p>

<pre><code>template&lt;typename T&gt; validate(const T&amp; xmlObject);
</code></pre>

<p>Then <code>validate</code> calls <code>T::soap_put()</code> to serialize it and passes the resulting string to <code>T::soap_get()</code> deserializing it again, using a freshly generated soap context initialized with the <code>SOAP_XML_STRICT</code> flag.</p>

<p>However in practice, upon deserialization, gsoap seems to be unable to recognize the namespace prefixes it generated while serializing, resulting in error messages of the form <code>""Tags '%s' and '%s' match but namespaces differ</code>.  I stepped a bit through the validation code in stdsoap2.cpp, which revealed that the failing method <code>soap_match_namespace()</code> matches against the soap context property <code>soap-&gt;local_namespaces</code> which is empty for my freshly constructed de-serializing soap context.</p>

<p>I have no idea how to continue at this point. Is this the expected behavior? How are the <code>T::soap_put()</code> and <code>T::soap_get()</code> methods supposed to be used anyway? Is there an alternative approach to output validation?</p>
",https://stackoverflow.com/questions/48775828/deserializing-serialized-objects-with-gsoap-in-order-to-validate-web-service-out,"['c++', 'gsoap']",467,FALSE,0,1
Testing API call that happens at app launch results in multiple calls to fulfill,"<p>I am trying to implement Unit Testing for the first time on an existing app. First of all, contrary to what I see in tutorials, the app is launched as I try to run unit tests. I tried setting Host App to ""None"" on my test target, but ran into several issues having to do with ""symbols not found"" errors.</p>

<p>I then kept trying to run unit tests even with the app launching, but I run into the following error:</p>

<blockquote>
  <p>'NSInternalInconsistencyException', reason: 'API violation - multiple calls made to -[XCTestExpectation fulfill] for Did log in user.'</p>
</blockquote>

<p>My guess is that my test logs in the user and fulfills an expectation on the delegate, but the app itself when it launches is logging in the user, so 'fulfill' gets called twice.</p>

<p>My test is the following:</p>

<pre><code>func testLogInUser() {
   UserManager.loginDelegate = self
   expectation = expectation(description: ""Did log in user"")
   UserManager.logInUser(withEmail: ""jacobo@viewer.com"", password: ""jacobo123"")
   waitForExpectations(timeout: 10.0)
}

//Delegate Method
func didLogIn(user: User) {
    XCTAssertEqual(user.email, ""jacobo@viewer.com"")
    XCTAssertNotNil(user.uid)
    XCTAssertNotEqual(user.type, .guest)
    expectation?.fulfill() //Crashes here
}
</code></pre>

<p>Therefore, I'm looking for a solution that either lets me run the tests and API calls without running the app, or somehow avoids fulfill being called multiple times.</p>

<p>There is an answer in SO that suggests setting 'expectation' to nil after use, but didn't work in my case. Also tried setting the variable to weak.</p>
",https://stackoverflow.com/questions/51989692/testing-api-call-that-happens-at-app-launch-results-in-multiple-calls-to-fulfill,"['swift', 'xcode', 'xctest', 'xctestexpectation']",134,FALSE,0,1
"sinon mocking GET, POST, PUT and DELETE methods assertions fail everytime. no idea why","<p>am learning sinon and nodeUnit for nodejs. wrote simple <a href=""https://github.com/MHDuke/nodeJs/blob/master/modules/http-module.js"" rel=""nofollow noreferrer"">module</a> that handles GET, POST, PUT and DELETE methods.</p>

<p>then started writing unit test. Now there are two sides for my problem: </p>

<p>One being: in <a href=""https://github.com/MHDuke/nodeJs/blob/master/unit-testing-intro/test-http-module.js"" rel=""nofollow noreferrer""><code>GET</code> test</a>  when i specify <code>requestMock.method = 'GET';</code> then
run <code>nodeunit test-http-module.js</code> test fails, when reviewing call stack it says POST request failed (handlePostRequest as highlighted in call stack below). </p>

<p>Two being: when changing <code>requestMock.method = 'GET';</code> to <code>'POST', 'PUT' or 'DELETE'</code> test still fails no matter what i change! but in latter cases the call stack shows the correct method being directed to.</p>

<p>I think there is a single problem causing the continuous failures and that <code>GET</code> being directed to <code>POST</code>.</p>

<p>please explain what is wrong.</p>

<blockquote>
  <p>ExpectationError: Unexpected call: writeHead(200, { Content-Type:
  ""text/plain"" })</p>
  
  <p>Expectation met: writeHead(200, { Content-Type: ""text/plain"" }[, ...]) once</p>
  
  <p>at Object.fail (D:\Projects\node-book\node_modules\sinon\lib\sinon\mock-expectation.js:281:25)</p>
  
  <p>at Object.invokeMethod (D:\Projects\node-book\node_modules\sinon\lib\sinon\mock.js:174:25)</p>
  
  <p>at Object.writeHead (D:\Projects\node-book\node_modules\sinon\lib\sinon\mock.js:67:35)</p>
  
  <p>at <code>handlePostRequest</code> (D:\Projects\node-book\modules\http-module.js:8:14)</p>
  
  <p>at Object.handleRequest (D:\Projects\node-book\modules\http-module.js:34:26)</p>
  
  <p>at Object.exports.handleGetRequestTest (D:\Projects\node-book\unit-testing-intro\test-http-module.js:22:21)</p>
</blockquote>
",https://stackoverflow.com/questions/51760499/sinon-mocking-get-post-put-and-delete-methods-assertions-fail-everytime-no-id,"['node.js', 'sinon', 'nodeunit']",181,TRUE,0,1
CQRS and Commands Java + Spring similar to MediatR,"<p>While working on a .NET project I come across a library MediatR which made CQRS and Commands simple to implement. I really like using commands and commands handlers as I've worked on far too many projects that have giant procedural style service classes that inject way to many dependencies making unit testing painful. I am looking for something similar to MediatR for Spring + Java. Essentially I would like to inject a single dependency into the controller class and have it delegate commands to the appropriate command handler. I provided a few snippets of what MediatR looks like below. I prefer the way mediator does it as injecting the CommandHandlers into the controller class can lead to the same issue with the class having tons of dependencies injected.</p>

<p>I've came across this library but it seems more like a side project that something that is production ready. <a href=""https://github.com/sleroy/spring-cqrs-arch"" rel=""noreferrer"">https://github.com/sleroy/spring-cqrs-arch</a>. I am aware of the Axon framework, but I'm not looking to go full blown event sourcing at this point. Are there any libraries out there already for this that maybe I'm haven't stumbled across yet? I suppose I could just use the Guava EventBus.</p>

<p>Below is a C# example of what MediatR usage looks like.</p>

<p>Controller</p>

<pre><code>namespace DAB.Controllers
{
    [Route(""api/[controller]"")]
    [ApiController]
    public class PersonController : ControllerBase
    {
        private readonly IMediator mediator;

        public PersonController(IMediator mediator)
        {
            this.mediator = mediator;
        }

        // GET api/values
        [HttpPut(""{id}/changename"")]
        public async Task&lt;ActionResult&gt; ChangeName([FromBody] ChangeNameCommand command)
        {
            await this.mediator.Send(command);
            return Ok();
        }
    }
}
</code></pre>

<p>Command</p>

<pre><code>public class ChangeNameCommand: IRequest&lt;bool&gt;
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
</code></pre>

<p>CommandHandler</p>

<pre><code>public class ChangeNameHandler: IRequestHandler&lt;ChangeNameCommand, bool&gt;
{
    public Task&lt;bool&gt; Handle(ChangeNameCommand request, CancellationToken cancellationToken)
    {
        Console.WriteLine($""Changing name to {request.FirstName} {request.LastName}"");
        return Task.FromResult(true);
    }
}
</code></pre>
",https://stackoverflow.com/questions/52704537/cqrs-and-commands-java-spring-similar-to-mediatr,"['java', 'spring', 'cqrs']",6456,TRUE,7,2
Having trouble successfully unit testing my Python program: No such file or directory....0 of 1 tests passed,"<p>I forked a repository from Github that contains a data engineering project. From the repository, I have created a Python script that works as it's supposed to on my local machine.</p>

<p>Basically, the program is supposed to read in an input .txt file, perform some clean-up and calculations on the file, and return an output .txt file.</p>

<p>The repository also has the code written to test the program. However, I'm still in the process of learning how to correctly compile and execute my code, and I'm running into problems with the unit testing.</p>

<p>From the command line, I run the file './test_run.sh' and the test shows that my program is correctly reading in my input file AND it is successfully creating a test directory for my output, including an ""output"" directory. </p>

<p>The problem is that the program is supposed to create an output file 'data_output.txt"" inside the output directory, but this is not happening.</p>

<p>Here is the error message I'm getting:</p>

<pre><code>$ ./test_run.sh
diff: ./test_output/output/data_output.txt: No such file or directory
[FAIL]: test_1
diff: ./test_output/output/data_output.txt: No such file or directory
[Thu Feb 15 20:56:11 EST 2018] 0 of 1 tests passed
</code></pre>

<p>What would I need to change so that my program creates the data_output.txt file and writes my program output to this file?</p>
",https://stackoverflow.com/questions/48819238/having-trouble-successfully-unit-testing-my-python-program-no-such-file-or-dire,"['python', 'unit-testing', 'compilation']",157,FALSE,0,0
Eclipse CDT missing C/C++ Unit,"<p>I'm tasked with hooking up Google Test in Eclipse. I got Google Test working from the command-line, but we want it working like JUnit for Java in Eclipse. This is theoretically possible. However, running through all the online instructions I can find, they all say to use Run -> Run Configurations... -> C/C++ Unit option. For the life of me, I can't find it. Everything else is in the Run Configurations dialog, just not that item.</p>

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

<p>So I figured, even though we have Eclipse for C++ Developers installed (which should contain everything that the CDT Plug-in contains), maybe it's missing the unit testing stuff. Trying to update CDT, however, just shows that the only thing missing is the Autotools stuff (which we have no need for).</p>

<p>Vital statistics:</p>

<ul>
<li>Eclipse version: Oxygen.1a Release (4.7.1a)</li>
<li>Operating System: Linux, CentOS</li>
<li>Compiler: gcc</li>
</ul>

<p>I know that's the not the latest version of Oxygen. It's the latest we can use, because the current versions have a bug that doesn't recognize our code as valid C++.</p>

<p>How do I get the C/C++ Unit option in Run Configurations?</p>
",https://stackoverflow.com/questions/50220864/eclipse-cdt-missing-c-c-unit,"['c++', 'eclipse', 'eclipse-cdt']",1277,TRUE,0,1
Testing Angular 1 service,"<p>I am working on an Angular 1 project where I am setting up unit testing. 
So, There is a service that I need to test, its name is ""appSecurity"". The methods in this service use pre-loaded user data coming from service named ""userService"". ""appSecurity"" service simply references this user data from userService to take appropriate security decisions. </p>

<p>Below is a part appSecurity service for better understanding:</p>

<pre><code>function appSecurity($log, $http, $state, $q, localStorageService, userService, grcRoutes, appRolesConstant, controlAssessmentService) {
    appSecurity.routeToErrorPageIfNotFullAccessRoleInCM = function () {
        var controlRegisterRoles = _.find(userService.currentUser.controlRegisterUsers, function (controlRegisterUser) {
        var controlRegisterUserRole = controlRegisterUser.applicationRoles[0];
        return controlRegisterUserRole.name === appRolesConstant.FullAccess;
      });
   };
}
</code></pre>

<p>As you can see, this service has many dependencies like $log, $http, $state, $q, localStorageService, userService, grcRoutes, appRolesConstant, controlAssessmentService. One of them is userService which has preloaded users data. </p>

<p>Basically I want to have the ability to inject mocked userService in appSecurity service so that I can test its methods without worrying about its dependencies data. Below is an example to do the same for a controller. </p>

<pre><code>beforeEach(inject(function($controller) {
  $scope = $rootScope.$new();

  userService = {
    query: function() {
      queryDeferred = $q.defer();
      return {$promise: queryDeferred.promise};
    }
  }

spyOn(userService, 'query').andCallThrough();

// controller injected with mocked service. How can I do the same with a 
//service. In this case I want to instantiate appSecurity service like this 
//with inject mocked userService. 
  $controller('BreakfastCtrl', {
    '$scope': $scope,
    'userService': userService 
  });
}));
</code></pre>

<p>The way in which we can create a controller with mocked dependency injections, is there a way to create a service with mocked injections. I tried $service replacing $controller in above code but it didn't work. </p>

<p>I want to do this, </p>

<pre><code>$service('appSecurityService', {
   '$scope': $scope,
   'userService': userService 
});
</code></pre>

<p>But $service cannot be found in angular-mocks. 
Any help is highly appreciated. </p>

<p>Thanks</p>
",https://stackoverflow.com/questions/49312702/testing-angular-1-service,"['javascript', 'angularjs', 'unit-testing', 'angular-mock']",36,FALSE,0,1
Debugging in C programming,"<p>I'm new to the Debugging approach, and there are many things I can not understand.</p>
<h1>The main question here I wanna confirm if my image file contain my source code then anyone can get the source code using debugging feature like list command .</h1>
<p>Debugging is used for image files , like exe extensions</p>
<p>and I see some commands in gdb like &quot;list command&quot;</p>
<p>if I can list all my source code is  this is safe and secure,I mean debugger will be able to see all my code.</p>
<p>if my code compiled as a release version, list command still able to show all my source code?</p>
<p>Also what is the benefit of debugging, I mean I can use testing unit testing , destruction testing or whatever.</p>
<p>so why exactly debugging. and what is the use to know the faults of my software after it is already compiled.</p>
<p>finally can I use debugging on source code itself?</p>
<p>briefly I wanna know the core need to debugging.</p>
<p>I'm sure this will get many down votes, but I do not mind if I can understand the core need of debugging.</p>
",https://stackoverflow.com/questions/49602101/debugging-in-c-programming,"['c', 'debugging', 'gdb']",641,TRUE,-5,1
Link error when adding unit tests to legacy solution,"<p>I'm currently evaluating unit testing frameworks for our dev team and hit a problem I can't figure out how to solve.</p>

<p>Our application is build using Visual Studio 2017. The solution contains 17 projects. Most of them developed by another team (basically 3rd party library from our viewpoint) and most projects produce a dll file. One project is configured to build the executable.</p>

<p>It's that exe project that I can't seem to test. I've tried both Boost::Test and Google.Test. When i try to write tests using a class defined in one of the dll projects, it works as expected.</p>

<p>But when I try to test code from the exe project, I get LNK2019 ""Unresolved external symbol"" linker errors for the code defined in the exe project. The include directories are set correctly, the test project references the relevant other projects. I'm at a loss.</p>

<p>After some online search and tinkering with newly set up test solutions I identified two possible causes:</p>

<ul>
<li>Can't test code in a projct producing an exe file</li>
<li>Can't test code in projects compiled with __stdcall</li>
</ul>

<p>Could my linker error be caused by this? And if so how do I resolve the error?</p>
",https://stackoverflow.com/questions/50467683/link-error-when-adding-unit-tests-to-legacy-solution,"['c++', 'visual-c++', 'visual-studio-2017', 'googletest', 'boost-test']",103,TRUE,0,1
StructureMap DbContext with identity,"<p>So i have recently started using structure map. I have a web api using identity. My goal is to have a dbcontext per request. Currently i am having context issues, the context injected through structure map is different to the one being used by the user manager. I have looked around and cant find a solution even though im sure its pretty obvious.</p>

<p>So to start with i have my structuremap setup. </p>

<pre><code>public class DefaultRegistry : Registry {
    #region Constructors and Destructors

    public DefaultRegistry() {
        Scan(
            scan =&gt; {
                scan.TheCallingAssembly();
                scan.AddAllTypesOf&lt;IImporterService&gt;().NameBy(type =&gt; type.Name);
                scan.WithDefaultConventions();
            });

        For&lt;IHttpContextBaseWrapper&gt;().Use&lt;HttpContextBaseWrapper&gt;();
        For&lt;ApplicationDbContext&gt;().Use(() =&gt; new ApplicationDbContext());
        For&lt;HttpContextBase&gt;().Use(() =&gt; new HttpContextWrapper(HttpContext.Current));
    }

    #endregion
}
</code></pre>

<p>I do not need to inject the user manager for the moment as its accessed through the httpcontext in a base service, i know this will probably have to change for unit testing in the future.</p>

<p>Next we have the startup auth.</p>

<pre><code>private void ConfigureOAuthTokenGeneration(IAppBuilder app)
    {
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext&lt;ApplicationUserManager&gt;(ApplicationUserManager.Create);
        app.CreatePerOwinContext&lt;ApplicationRoleManager&gt;(ApplicationRoleManager.Create);

        //Token Auth
        var OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString(""/api/account/login""),
            Provider = new ApplicationOAuthProvider(""self""),
            AuthorizeEndpointPath = new PathString(""/api/AccountApi/ExternalLogin""),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(121),
            RefreshTokenProvider = new ApplicationRefreshTokenProvider(),
            //#if DEBUG
            AllowInsecureHttp = true,
            //#endif
        };

        // Enable the application to use bearer tokens to authenticate users
        app.UseOAuthBearerTokens(OAuthOptions);
    }
</code></pre>

<p>I have cut down the code but i have the typical structure of service and repository layers. All inject using structuremap, the service and repositories have the correct context, the only on that does not is the user manager. I know its the line below causing the issue:</p>

<pre><code>app.CreatePerOwinContext(ApplicationDbContext.Create);
</code></pre>

<p>However like i said i am still getting used to structure map, i previously used unity and would just resolve the instance i need from the current container. Any help or guidance is much appreciated.</p>
",https://stackoverflow.com/questions/50545846/structuremap-dbcontext-with-identity,"['c#', 'asp.net', 'asp.net-identity', 'structuremap']",284,TRUE,0,1
How to suppress debug message on functional test with simple-phpunit,"<p>I'm just getting started with Symfony 4 and have this problem.</p>

<ol>
<li>Is it normal to have debugged message printed on a console like this when running the functional test?</li>
</ol>

<pre class=""lang-php prettyprint-override""><code>$ vendor/bin/simple-phpunit 
PHPUnit 5.7.27 by Sebastian Bergmann and contributors.

Testing Functional Controller
2018-03-20T18:51:20+07:00 [debug] Notified event ""kernel.request"" to listener ""Symfony\Component\HttpKernel\EventListener\DebugHandlersListener::configure"".
2018-03-20T18:51:20+07:00 [debug] Notified event ""kernel.request"" to listener ""Symfony\Component\HttpKernel\EventListener\ValidateRequestListener::onKernelRequest"".
2018-03-20T18:51:20+07:00 [debug] Notified event ""kernel.request"" to listener ""Symfony\Component\HttpKernel\EventListener\TestSessionListener::onKernelRequest"".
2018-03-20T18:51:20+07:00 [debug] Notified event ""kernel.request"" to listener ""Symfony\Component\HttpKernel\EventListener\SessionListener::onKernelRequest"".
2018-03-20T18:51:20+07:00 [debug] Notified event ""kernel.request"" to listener ""Symfony\Component\HttpKernel\EventListener\RouterListener::onKernelRequest"".
2018-03-20T18:51:20+07:00 [debug] Listener ""Symfony\Component\HttpKernel\EventListener\RouterListener::onKernelRequest"" stopped propagation of the event ""kernel.request"".
2018-03-20T18:51:20+07:00 [debug] Listener ""Symfony\Bundle\FrameworkBundle\EventListener\ResolveControllerNameSubscriber::onKernelRequest"" was not called for event ""kernel.request"".
2018-03-20T18:51:20+07:00 [debug] Listener ""Symfony\Component\HttpKernel\EventListener\LocaleListener::onKernelRequest"" was not called for event ""kernel.request"".
2018-03-20T18:51:20+07:00 [debug] Notified event ""kernel.response"" to listener ""Symfony\Component\HttpKernel\EventListener\ResponseListener::onKernelResponse"".
2018-03-20T18:51:20+07:00 [debug] Notified event ""kernel.response"" to listener ""Symfony\Bundle\FrameworkBundle\DataCollector\RequestDataCollector::onKernelResponse"".
2018-03-20T18:51:20+07:00 [debug] Notified event ""kernel.response"" to listener ""Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelResponse"".
2018-03-20T18:51:20+07:00 [debug] Notified event ""kernel.response"" to listener ""Symfony\Component\HttpKernel\EventListener\TestSessionListener::onKernelResponse"".
2018-03-20T18:51:20+07:00 [debug] Notified event ""kernel.response"" to listener ""Symfony\Component\HttpKernel\EventListener\SessionListener::onKernelResponse"".
2018-03-20T18:51:20+07:00 [debug] Notified event ""kernel.response"" to listener ""Symfony\Component\HttpKernel\EventListener\SaveSessionListener::onKernelResponse"".
2018-03-20T18:51:20+07:00 [debug] Notified event ""kernel.response"" to listener ""Symfony\Component\HttpKernel\EventListener\StreamedResponseListener::onKernelResponse"".
2018-03-20T18:51:20+07:00 [debug] Notified event ""kernel.finish_request"" to listener ""Symfony\Component\HttpKernel\EventListener\LocaleListener::onKernelFinishRequest"".
2018-03-20T18:51:20+07:00 [debug] Notified event ""kernel.finish_request"" to listener ""Symfony\Component\HttpKernel\EventListener\RouterListener::onKernelFinishRequest"".
2018-03-20T18:51:20+07:00 [debug] Notified event ""kernel.terminate"" to listener ""Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelTerminate"".
F                                                                   1 / 1 (100%)

Time: 136 ms, Memory: 10.00MB

There was 1 failure:

1) App\Tests\Controller\HomeControllerTest::testHomepage
Failed asserting that 404 matches expected 200.

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
</code></pre>

<ol start=""2"">
<li>Can it be disabled/suppressed? It seems this message doesn't appear on unit testing.</li>
</ol>

<p><strong>Edit</strong></p>

<p>by adding environment variable into <code>phpunit.xml</code> I got it suppressed but now it's showing uncaught exception when testing undefined route.</p>

<pre><code>&lt;phpunit&gt;
    ...
    &lt;php&gt;
        &lt;env name=""APP_DEBUG"" value=""false"" /&gt;
    &lt;/php&gt;
    ...
&lt;/phpunit&gt;
</code></pre>

<p>Log</p>

<pre><code>$ vendor/bin/simple-phpunit 
PHPUnit 5.7.27 by Sebastian Bergmann and contributors.

Testing 
.2018-03-21T11:22:50+07:00 [error] Uncaught PHP Exception Symfony\Component\HttpKernel\Exception\NotFoundHttpException: ""No route found for ""GET /"""" at vendor/symfony/http-kernel/EventListener/RouterListener.php line 144
F.
Time: 124 ms, Memory: 8.00MB

There was 1 failure:

1) App\Tests\Controller\HomeControllerTest::testHomepage
Failed asserting that 404 matches expected 200.
...
</code></pre>

<p>Is it possible to hide this error message?</p>

<h2>Update</h2>

<p>It seems this problem occur when I delete <code>vendor</code> and <code>bin</code> directory in the root project. Trying to re-install all dependencies with <code>composer install</code> doesn't fix this problem, so I decide to re-create the project from start. This is the steps that I do :</p>

<ul>
<li>create new symfony project with <code>composer create-project symfony/skeleton my-project-name</code></li>
<li>adding other dependecies such as twig, maker, annotation etc with composer command. I'm not editing <code>composer.json</code> directly until all dependecies is installed and there's no problem with functional testing.</li>
<li>copy <code>.git</code> directory from previous project into new 're-created' project to import git history.</li>
<li>I'm letting composer (symfony recipe) to resolve all configuration, overwrite my previous config.</li>
<li>resolve other conflict before commiting</li>
</ul>

<p>I'm letting this qustion open in case there's someone figure it out what's actually happen and how to resolve it without re-creating the project.</p>
",https://stackoverflow.com/questions/49384030/how-to-suppress-debug-message-on-functional-test-with-simple-phpunit,"['functional-testing', 'symfony4']",1287,FALSE,3,1
Unit test Actions on Google Dialogflow locally,"<p>I'm trying to unit test a <code>DialogflowApp</code> locally by using the firebase shell environment. (in a cli do firebase experimental:functions:shell and then call my methods)</p>

<p>I have followed this guide by google <a href=""https://firebase.google.com/docs/functions/local-emulator"" rel=""nofollow noreferrer"">https://firebase.google.com/docs/functions/local-emulator</a> but they don't use the DialogflowApp where the invoked function tries to bind a request object containing intents and parameters like this -></p>

<pre><code>exports.myFunction = functions.https.onRequest((request, response) =&gt; {
const app = new App({ request, response });

function myMethod(app) {
    let myArgument = app.getArgument(MY_ARGUMENT);
    app.tell('Here we are responding');
}

let actionMap = new Map();
actionMap.set(MYMETHOD_ACTION, myMethod);

app.handleRequest(actionMap);
});
</code></pre>

<p>Regardless of what request object I send in the CLI, like this <code>myFunction(require(""../test/testdata.json""))</code>, the request body object is empty, like this <code>body: {}</code> which means I can't do <code>app.handleRequest()</code> or <code>app.getArgument()</code>. The error message I get is </p>

<blockquote>
  <p>RESPONSE RECEIVED FROM FUNCTION: 400, Action Error: no matching intent
  handler for: null</p>
</blockquote>

<p>I thought that if I populated testdata.json with the json request data shown in Actions on Google -> console.actions.google.com -> Simulator it would be valid data but no. </p>

<p>My question is, how can i mock my request data so that I can start unit testing my fullfillment methods locally?</p>

<p>EDIT 1:</p>

<pre><code>firebase &gt; myMethod.post(""/"").form(require(""../test/testdata.json""))
Sent request to function.
firebase &gt; info: User function triggered, starting execution
info: Function crashed
info: TypeError: Cannot destructure property `parameters` of 'undefined' or 'null'.
</code></pre>

<p>if we look in dialogflow_app.js we can see this code for fetching an argument value</p>

<pre><code>  getArgument (argName) {
    debug('getArgument: argName=%s', argName);
    if (!argName) {
      error('Invalid argument name');
      return null;
    }
    const { parameters } = this.body_.result;
    if (parameters &amp;&amp; parameters[argName]) {
      return parameters[argName];
    }
    return this.getArgumentCommon(argName);
  }
</code></pre>

<p>this.body_ is always just empty <code>{}</code>, regardless of how and what I send into the method when running locally.</p>

<p>EDIT 3</p>

<pre><code>firebase &gt; myMethod({method: ""post"",json: true, body:  require(""../test/testdata.json"")})
</code></pre>

<p>Sent request to function.
firebase > info: User function triggered, starting execution
info: Function crashed
info: TypeError: Cannot destructure property <code>parameters</code> of 'undefined' or 'null'.</p>
",https://stackoverflow.com/questions/48791293/unit-test-actions-on-google-dialogflow-locally,"['firebase', 'google-cloud-functions', 'chatbot', 'actions-on-google', 'dialogflow-es']",1567,TRUE,3,1
SQLite with MVC Core,"<p>I'm trying to create a database in memory and run a query with .NET Core 2.1 framework. To do this I have installed a package called <code>Microsoft.Data.Sqlite.Core</code> and then tried to do the following:</p>

<pre><code>var connection = new SqliteConnection(""Data Source=:memory:"");
connection.Execute(""Some Create Table Query"");
</code></pre>

<p>And my code will crash with the following error:</p>

<blockquote>
  <p>You need to call SQLitePCL.raw.SetProvider().  If you are using a bundle package, this is done by calling SQLitePCL.Batteries.Init().</p>
</blockquote>

<p>I've done a lot of digging to find a solution and one of them suggested calling this: </p>

<pre><code>SQLitePCL.raw.SetProvider(new SQLite3Provider_e_sqlite3());
</code></pre>

<p>This produces me a new error:</p>

<blockquote>
  <p>'Unable to load DLL 'e_sqlite3' or one of its dependencies: The specified module could not be found. (Exception from HRESULT: 0x8007007E)'</p>
</blockquote>

<p>I am really lost at this point how to accomplish this. All I want to do is create an in-memory database so I can run some queries for purposes of unit testing.</p>

<p>I'm not sure if this is relevant but I am not using EF6, I am using Dapper and also I am using SQL Server in my actual project. I wanted to plug in Sqlite in unit tests so I can also test my queries.</p>

<p>I have a feeling I am using wrong packages, but looking around there are so many and I can't find any clear documentation on how to use Sqlite with MVC Core projects.</p>
",https://stackoverflow.com/questions/51575892/sqlite-with-mvc-core,"['c#', 'sqlite', 'asp.net-core']",1026,TRUE,3,1
Architecture of an application which opens multiple documents (projects),"<p>I am working on a Qt based CAD application and I am trying to figure out the application's architecture. The application is able to load multiple projects with plans, sections, etc, and to show these drawings in dedicated views. There are per project and global configurations.</p>

<p>The application is represented by the global object, derived from <code>QApplication</code>:</p>

<pre><code>class CADApplication Q_DECL_FINAL: public QApplication {
    Q_OBJECT
public:
    explicit CADApplication(int &amp;args, char **argv);
    virtual ~CADApplication();
    ...
    ProjectManager* projectManager() const;
    ConfigManager* configManager() const;
    UndoManager*  undoManager() const;

protected:
    const QScopedPointer&lt;ProjectManager&gt; m_projectManager;
    const QScopedPointer&lt;ConfigManager&gt; m_configManager;
    ...
};
</code></pre>

<p>The ""managers"" are created in the <code>CADApplication</code>'s constructor. They are responsible for functionality related to loaded projects (<code>ProjectManager</code>), global configuration options (<code>ConfigManager</code>) and so on.</p>

<p>There are also project views, configuration options dialogs, and other objects that may need access to the ""managers"".</p>

<p>In order to get current project, the <code>SettingsDialog</code> needs to:</p>

<pre><code>#include ""CADApplication.h""
#include ""ProjectManager.h""
...
SettingsDialog::SettingsDialog(QWidget *parent)
: QDialog(parent)
{
    ...
    Project* project = qApp-&gt;projectManager()-&gt;currentProject();
    ...
}
</code></pre>

<p>What I like about the whole approach is that it follows RAII paradigm. The ""managers"" are created and destroyed on applcation's instantiation / destruction.</p>

<p>What I don't like is that it is not prone to circular references, and that I need to include ""CADApplication.h"" from every source file, where the instance of any of the ""managers"" is required. It is like the <code>CADApplication</code> object is used like some kind of global ""holder"" of these ""managers"".</p>

<p>I've done some research. It seems like there are also several other approaches that imply usage of singletons. The OpenToonz makes use of <code>TProjectManager</code> singleton:</p>

<pre><code>class DVAPI TProjectManager {
...
public:
    static TProjectManager *instance();
    ...
};

TProjectManager* TProjectManager::instance() {
    static TProjectManager _instance;
    return &amp;_instance;
}
</code></pre>

<p>In every file, where they need to access the project manager:</p>

<pre><code>#include ""toonz/tproject.h""
...

TProjectManager *pm = TProjectManager::instance();
TProjectP sceneProject = pm-&gt;loadSceneProject(filePath);
</code></pre>

<p>From your experience, which of these approaches should I stick to in order to pursue good architecture and to make application error prone and simplify unit testing? Maybe there are other paradigms?</p>
",https://stackoverflow.com/questions/48582916/architecture-of-an-application-which-opens-multiple-documents-projects,"['c++', 'qt', 'architecture', 'conceptual']",571,TRUE,16,4
Are there any techniques to fast-forward time for testing purposes in a Qt application?,"<p>Using Qt for developing a system that in various places involves time based state transitions.  I'm trying to put in place comprehensive unit testing coverage as I go, and obviously trying to provide thorough automated testing of state transitions that occur over multiple second or even minute periods is severely suboptimal.</p>

<p>In the past, when dealing with the same challenges for ""bare metal"" C and RTOS based embedded systems, I've successfully implemented hook functions that have allowed the fast-forwarding/acceleration of passing time for testing purposes, and am wondering if anyone out there has come across any techniques for achieving the same in Qt (developer APIs, shim libraries etc) </p>

<p>The state transitions in question may trigger from a combination of QTimer timeouts, examination of QDateTime/QElapsedTimer/QDeadlineTimer timestamps and QThread sleeps, so a simple fake of QTimer::timeout signals is not enough.</p>

<p>Not really needing the usual suggestions regarding dependency injection of mockable timers, interfaces that allow configurable timeouts, or hanging custom test facilitating facade/decorators over the entirety of the Qt library time related classes.  I'm well aware of how I could do this, I'm hoping that I don't have to...</p>

<p>Duped at <a href=""https://forum.qt.io/topic/88268/are-there-any-techniques-to-fast-forward-time-for-testing-purposes-in-a-qt-application"" rel=""nofollow noreferrer"">https://forum.qt.io/topic/88268/are-there-any-techniques-to-fast-forward-time-for-testing-purposes-in-a-qt-application</a></p>

<p>thx</p>
",https://stackoverflow.com/questions/49062286/are-there-any-techniques-to-fast-forward-time-for-testing-purposes-in-a-qt-appli,"['qt', 'unit-testing']",258,FALSE,2,1
Angular 2+ without routing in ASP.Net MVC application,"<p>I have to work in ASP.Net MVC content management system.  As part of the this, ASP.Net MVC has to control the routing because it's integral to how the content is managed.  It does full-page reloads so I'm not building a single-page-app.</p>

<p>I'd like to use Angular 2+ (currently trying version 4) as my front-end framework so that I can leverage the component architecture, binding, Typescript, unit testing etc.  However, I have no need for the routing.</p>

<p>My intention is to compile the Angular app once and add the appropriate JS and CSS assets on ASP.Net MVC layout page.  Then each page where Angular is required, I would add the bootstrap component and then nest the other components (no <code>router-outlet</code>).</p>

<p>Unfortunately, it appears that it won't work without routing.</p>

<p>Here's some of my code.</p>

<p><strong>_Layout.cshtml</strong></p>

<pre><code>&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;link rel=""stylesheet"" href=""~/Dist/vendor.css"" /&gt;
&lt;/head&gt;
&lt;body&gt;
    @RenderBody()
    &lt;script src=""~/Dist/vendor.js""&gt;&lt;/script&gt;
    &lt;script src=""~/Dist/main-client.js""&gt;&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p><strong>app.component.html</strong></p>

<p><code>&lt;div&gt;&lt;/div&gt;</code></p>

<p><strong>Controller View (Index.cshtml)</strong></p>

<pre><code>&lt;app&gt;
    &lt;test-component&gt;
    &lt;/test-component&gt;
&lt;/app&gt;
</code></pre>

<p><strong>Output</strong></p>

<p>Viewing the HTML source in Chrome shows the same HTML in the Razor view.</p>

<p>However, inspecting the page with Chrome Dev Tools has the following.  Note: there are no errors in the console.</p>

<p><code>&lt;app ng-version=""4.4.6""&gt;&lt;div&gt;&lt;/div&gt;&lt;/app&gt;</code></p>

<p>The <code>app</code> element gets rendered bu the <code>test-component</code> element does not (HTML from <code>test-component.component.html</code> does not get substituted into the page).  My guess is because Angular 2+ requires a <code>router-outlet</code> component.</p>

<p>Is it possible to use Angular 2+ without the routing?</p>
",https://stackoverflow.com/questions/48392107/angular-2-without-routing-in-asp-net-mvc-application,"['asp.net-mvc', 'angular']",856,FALSE,2,0
libgtest.so error adding symbols: DSO missing from command line,"<p>I have been using gtests for unit testing a personal project. Last week I upgraded to the LTS version of Linux Mint. Unfortunately, after that event, I haven't been able to compile my project due to gtests linking problems.</p>

<p>The following error is being issued:</p>

<pre><code>/usr/bin/x86_64-linux-gnu-ld: build/tests/policies/roundrobin_tests.o: undefined reference to symbol '_ZN7testing4TestC2Ev'
/home/myuser/Documents/googletest-release-1.8.0/googletest/libgtest.so: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status
</code></pre>

<p>I have generated both <strong>libgtest.so</strong> and <strong>libgtest_main.so</strong> through CMake 3.10.2. The gtest version is the release-1.8.0, the same I used to have before.</p>

<p>Those libraries are located in /usr/lib and the corresponding include folder has also been copied to /usr/include. I made sure that this location is in my ld path and that is not the problem.</p>

<p>My compiler is g++ v7.3.0 and the command Im using to compile the testes is:</p>

<pre><code>g++ -std=c++14 -Wall -O3 -Iinclude build/tests/policies/roundrobin_tests.o -lgtest_main -pthread -o bin/policies/roundrobin_tests
</code></pre>

<p>I have tried altering the order of the elements in the command, explicitly adding -L/usr/lib and -I/usr/include without luck. A funny fact is that if I take off the -pthread flag, the error is still the same.</p>

<p>The same command was used before and the only difference is the compiler version I am using now as I used g++ 5.4.0 before. Any insights on how to solve this?</p>

<p><strong>edit:</strong> Just tested the same process with g++ 5.4.0 and CMake 3.5 and the same problems ocurred.</p>
",https://stackoverflow.com/questions/52304804/libgtest-so-error-adding-symbols-dso-missing-from-command-line,"['c++', 'compiler-errors', 'linker-errors', 'googletest']",1300,FALSE,2,0
How to deploy GIT code to EC2 automatically,"<p>I have a git repo and local development environment for some Spring Micro-service application. I have a 10 EC2 instance for prod and 5 EC2 instances for test deployment. </p>

<p>For test and prod, we have two different branches of GIT and our plan is that ... </p>

<ol>
<li>First, we will develop code and do unit testing in our local. </li>
<li>We will upload the code in git test brunch and deploy the changes in test EC2 instances </li>
<li>After the successful test, we will upload the code changes in prod brunch and finally deploy the code prod EC2 instances. </li>
</ol>

<p>copying the microservice war file in all EC2 instances one by one, for every change, is not a good idea at all I guess. Is there any automated way/service by which I can connect my GIT repo with AWS service, which will compile the code and run build and copy the war file to the specific local in a specific EC2 instance? </p>

<p>That has to be done per project bases, as it is a microservice so, </p>

<p>Procect1 war should go in EC2-1(say one ec2 instance) /home/user/war</p>

<p>Project2 war should go in EC2-2(say another ec2 instance) /home/user/war</p>

<p>something like that.</p>
",https://stackoverflow.com/questions/50075739/how-to-deploy-git-code-to-ec2-automatically,"['git', 'amazon-web-services', 'amazon-ec2', 'deployment']",1475,TRUE,2,2
Breakpoint does not hit in Nunit Unit Tests,"<p>I am facing some kind of weird <code>visual studio</code> behavior I guess...</p>

<p>I have done Unit Testing in my application using <code>NUnit</code>, in some Unit Tests I have used <code>NFluent</code> and <code>NSubstitute</code> (to make my UT more readable and closer to human language)</p>

<p>Everything worked fine until suddenly I became unable to debug my unit tests.</p>

<p>When I run any test it passes and get green colored. </p>

<p>I figured out that there was a problem when I got an error in my build on <code>VSTS</code> and my test doesn't pass unlike in my dev env where every test is ok.</p>

<p>I tried to analyse test by test so I found that I am able to debug Tests made with <code>NSubstitute</code> and <code>NFluent</code> but tests which are written only using standard <code>NUnit</code> are undebugable ...</p>

<p>Here are the actions I made:</p>

<blockquote>
  <ul>
  <li><p>went to tools-options-test-logging and changed it to ""Diagnostics"" the way i can understand what is happening ==> found that many .dll
  are flagged as ""unloaded""</p></li>
  <li><p>I double checked that i am on debug environment</p></li>
  <li><p>I clean rebuild / open/ close solution and visual studio</p></li>
  </ul>
</blockquote>

<p>Nothing changed and I am still getting error on VSTS build and no errorson dev env neither I can debug on my local environment...</p>

<p>Any suggestion or solution will be welcome .</p>
",https://stackoverflow.com/questions/52893398/breakpoint-does-not-hit-in-nunit-unit-tests,"['visual-studio', 'unit-testing', 'debugging', 'nunit', 'nsubstitute']",1476,TRUE,2,1
Test Flask Dance with unittest,"<p>I have written a flask application that uses flask dance for user authentication. Now I want to test a few views for that I have enabled <code>@login_required</code>.</p>

<p>I wanted to follow the flask dance testing <a href=""https://flask-dance.readthedocs.io/en/latest/testing.html"" rel=""nofollow noreferrer"">docs</a> but I could not get it to work. Because I am only using unittest and not pytest. I also use github and not google as in the docs. So is <code>sess['github_oauth_token']</code> correct? A prototype sample test could look like the following:</p>

<pre><code>def test_sample(self):
    with self.client as client:
        with client.session_transaction() as sess:
            sess['github_oauth_token'] = {
                'access_token': 'fake access token',
                'id_token': 'fake id token',
                'token_type': 'Bearer',
                'expires_in': '3600',
                'expires_at': self.time + 3600
            }

        response = client.post(url_for('core.get_sample'), data=self.fake_sample)

        self.assertRedirects(response, url_for('core.get_sample'))
</code></pre>

<p>The assertRedirect fails because I am redirected to the login page <code>http://localhost/login/github?next=%2Fsample%2F</code> and not <code>url_for('core.get_sample')</code>.</p>

<p>Then tried to simply disable it, by following the official flask login <a href=""https://flask-login.readthedocs.io/en/latest/#protecting-views"" rel=""nofollow noreferrer"">docs</a>.</p>

<blockquote>
  <p>It can be convenient to globally turn off authentication when unit
  testing. To enable this, if the application configuration variable
  LOGIN_DISABLED is set to True, this decorator will be ignored.</p>
</blockquote>

<p><strike>But this does not work as well, the test still fail because login_required is somehow executed.</strike></p>

<p>So my questions are:</p>

<ul>
<li>Because I am using github and not google as in the docs is <code>github_oauth_token</code> the correct key for the session?</li>
<li>How do I test views that have the <code>@login_required</code> decorator with unittest when using Flask Dance?</li>
</ul>

<p>Edit: <code>LOGIN_DISABLED=True</code> works as long as I define it in my config class I use for <code>app.config.from_object(config['testing'])</code>, what did not work was to set <code>self.app.config['LOGIN_DISABLED'] = True</code> in my setup method.</p>
",https://stackoverflow.com/questions/51508666/test-flask-dance-with-unittest,"['python', 'flask', 'oauth', 'python-unittest']",262,TRUE,1,1
How to represent foreign key lookup table in Django unit test?,"<p>I'm building three Django models that will allow users to create lists of items that represent activities (e.g. movies, concerts, and sporting events) they want to attend. Since each user can include one or more items (i.e. activities) in a list and multiple users may have the same item (activity) in one of their lists, there's a many-to-many relationship between lists and items:</p>

<p>The 'list_type' table is a foreign key lookup table that identifies what types of activity items (movies, etc.) are stored in a list.  I pre-populate this table via a Django migration when I run my initial migrations that create my tables.</p>

<pre><code># list/models.py
class ListType(models.Model):
    LIST_TYPES = (
        (1, 'Movie'),
        (2, 'Concert'),
        (3, 'Sport'),
    )
    type = models.CharField(_('type'), max_length=16)
    class Meta:
        db_table = 'list_type'

class List(models.Model):
    user = models.ForeignKey(User)
    type = models.ForeignKey(ListType, help_text=_('Type of list'))
    name = models.CharField(_('list'), max_length=128, help_text=_('Name of list'))
    class Meta:
        db_table = 'list'
        unique_together = (('user', 'type', 'name'), )

class Item(models.Model):
      # value contains the pk of a movie, concert, or sporting event record
    lists = models.ManyToManyField(List, related_name='items').
    value = models.IntegerField(_('item'), help_text=_('Item in list'))
    class Meta:
        db_table = 'item'
</code></pre>

<p>I've been trying to represent the Type table with a factory-boy factory:</p>

<pre><code>import factory
from list.models import ListType

class ListTypeFactory(factory.django.DjangoModelFactory):
    type = 'Movie'
    #type = ListType.objects.get(type='Movie')

    class Meta:
        model = Type
</code></pre>

<p>The problem I'm having is that when I run a unit test and am just setting things up, I get an error:</p>

<pre><code>class ListTest(TestCase):
    def setUp(self):
        self.activity_type = ListTypeFactory(type='Member')

# =&gt; IntegrityError: duplicate key value violates unique constraint...
# =&gt; ""Key (type)=(Movie) already exists""
...
</code></pre>

<p>This makes sense as the Django TestCase test harness makes a copy of all my tables and the list_type table is prepopulated.  But what's the correct way to represent this table in a unit test?  Factory-boy doesn't appear to be the right mechanism and I don't want to touch the database to create an instance of the table as touching the database is a unit testing anti-pattern.</p>
",https://stackoverflow.com/questions/48752641/how-to-represent-foreign-key-lookup-table-in-django-unit-test,"['django', 'unit-testing', 'django-models']",243,FALSE,1,0
How to store autocomplete results in redux and react,"<p>I am trying to figure out how best to work with react, redux and an autocomplete component. At this present time, I am using <a href=""http://jedwatson.github.io/react-select/"" rel=""nofollow noreferrer"">react-select</a>. The issue I have is around when and where to make the API call to retrieve the autocomplete results.</p>

<p>There are two ways I have attempted to solve this problem:</p>

<ol>
<li><p>Make the API call from inside the component or via a callback passed in from the container wrapping the component. This works just fine for me. I imagine unit testing it is a little less tidy as a result of it. </p></li>
<li><p>Raise a redux action on a keystroke. In the action creator make the API call. With the use of redux-thunk middleware, the promise is resolved and a new action is raised with the search results as it's payload and is stored in some part of the store. The autocomplete component has been listening to this list and renders the list of results. I partly got this working with the <a href=""http://jedwatson.github.io/react-select/"" rel=""nofollow noreferrer"">react-select</a> but the state of the input component is getting wiped out on subsequent keystrokes.</p></li>
</ol>

<p>I looking for guidance on the advantages/disadvantages of either approach and if there is best practice here to adopt.</p>

<p>Thanks.</p>
",https://stackoverflow.com/questions/50293001/how-to-store-autocomplete-results-in-redux-and-react,"['reactjs', 'autocomplete', 'redux', 'redux-thunk', 'react-select']",1241,TRUE,1,1
Should FluentAssertions be used in production code?,"<p>I've been using FluentAssertions for unit testing and was wondering why it's only ever mentioned in that context.  If you generally write fail-fast production code with guards you would have to duplicate some of the functionality FluentAssertions already provides.  Some of the reasons I can think of to not use it:</p>

<ol>
<li>Its focus is to be readable, not to perform well.  Counter: isn't that what higher-level languages also do and related to the warning to not do premature optimization?</li>
<li>Also related to performance, there is no good way to have some assertions not run when code is compiled in release mode.  Counter: You may remove an assertion you think won't happen in production but leads to an exception that is hard to track down.  As long as they're not affecting performance significantly, leave it.</li>
<li>Its assertions don't always throw standard exceptions.  For example, <code>ArgumentNullException</code> and <code>ArgumentException</code> are ubiquitous and expected, but FluentAssertions doesn't know you're testing an argument and throws a generic exception.</li>
</ol>

<p>Maybe it's already known performance is significantly impacted so #1 and #2 are legitimate, but you would generally also want fast unit tests so the same logic could apply there.  Any other good reasons not to use FluentAssertions in production code?</p>
",https://stackoverflow.com/questions/49724379/should-fluentassertions-be-used-in-production-code,"['c#', 'fluent-assertions']",1174,TRUE,1,1
.babelrc breaking semantic-ui and next app,"<p>I am not sure what went on, but whenever I wanted to add unit testing to my app, I had to add <code>.babelrc</code> file with just the following code:</p>

<pre><code>{
  ""presets"": [
    ""es2015"",
    ""next/babel""
  ]
}
</code></pre>

<p>Prior to that, I did not need the file and it was just an nextjs app with semantic. So far, so good. Until I decided to rebuild my semantic-ui theme which turned out to be a massive mistake!</p>

<p>This was what I ran: <code>cd semantic &amp;&amp; gulp build</code></p>

<p>This caused my app to stop working whenever <code>.babelrc</code> is present.</p>

<p>These are my <code>package.json</code> scripts:</p>

<pre><code>  ""scripts"": {
    ""dev"": ""next"",
    ""build"": ""next build"",
    ""start"": ""next start"",
    ""semantic"": ""cd semantic &amp;&amp; gulp build"",
    ""test"": ""mocha --require babel-core/register --watch-extensions js **/*.test.js""
  },
</code></pre>

<p>If I attempt to run the <code>next</code> related scripts, I get the following error:</p>

<blockquote>
  <p>Error: Plugin/Preset files are not allowed to export objects, only functions. In /Users/theJuls/Workspace/cbt/client/node_modules/babel-preset-es2015/lib/index.js</p>
</blockquote>

<p>If I try to run my unit tests, I get</p>

<blockquote>
  <p>Error: Plugin 0 specified in ""/Users/theJuls/Workspace/cbt/client/node_modules/next/babel.js"" provided an invalid property of ""default"" (While processing preset: ""/Users/theJuls/Workspace/cbt/client/node_modules/next/babel.js"")</p>
</blockquote>

<p>If I remove <code>.babelrc</code>, all the <code>next</code> scripts run normally, however I completely lost my unit tests. Why is this happening? What can I do to fix this?</p>

<p>I am not sure if this is relevant but here is my current file structure:</p>

<pre><code>api/
components/
config/
lib/
pages/
semantic/
store/
.babelrc
package-lock.json
package.json
semantic.json
</code></pre>
",https://stackoverflow.com/questions/50201358/babelrc-breaking-semantic-ui-and-next-app,"['semantic-ui', 'babeljs', 'package.json', 'next.js']",260,TRUE,1,1
Is it necessary to Mock every class that is injected into the method?,"<p>My question is similar to this one: <a href=""https://stackoverflow.com/questions/23643643/should-i-mock-all-the-dependencies-when-unit-testing"">Should I mock all the dependencies when unit testing?</a></p>

<p>I understand the benefit of mocking when my code accesses a database or a web service or a file on the file system.  Mocking means that if there is an issue that I have no control over e.g. a network issue, then my unit tests will pass - because my code is still correct.</p>

<p>However, say I have some code like this:</p>

<pre><code>public Offer AssignOffer(OfferType offerType, IOfferValueCalculator valueCalculator) 
        { 
            DateTime dateExpiring = offerType.CalculateExpirationDate(); 
            int value = valueCalculator.CalculateValue(this, offerType); 


            var offer = new Offer(this, offerType, dateExpiring, value); 


            _assignedOffers.Add(offer); 


            NumberOfActiveOffers++; 


            return offer; 
        } 
</code></pre>

<p>which I took from here: <a href=""https://github.com/jbogard/presentations/blob/master/WickedDomainModels/After/Model/Member.cs"" rel=""nofollow noreferrer"">https://github.com/jbogard/presentations/blob/master/WickedDomainModels/After/Model/Member.cs</a></p>

<p>Is it normal practice to mock the object parameters passed to the method i.e. OfferType and IOfferValueCalculator (interfaces and classes I have written)? These classes were written by me and are in the same project as Member.AssignOffer.</p>

<p>I asked a similar question earlier; however it was closed because opinion based.  I have tried to make this question more clearer by providing example code.</p>

<p>My question is also similar to this: <a href=""https://stackoverflow.com/questions/38181/when-should-i-mock"">When should I mock?</a>.</p>

<p>This: <a href=""https://lostechies.com/jimmybogard/2011/01/07/putting-mocks-in-their-place/"" rel=""nofollow noreferrer"">https://lostechies.com/jimmybogard/2011/01/07/putting-mocks-in-their-place/</a> and this: <a href=""http://www.taimila.com/blog/ddd-and-testing-strategy/"" rel=""nofollow noreferrer"">http://www.taimila.com/blog/ddd-and-testing-strategy/</a> seem to advise only mocking: ""Mock across architecturally significant boundaries, but not within those boundaries"".</p>
",https://stackoverflow.com/questions/48427674/is-it-necessary-to-mock-every-class-that-is-injected-into-the-method,"['c#', 'unit-testing', 'mocking']",175,FALSE,0,2
Droid API 22+ options for Date/Duration (in Kotlin)?,"<p>I'm porting an iOS app to Android, target API 22. I do a bunch of Date/TimeInterval stuff. I do it all in UTC so it just works for me.</p>
<p>I'm struggling with what to use for Android. There's Date (from the beginning of time, ha ha). I guess I could do duration math by converting to/from the <code>time</code> milliseconds attribute. It's not clear to me what zone/rules apply to those.</p>
<p>I see people who seem to use Calendars as Date objects and pass those around. That seems a bit off.</p>
<p>And then there's the new Java 8 java.time stuff which looks pretty complete actually (ZonedDateTime, Duration, etc). But that's API 26 and newer. Is there a back port of this that's reliable?</p>
<p>My needs are pretty basic (I think):</p>
<ul>
<li><p>grab &quot;now&quot; time (in UTC)</p>
</li>
<li><p>be able to subtract two times and get a time delta</p>
</li>
<li><p>be able to subtract a time delta from a time to get a new time</p>
</li>
<li><p>be able to add a time delta to a time to get a new time</p>
</li>
<li><p>be able to display/stringify times in the current/local time zone</p>
<p>... and as a bonus</p>
</li>
<li><p>easily instantiate given UTC times from something like ISO8601 strings, for unit testing purposes</p>
</li>
</ul>
",https://stackoverflow.com/questions/51411714/droid-api-22-options-for-date-duration-in-kotlin,"['android', 'date', 'duration', 'android-5.1.1-lollipop']",247,TRUE,0,1
can&#39;t mock the object in the junit testing,"<p>I have a code below need to do the unit testing</p>

<pre><code>@ManagedBean
@SessionScoped
public class XC implements Serializable {
   public void applyX(){    
       FacesContext context = FacesContext.getCurrentInstance();

       if (!context.isValidationFailed()) {
          try {...
    }
 }
</code></pre>

<p>I wrote a testing code to mock the context. The full class is below.</p>

<pre><code>package com.xyx.abc.admin.view.test;

import static org.mockito.Mockito.when;

import javax.faces.context.FacesContext;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import com.xyx.abc.admin.view.XsltConfig;

@RunWith(PowerMockRunner.class)
@PrepareForTest({FacesContext.class})
public class XsltConfigTest {

  private XsltConfig xc;

  @Mock
  private FacesContext context;

  @Before
  public void setUp() throws Exception {

    xc = new XsltConfig();

    MockitoAnnotations.initMocks(this);

    context = PowerMockito.mock(FacesContext.class);
    when(context.isValidationFailed()).thenReturn(false);
    // PowerMockito.mockStatic(FacesContext.class);
    when(FacesContext.getCurrentInstance()).thenReturn(context);

  }

  /*
   * @Before public void init() { MockitoAnnotations.initMocks(this); }
   */

  @Test
  public void testApplyXslt() {
    String theXml = ""&lt;?xml version=\""1.0\""?&gt;\r\n"" + ""&lt;?xml-stylesheet type=\""text/xsl\"" href=\""example.xsl\""?&gt;\r\n"" + ""&lt;Article&gt;\r\n""
        + ""  &lt;Title&gt;My Article&lt;/Title&gt;\r\n"" + ""  &lt;Body&gt;This is my article text.&lt;/Body&gt;\r\n"" + ""&lt;/Article&gt;"";
    xc.setSampleXml(theXml);
    String theXslt = ""&lt;?xml version=\""1.0\""?&gt;\r\n"" + ""&lt;xsl:stylesheet version=\""1.0\"" xmlns:xsl=\""http://www.w3.org/1999/XSL/Transform\""&gt;\r\n""
        + ""\r\n"" + ""  &lt;xsl:output method=\""text\""/&gt;\r\n"" + ""\r\n"" + ""  &lt;xsl:template match=\""/\""&gt;\r\n""
        + ""    Article - &lt;xsl:value-of select=\""/Article/Title\""/&gt;\r\n"" + ""    Authors: &lt;xsl:apply-templates select=\""/Article/Authors/Author\""/&gt;\r\n""
        + ""  &lt;/xsl:template&gt;\r\n"" + ""\r\n"" + ""  &lt;xsl:template match=\""Author\""&gt;\r\n"" + ""    - &lt;xsl:value-of select=\"".\"" /&gt;\r\n""
        + ""  &lt;/xsl:template&gt;\r\n"" + ""\r\n"" + ""&lt;/xsl:stylesheet&gt;"";
    xc.setSampleXslt(theXslt);
    String theResult = ""Article - My Article"";
    xc.setXsltResult(theResult);


    xc.applyXslt();
    // assertEquals(theResult, xc.getXsltResult());
  }

}
</code></pre>

<p>I always got the below error. It seems it's at the class loading time .</p>

<blockquote>
  <p>java.lang.ClassFormatError: JVMCFRE074 no Code attribute specified;
  class=javax/faces/context/FacesContext, method='&lt;'init'>'()V, pc=0    at
  java.lang.ClassLoader.defineClassImpl(Native Method)  at
  java.lang.ClassLoader.defineClass(ClassLoader.java:346)   at
  java.security.SecureClassLoader.defineClass(SecureClassLoader.java:154)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:727)     at
  java.net.URLClassLoader.access$400(URLClassLoader.java:95)    at
  java.net.URLClassLoader$ClassFinder.run(URLClassLoader.java:1182)     at
  java.security.AccessController.doPrivileged(AccessController.java:686)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:602)   at
  java.lang.ClassLoader.loadClassHelper(ClassLoader.java:846)   at
  java.lang.ClassLoader.loadClass(ClassLoader.java:825)     at
  sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:325)     at
  java.lang.ClassLoader.loadClass(ClassLoader.java:805)     at
  java.lang.Class.forNameImpl(Native Method)    at
  java.lang.Class.forName(Class.java:348)   at
  sun.reflect.generics.factory.CoreReflectionFactory.makeNamedType(CoreReflectionFactory.java:126)
    at
  sun.reflect.generics.visitor.Reifier.visitClassTypeSignature(Reifier.java:137)
    at
  sun.reflect.generics.tree.ClassTypeSignature.accept(ClassTypeSignature.java:61)
    at
  sun.reflect.annotation.AnnotationParser.parseSig(AnnotationParser.java:451)
    at
  sun.reflect.annotation.AnnotationParser.parseClassValue(AnnotationParser.java:432)
    at
  sun.reflect.annotation.AnnotationParser.parseClassArray(AnnotationParser.java:736)
    at
  sun.reflect.annotation.AnnotationParser.parseArray(AnnotationParser.java:543)
    at
  sun.reflect.annotation.AnnotationParser.parseMemberValue(AnnotationParser.java:367)
    at
  sun.reflect.annotation.AnnotationParser.parseAnnotation2(AnnotationParser.java:298)
    at
  sun.reflect.annotation.AnnotationParser.parseAnnotations2(AnnotationParser.java:132)
    at
  sun.reflect.annotation.AnnotationParser.parseAnnotations(AnnotationParser.java:84)
    at java.lang.Class.getAnnotationCache(Class.java:2539)  at
  java.lang.Class.getAnnotations(Class.java:2229)   at
  org.junit.runner.Description.createSuiteDescription(Description.java:123)
    at
  org.junit.internal.runners.ErrorReportingRunner.getDescription(ErrorReportingRunner.java:25)
    at
  org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createUnfilteredTest(JUnit4TestLoader.java:85)
    at
  org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:70)
    at
  org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:43)
    at
  org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:444)
    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)</p>
</blockquote>
",https://stackoverflow.com/questions/49284103/cant-mock-the-object-in-the-junit-testing,"['java', 'junit', 'mockito', 'powermock']",776,FALSE,0,0
how to replace imported modules as stub,"<p>I would like to replace imported modules as stub so as to focus on unit testing only the main module. I've tried using sinon.stub but it seems it's not doing what I expect it to do as I keep on getting an error when running the test.</p>

<pre>
    { Error: Command failed: identify: unable to open image `test.exe': No such file or directory @ error/blob.c/OpenBlob/2724.
    identify: no decode delegate for this image format `EXE' @ error/constitute.c/ReadImage/504.

        at ChildProcess. (/node_modules/imagemagick/imagemagick.js:88:15)
        at ChildProcess.emit (events.js:159:13)
        at maybeClose (internal/child_process.js:943:16)
        at Process.ChildProcess._handle.onexit (internal/child_process.js:220:5) timedOut: false, killed: false, code: 1, signal: null }

</pre>

<p>Here is my main module.</p>

<pre>

    // src/services/identifyService.js
    import imagemagick from 'imagemagick';

    class IdentifyService {
        async identify(filePath) {
            imagemagick.identify(['-format', '%w_%h', filePath], function(err, output) {
                if (err) reject(err);

                return resolve(output);
            });
        }
    }

</pre>

<p>And this is my test.</p>

<pre>

    // test/identifyService.test.js
    import imagemagick from 'imagemagick';
    import IdentifyService from '../src/services/identifyService';

    describe('Verify image processing', () => {
        before(() => {
            const fileInfo = [{page: 1, width:100, height: 100, colorspace: 'RGB'}];
            sinon.stub(imagemagick, 'identify').returns(fileInfo);
        });

        it('returns metadata', (done) => {
            const metadata = IdentifyService.identify('test.exe');
            expect(metadata).to.have.lengthOf(0);
        });
    });

</pre>

<p>Am I doing something wrong here? Any help would be greatly appreciated.</p>
",https://stackoverflow.com/questions/51318875/how-to-replace-imported-modules-as-stub,"['node.js', 'mocha.js', 'sinon']",561,TRUE,0,1
"XAML, MVVM and TwoWay Data Binding","<p>I have the following XAML. I'm using UWP (Universal Windows Platform) but the problem I'd like to describe also applies to other XAML frameworks such as WPF:</p>

<pre><code>&lt;!-- MyVM is a ViewModel --&gt;
&lt;AutoSuggestBox
    QueryIcon=""Find""
    TextChanged=""{x:Bind MyVM.FilterTextChanged}"" 
    Text=""{x:Bind MyVM.FilterText, Mode=TwoWay}""/&gt;
</code></pre>

<p>This is how it works: when the user types text in the <code>AutoSuggestBox</code>, <code>MyVM</code> ViewModel is informed about every key stroke and filters data using <code>FilterText</code>.</p>

<p>This is how <code>MyVM</code> looks like:</p>

<pre><code>// Uses INotifyPropertyChanged from MVVMLight
private string filterText;
public string FilterText
{
    get { return filterText; }
    set { Set(ref filterText, value); }
}

public async void FilterTextChanged()
{
    await LoadData(); // uses FilterText to filter data
}
</code></pre>

<p>The problem arises when I need to modify <code>FilterText</code> value, for example to clear it or to set a pre-defined filter. Thanks to the TwoWay binding, the text in the <code>AutoSuggestBox</code> is displayed correctly but as a ""side-effect"" the <code>FilterTextChanged</code> method is called (because the text has changed). I don't want this ""side-effect"". It is bad from two reasons:</p>

<ol>
<li><p>It makes the ViewModel dependent on XAML in the View. What I mean by that is that although I don't call <code>FilterTextChanged</code>, it is called anyway when I set the <code>FilterText</code> value just because it is TwoWay-bound in XAML.</p></li>
<li><p>It makes automated unit testing impossible. Without XAML, the ViewModel behaves differently: the <code>FilterTextChanged</code> method is not called when I set a <code>FilterText</code> value.</p></li>
</ol>

<p>This is a general problem with XAML, MVVM, and TwoWay binding, not restricted to the specific example with <code>AutoSuggestBox</code>.</p>

<p>How to solve this problem? The main question for me is how to unit test it?</p>
",https://stackoverflow.com/questions/48833256/xaml-mvvm-and-twoway-data-binding,"['wpf', 'unit-testing', 'xaml', 'mvvm', 'uwp-xaml']",470,FALSE,0,1
How to write a unit test,"<p>everyone.</p>

<p>I'm new to unit testing and can't get the idea of it.</p>

<p>I have a module that have a process() function. Inside process() function module does a lot of non-trivial job. The task is to check module's output.</p>

<p>For example, there is a method calculateDistance() inside process() method that calculates distance value. Test requirement sounds like ""check that module calculates distance..."" </p>

<p>As I understand I have to:</p>

<ol>
<li>Prepare input data</li>
<li>Call module's process() method </li>
<li>Calculate distance by hands </li>
<li>Get module's output value for distance</li>
<li>Compare this value to value calculated.</li>
</ol>

<p>But it is easy for some trivial cases, for example some ariphmetical operations. But what if inside calculateDistance() there are lots of formulas. How should I calculate this distance's value? Should I just copy all source code from calculateDistance() function to the test's code to calculate this value from step 3?</p>

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

<pre><code>void process(PropertyList&amp; propList)
{
    m_properties = &amp;propList;
    ...
    for (int i = 0; i &lt; m_properties.propertiesCount; i++)
    {
        calculateDistance();
    }
}

void calculateDistance(int indx)
{
    Property&amp; property = m_properties-&gt;properties[indx];
    property.distance = 0;

    for (int i = 0; i &lt; property.objectsCount - 1; i++)
    {
        property.distance += getDistanceBetweenObjs(i, i + 1);
    }
}

int getDistanceBetweenObjects(indx1, indx2)
{
    // here is some complex algorithm of calculating the distance
}
</code></pre>

<p>So, my question is: should I prepare input data where I know the resulting distance value and just compare this value to the output value? Or should I get input data structures, calculate distance value the same way as calculateDistance() method does (here is code duplication) and compare this value to the output distance? </p>
",https://stackoverflow.com/questions/51970212/how-to-write-a-unit-test,"['c++', 'unit-testing']",79,FALSE,-3,1
Search tree node via closure in Google Apps Script,"<p><strong>General problem I'm trying to solve</strong></p>

<p>I'm trying to implement a search tree in Google Apps Script, sorted by <code>pkgName</code> attribute, with the end purpose of comparing imported metadata on a software project against a Sheet containing similar data. </p>

<p>To keep the namespace of the constructor function from being polluted with ""private"" properties, I used closures. </p>

<p><strong>Implementation</strong> </p>

<p>The implementation I have thus far is thus: </p>

<p><em>SheetDataNode.gs</em></p>

<pre><code>/**
 *  Constructor for a SheetDataNode. Takes one, three, or four arguments.
 *  @param { { package : string, files : { complexity : number, name : string, testingStatus : string }[], rowNumber : number } | string } line data or package name
 *  @param { string } filename : the files contained in package
 *  @param { number } complexity : the total number of branches in the file 
 *  @param { number } rowNumber : the row number as this appears in the spreadsheet it is being created from
 *  @param { string } [ testingStatus ] : the status on the testing of this file. Should be one of the following: NOT_TESTED, FULLY_TESTED, IN_PROGRESS, or PARTIAL
 *  @returns { SheetDataNode }
 *  @deprecated This function is not working right now 
 **/
function SheetDataNode(data, filename, complexity, rowNumber, testingStatus) { 
    var _pkgName = '';
    var _leftChild = null;
    var _rightChild = null;
    var _beenFound = false;
    var _rowNumber = rowNumber;
    var _files = [];

    // if there's only one argument, it better be an object, having the required fields
    if (arguments.length === 1) { 
      // it should have package field
      if ((data.package === undefined) || (data.package !== data.package.toString())) { 
        throw ReferenceError('only one argument was specified, but it is not an object that contains package');
      }
      // it should have files field
      if ((data.files === undefined) || (!Array.isArray(data.files))) { 
        throw ReferenceError('Called from the one-arg constructor, so files should be Array');
      }
      // that files field should itself be an object with the following fields: complexity and name
      for (var idx in data.files) { 
        if (data.files[idx].complexity !== parseInt(data.files[idx].complexity)) { 
          throw TypeError(""complexity should be an integer"");
        }
        if (data.files[idx].name !== data.files[idx].name.toString()) { 
          throw TypeError(""name of file should be a string"");
        }
      }

      // sort the array of files
      data.files.sort(fileSorter)

      // call the initialization function
      return SheetDataNode._init(data.package, data.files, parseInt(data.rowNumber));
    }
    // performing argument checking
    if (filename !== filename.toString()) throw TypeError(""filename is supposed to be a String"")
    if ((complexity !== undefined) &amp;&amp; (complexity !== parseInt(complexity))) { 
      throw TypeError(""complexity must be a number, or undefined"")
    }

  // call the initialization function, constructing a single file object
  return SheetDataNode._init(data.toString(), [{
    complexity : complexity,
    name: filename, 
    testingStatus : testingStatus
  }])
}

// Helper private function that performs initialization
SheetDataNode._init = function(package, files, rowNumber) { 
  // bring in the variables
  var _pkgName = package;
  var _files = files;
  var _leftChild = null;
  var _rightChild = null;
  var _beenFound = false;
  var _rowNumber = rowNumber;

  // providing a function to add file
  _addFile = function(file) { 
    for (var f in _files) { 
      if (file.name &lt; _files[f].name) { 
        _files.splice(f, 0, file)
        return 
      }
    }
    _files.push(file)
  }


  return {
    getRowNumber : function() { return _rowNumber; },
    getPackageName : function () { return _pkgName; },
    getFiles: function() { return _files; },
    addFile : _addFile,
    addFiles : function(files) { 
      if (!Array.isArray(files)) throw TypeError(""files should be an Array"")
      for (var idx in files) { 
        _addFile(files[idx])
      }
    },
    getLeftChild : function() { return _leftChild; },
    setLeftChild : function(node) { 
        _leftChild = node;
    },
    getRightChild : function() { return _rightChild; },
    setRightChild : function(node) { 
        _rightChild = node;
    },
    insertNode : function(node) { 
      // set the current node as the head node
      var currentNode = this;
      // while we are on a non-null node
      while (currentNode) { 
        // if the package of node is the same as that of currentNode
        if (currentNode.getPackageName() === node.getPackageName()) { 
          // simply add the files of node to currentNode._files
          currentNode.addFiles(node.getFiles())
          return
        }
        // if the package of node ""comes before"" that of currentNode, move to the left
        if (currentNode.getPackageName() &gt; node.getPackageName()) { 
          // if the left child of node is defined, that becomes the current node
          if (currentNode.getLeftChild()) currentNode = currentNode.getLeftChild()
          // else construct it, and we're done
          else { 
            currentNode.setLeftChild(node)
            return
          }
        }
        // if the package of node ""comes after"" that of currentNode, move to the right
        if (currentNode.getPackageName() &lt; node.getPackageName()) {
          // if the right child of node is defined, that becomes the current node
          if (currentNode.getRightChild()) currentNode = currentNode.getRightChild()
          // else construct it, and we're done
          else {
            currentNode.setRightChild(node)
            return 
          }
        }
        throw Error(""Whoa, some infinite looping was about to happen!"")
      }
    }
  }

}
</code></pre>

<p><em>UtilityFunctions.gs</em></p>

<pre><code>/**
 *  Sorts file objects by their name property, alphabetically
 *  @param { { name : string } } lvalue
 *  @param { { name : string } } rvalue
 *  @returns { boolean } the lexical comparison of lvalue.name,rvalue.name
 **/ 
function fileSorter(lvalue, rvalue) {
  if (lvalue.name &gt; rvalue.name) return 1;
  return (lvalue.name &lt; rvalue.name) ? -1 : 0;
}
</code></pre>

<p><strong>Problem</strong></p>

<p>I'm unit-testing the code, with the failing test case consisting of the following steps : </p>

<ul>
<li>construct a <code>SheetDataNode</code> <code>node</code></li>
<li>construct another <code>SheetDataNode</code> <code>otherNode</code> with the same package name as the first, but different filename</li>
<li>insert <code>otherNode</code> into <code>node</code></li>
<li>expectation: it now has two files</li>
<li>actual: it only has one: the original.</li>
<li>expectation: neither left nor right child nodes were set by this operation</li>
<li>actual : neither left nor right child nodes were set by this operation</li>
</ul>

<p>The code to do the above looks like this: </p>

<pre><code>  QUnit.test(""inserting a node having the same package as the node it is assigned to"",
             function() { 
               // create the base node
               var node = SheetDataNode(""example"", ""main.go"", 3, 1)
               // insert an other node, with identical package name
               var otherNode = SheetDataNode(node.getPackageName(), ""logUtility.go"", 12, 3)
               node.insertNode(otherNode)
               // node should contain two files, and neither a left child nor a right child
               deepEqual(node.getFiles().map(function(val) { 
                 return val.name
               }), 
                         [""logUtility.go"", ""main.go""], 
                         ""node contains the right file names"")
               equal(node.getFiles().length, 2, ""A package got added to the node"")
               ok(!node.getLeftChild(), ""leftChild still unset"")
               ok(!node.getRightChild(), ""rightChild still unset"")
             })
</code></pre>

<p>Here is screenshot of the failing assertions:</p>

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

<p>Remember that the method under test is like this: </p>

<pre><code>insertNode : function(node) { 
      // set the current node as the head node
      var currentNode = this;
      // while we are on a non-null node
      while (currentNode) { 
        // if the package of node is the same as that of currentNode
        if (currentNode.getPackageName() === node.getPackageName()) { 
          // simply add the files of node to currentNode._files
          currentNode.addFiles(node.getFiles())
          return
        }
        // if the package of node ""comes before"" that of currentNode, move to the left
        if (currentNode.getPackageName() &gt; node.getPackageName()) { 
          // if the left child of node is defined, that becomes the current node
          if (currentNode.getLeftChild()) currentNode = currentNode.getLeftChild()
          // else construct it, and we're done
          else { 
            currentNode.setLeftChild(node)
            return
          }
        }
        // if the package of node ""comes after"" that of currentNode, move to the right
        if (currentNode.getPackageName() &lt; node.getPackageName()) {
          // if the right child of node is defined, that becomes the current node
          if (currentNode.getRightChild()) currentNode = currentNode.getRightChild()
          // else construct it, and we're done
          else {
            currentNode.setRightChild(node)
            return 
          }
        }
        throw Error(""Whoa, some infinite looping was about to happen!"")
      }
</code></pre>

<p>The test against the method <code>addFiles</code>, which has this code:</p>

<pre><code>  QUnit.test(""testing method addFiles"",
             function() { 
               // create the base node
               var node = SheetDataNode(""example"", ""main.go"", 3, 1)
               // create an array of files to add
               const filesToAdd = [{
                 name : 'aFile.go',
                 complexity : 10
               }, {
                 name : 'anotherFile.go',
                 complexity : 10
               }, {
                 name : 'yetAnotherFile.go',
                 complexity : 10
               }]
               // is node.getFiles() an array?!
               ok(Array.isArray(node.getFiles()), ""node.getFiles() is an array"")

               // add the files
               node.addFiles(filesToAdd)
               Logger.log(node.getFiles())
               // node.getFiles() should be an Array
               ok(Array.isArray(node.getFiles()), ""node.getFiles() is still an array"")
               // node.getFiles should now contain filesToAdd
               equal(node.getFiles().length, 1 + filesToAdd.length, ""node.getFiles().length increased by the length of the files to add"")
             })
</code></pre>

<p>passes: </p>

<p><a href=""https://i.stack.imgur.com/Ntaxw.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Ntaxw.png"" alt=""enter image description here""></a>, as do the other tests against <code>insertNode</code>, meaning the problem might exist with how we try to reference <code>currentNode</code> in <code>insertNode</code> for array property modification. <strong>If so, I have no idea how else to reference, in Google Apps Script, the <code>SheetDataNode</code> to undergo state change</strong></p>
",https://stackoverflow.com/questions/53688535/search-tree-node-via-closure-in-google-apps-script,"['unit-testing', 'google-apps-script', 'closures', 'search-tree']",107,TRUE,0,1
"Abstractions, solid and property injection vs constructor injection","<p>I have a discussion with someone at my work. The classes and interfaces look like the following:</p>

<pre><code>public interface ISomeInterface { }

public class ImplementationOfInterface : ISomeInterface { }

public class ClassThatUsesInterface {
    private ISomeInterface _interface;

    public ISomeInterface Interface {
         get =&gt; _interface ?? new ImplementationOfInterface();
         set =&gt; _interface = value;
    }
}
</code></pre>

<p>99% of the time we would use <code>ImplementationOfInterface</code>. The last 1% would probably be unit testing purposes. </p>

<p>I have tried reading up on Dependency Injection, Dependency Inversion Principle, Service, SOLID and a bit more unrelated things like Service Locator pattern/anti-pattern, two step initialization anti-pattern and so on, but have not found anyone describing this way of doing it.</p>

<p>It's half-way clear that the D in SOLID is violated; ""Dependency inversion principle;
one should ""depend upon abstractions, [not] concretions."". Since it's fairly easy to override this in unit tests or switch the implementation if you'd like to... which makes me even more confused about it..</p>

<p>Even tho it might be against the D in SOLID and does not really do anything following proper dependency injection, it's really hard to argue against this usage.</p>

<p>Personally I have suggested to inject the instance through the constructor, but my colleagues thinks this is too much extra work, and don't see the benefits. To be honest, I'm having a hard time not agreeing, but I still have a bad feeling about it.. </p>

<p>Can you come up with articles or powerful arguments for and against the use of this particular ""hack""?</p>
",https://stackoverflow.com/questions/53190580/abstractions-solid-and-property-injection-vs-constructor-injection,"['c#', 'oop', 'design-patterns', 'architecture']",714,TRUE,0,2
Efficiently test events with Jasmine,"<p>I'm testing a rather large project, and everything is fine except for events (that is EventEmitter / event.js from node) where I have to change the environment to get different outcomes from the same event.</p>

<p>My current setup looks as follows:</p>

<pre><code>beforeEach((done)=&gt; {
        //&lt;sets up some stuff&gt; 


       //&lt;sets up spies &gt;

        &lt;the_Event_Emitter&gt;.emit('keyword1');


        setTimeout(() =&gt; {
            done();
        },1);

    });
</code></pre>

<p>and then in the specs are just the expects.</p>

<p>Which works perfectly but I'd have to write an entire describe-Block with a specific beforeAll-block for EVERY variant to the environment (the event in question has a switch-case over some variable)</p>

<p>making the beforeEach-block look like this:</p>

<pre><code>&lt;the_Event_Emitter&gt;.emit('keyword1');
&lt;change Environment&gt;
&lt;the_Event_Emitter&gt;.emit('keyword1');
...
</code></pre>

<p>would ""work"" but is unacceptably unclean, with calls leaking into the wrong specs etc.</p>

<p>Is there a decent way of doing this?
The waitFor() from the old (pre 2.0) Jasmine would have solved ALL my problems with ease.</p>

<p>[I tried having no beforeEach ( the .emit etc. within the spec) but that doesnt work since events run asynchronously, so the code in question is run AFTER the expects have been tried (and failed becuase the code hasn't run yet)]</p>

<p>EDIT: 
I now ""did"" it by setting the environment in the previous test.
Which is fine as long as the tests run all and in order (which is not proper unit testing as fas as I know...)</p>
",https://stackoverflow.com/questions/49299157/efficiently-test-events-with-jasmine,"['javascript', 'node.js', 'unit-testing', 'testing', 'jasmine']",107,FALSE,0,0
Reading top command causing py.test to fail in Python27,"<p>I am unit testing my application with py.test and am running into false test failures for this specific piece of code:</p>

<pre><code># get current cpu usage in %
def get_cpu_use_perc(self):
    cpu_use = os.popen(""top -n1 | awk '/Cpu\(s\):/ {print $2}'"").readline().strip('\\')
    print('-DBG- CPU Use call from terminal returns: {}'.format(cpu_use))
    self._cpu_use = float(cpu_use)
    return self._cpu_use
</code></pre>

<p>I am pretty new to py.test, so I'm not too sure how to fix this. I have tested this specific function separately and it returns a number as I would expect. Looking through the documentation, it looks like there are issues when trying to use stdout. I have tested other code that uses os.popen('command_here').readline() and that works fine, so I assume it has to do with top.</p>

<p>What about this command is causing the test to fail? Is there a better way to get the CPU usage on a raspberry pi without using top that will work with py.test? Is there a marker or something I can add to allow the tool to capture the information I want?</p>

<p><strong>EDIT</strong>: Here is an update for code snippet for the unit test:</p>

<pre><code>import time
from system_monitor import system_monitor

# create object
sys_mon = system_monitor()

# simplified unit test
def test_memory(num_checks=20):
    cpu_use_perc = sys_mon.get_cpu_use_perc()

    assert float(cpu_use_perc)  &lt; 5.0  # tested CPU usage, too high for testing
</code></pre>

<p>When I run this unit test from the command line, I see:</p>

<pre><code>&gt;&gt;&gt;sudo python test_sys_mon.py
-DBG- CPU Use call from terminal returns: 3.2
</code></pre>

<p>When I run my test suite using py.test integrated with setup.py, I see:</p>

<pre><code>&gt;&gt;&gt;sudo python setup.py test
--- other test stuff passing here that is not important...
...
&gt;           cpu_use_perc = sys_mon.get_cpu_use_perc()                                                   

src/system_monitor/test/test_sys_mon.py:128:                                                                                                                                                    
</code></pre>

<hr>

<pre><code>self = &lt;system_monitor.system_monitor.system_monitor object at 0xb58a6ad0&gt;                                             

def get_cpu_use_perc(self):                                                                                        
    cpu_use = os.popen(""top -n1 | awk '/Cpu\(s\):/ {print $2}'"").readline().strip('\\')                            
    print('-DBG- CPU Use call from terminal returns: {}'.format(cpu_use))                                          
&gt;   self._cpu_use = float(cpu_use)                                                                                 
E   ValueError: could not convert string to float:                                                                 

src/system_monitor/system_monitor.py:50: ValueError                                                                    
------------------------- Captured stdout call -----------------------------

-DBG- CPU Use call from terminal returns:                                                                              
------------------------- Captured stderr call -----------------------------
</code></pre>

<p>It looks like this <code>os.popen()</code> is returning an empty string, but I'm not sure how to fix this so I can use the top command with py.test</p>
",https://stackoverflow.com/questions/52798392/reading-top-command-causing-py-test-to-fail-in-python27,"['python', 'raspberry-pi', 'pytest']",61,FALSE,0,1
Resolve Dependency in unit test cases angular 4 in a layered structure,"<p>I am new to angular and working on Unit test case for my project. I went through some articless <a href=""https://codecraft.tv/courses/angular/unit-testing/overview/"" rel=""nofollow noreferrer"">Unit Testing</a></p>

<p><a href=""https://angular.io/guide/testing"" rel=""nofollow noreferrer"">    </a></p>

<p>After reading these articles when I try to write unit test case for my project i am not able to resolve dependency in my test cases. As I have a layered structure and when I inject dependency in my test cases  which in turn are calling other layer there dependency are not resolved. I am not able to find out how to resolve the dependency to execute the test case.</p>

<p>I have a LoginComponent class
a AuthService class
and a HttpService class</p>

<p><pre><code></p>

<pre><code>    import { Component, OnInit } from '@angular/core';
import {Router} from '@angular/router';
import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms';
import { HttpService } from '../../common/services/http.service';
import {LocalStorageService} from '../../common/services/local-storage.service';
import { AuthService } from '../../common/services/auth.service';
import {PathConfig} from '../../common/config/path.config';
import { ToastrService } from 'ngx-toastr';

@Component({
  selector: 'app-user-login',
  styleUrls: ['./login.component.scss'],
  templateUrl: './login.component.html'
})
export class LoginComponent implements OnInit {
  public loginForm: FormGroup;
  public submitted: boolean;

  constructor(private router: Router, 
              private httpService: HttpService,
              private localStorageService: LocalStorageService,
              private authService: AuthService,
              private toastr: ToastrService) {}

  ngOnInit () {
    this.loginForm = new FormGroup({
      name: new FormControl('testmarion', [Validators.required]),
      pwd: new FormControl('testmarion', [Validators.required])
    });
  }

  doLogin(value: any, isValid: boolean ) {
    if (isValid) {
      this.authService.login(PathConfig.LOGIN, value)
      .then((data:any)=&gt; {
           this.localStorageService.set(""userInfo"",JSON.stringify(data.response));
           this.localStorageService.set(""AuthToken"",data.response.AccessToken);
           this.router.navigate(['/home']);
      }).
      catch(err =&gt; {
        this.toastr.error(err.message);
  });

    }
  }
}
</code></pre>

<p></pre></code></p>

<p><pre><code></p>

<pre><code>import { Injectable }     from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {LocalStorageService} from ""./local-storage.service"";
import {ConstantConfig} from ""../config/constant.config"";
import {HttpHeaders} from ""@angular/common/http"";

@Injectable()

@Injectable()
export class AuthService {
    constructor ( private http:HttpClient , private localStorage:LocalStorageService) {}
    //Auth REQUEST
    login(url,obj: Object): Promise&lt;any&gt;{
      let body = JSON.stringify(obj); 
       let modifyUrl = url +'?userName='+obj['name']+'&amp;'+'password='+obj['pwd'];
        return this.http.get(modifyUrl)
        .toPromise()
        .then((res:any) =&gt; {
          console.log(res);
         return ({'response':res})
        }).catch((error:any) =&gt; { return Promise.reject( error || 'Server error')}  )
    }

    //check login status
   isLoggedIn():boolean{
       var data = this.localStorage.get(ConstantConfig.AUTH_TOKEN);
       return data ? true : false ;
   }
}
</code></pre>

<p></pre></code>    </p>

<p><pre><code></p>

<pre><code>import {Injectable, Inject}     from '@angular/core';
import {HttpClient, HttpParams} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

import {LocalStorageService} from ""./local-storage.service"";
import {ConstantConfig} from ""../config/constant.config"";

@Injectable()
export class HttpService {
  // Resolve HTTP using the constructor
  constructor (private http: HttpClient ,@Inject(LocalStorageService)private localStorage:LocalStorageService) {}

  // GET REQUEST
  get(url) : Observable&lt;any&gt;{

    // Create a request option
    let options = {
      headers: {
        'Content-Type':'application/json',
         'Authorization': this.localStorage.get(ConstantConfig.AUTH_TOKEN)
      },

    };

    //using get request
   // return this.http.get(url,options)
   return this.http.get(url)
    // and calling .json() on the response to return data
      .map((res:any) =&gt; res ).catch((err:any) =&gt; Observable.throw(err['error'] || err || 'Server error'))

  }

  //POST REQUEST
  post(url,obj: Object): Observable&lt;any&gt; {
      let body    = obj
      let options = { headers: {
          'Content-Type':'application/json',
          'Authorization': this.localStorage.get(ConstantConfig.AUTH_TOKEN)
      } }; // Create a request option

    //using post request
    return this.http.post(url, body, options) //using post request
      .map((res:any) =&gt; res ) //and calling .json() on the response to return data
      .catch((err:any) =&gt;  Observable.throw(err['error'] || err || 'Server error')); //errors if any
  }


}
</code></pre>

<p></pre></code></p>

<p>the doLogin function in component class calls the login function in the AuthService class which calls the get method of httpservice to make a api hit.</p>

<p>I am trying to create unit test case for doLogin function.
For this in login.component.spec.ts file what I tried is created an instance of login component by injecting dependencies in the constructor now when I call the doLogin function with my object in my unit test I get the error that cannot call Login function of undefined. Same case is when I use TestBed.</p>

<p>I am not able to figure out how do I resolve the dependencies of the services. </p>
",https://stackoverflow.com/questions/49234033/resolve-dependency-in-unit-test-cases-angular-4-in-a-layered-structure,"['angular', 'karma-jasmine']",708,FALSE,0,1
"TypeScript: Could not find a declaration file for module in unit tests, only","<p>I'm using TypeScript with Visual Studio Code on Windows 10 to develop an NPM module. I use mocha/chai combined with nyc (istanbul) for unit testing and code coverage.</p>

<p>For some of my tests I would like to use chai-bytes to compare buffers more easily. Unfortunately, there is no type definition file in the chai-bytes module and there is no definition at @types/chai-bytes available.</p>

<p>Therefore, I have written my own type definition file for the chai-bytes plugin (which is very simple), but during execution of <code>npm test</code> I get the following error:</p>

<pre><code>TSError: ⨯ Unable to compile TypeScript:
test/utls/BitArray-test.ts(3,23): error TS7016: Could not find a declaration file for module 'chai-bytes'. 'C:/Users/&lt;user&gt;/Source/Repos/velux-api/node_modules/chai-bytes/index.js' implicitly has an 'any' type.
  Try `npm install @types/chai-bytes` if it exists or add a new declaration (.d.ts) file containing `declare module 'chai-bytes';`
test/utls/BitArray-test.ts(48,38): error TS2339: Property 'equalBytes' does not exist on type 'Assertion'.
</code></pre>

<p>VS Code provides me with full Intellisense, so I think my type definition file works and is found at least by VS Code.</p>

<p>This is my directory structure:</p>

<pre><code>dist\              &lt;-- My compiled code goes here
  utils\
    BitArray.d.ts
    BitArray.js
    BitArray.js.map
  index.d.ts
  index.js
  index.js.map
  ...
src\
  utils\
    BitArray.ts
  index.ts
  ...
test\
  utils\
    BitArray-test.ts
  ... (other test files)
  mocha.opts
types\
  chai-bytes\
    index.d.ts       &lt;-- Type definition file for 'chai-bytes'
</code></pre>

<p>I have tried to move the type definition file to the source tree (several places), but with no effect, besides, that sometimes it got even worse, so that even VS Code haven't found it anymore.</p>

<p>These are my config files:</p>

<p>package.json:</p>

<pre class=""lang-js prettyprint-override""><code>{
      ""name"": ""klf-200-api"",
      ""version"": ""3.0.0"",
      ""description"": ""This module provides a wrapper to the socket API of a Velux KLF-200 interface. You will need at least firmware 0.2.0.0.71 on your KLF interface for this library to work."",
      ""main"": ""dist/index.js"",
      ""types"": ""dist/index.d.ts"",
      ""author"": {
        ""name"": ""Michael Schroeder""
      },
      ""dependencies"": {
        ""@types/promise-timeout"": ""^1.3.0"",
        ""promise-timeout"": ""^1.3.0""
      },
      ""devDependencies"": {
        ""@types/chai"": ""^4.1.6"",
        ""@types/chai-as-promised"": ""^7.1.0"",
        ""@types/mitm"": ""^1.3.2"",
        ""@types/mocha"": ""^5.2.5"",
        ""@types/node"": ""^10.11.7"",
        ""@types/sinon"": ""^5.0.7"",
        ""@types/sleep"": ""0.0.7"",
        ""babel-eslint"": ""^8.0.0"",
        ""chai"": ""^4.1.0"",
        ""chai-as-promised"": ""^7.1.1"",
        ""chai-bytes"": ""^0.1.1"",
        ""chai-sinon"": ""^2.8.1"",
        ""cross-env"": ""^5.2.0"",
        ""eslint"": ""^4.7.1"",
        ""eslint-config-defaults"": ""^9.0.0"",
        ""eslint-plugin-react"": ""^7.3.0"",
        ""gulp"": ""^4.0.0"",
        ""gulp-release-it"": ""^2.0.14"",
        ""gulp-typescript"": ""^5.0.0-alpha.3"",
        ""gulp-uglify"": ""^3.0.1"",
        ""istanbul"": ""^0.4.5"",
        ""mitm"": ""^1.4.0"",
        ""mocha"": ""^3.4.2"",
        ""nock"": ""^9.0.14"",
        ""nyc"": ""^13.1.0"",
        ""sinon"": ""^7.1.1"",
        ""sleep"": ""^5.2.3"",
        ""source-map-support"": ""^0.5.9"",
        ""ts-mocha"": ""^2.0.0"",
        ""ts-node"": ""^7.0.1"",
        ""typescript"": ""^3.1.2"",
        ""uglify-es"": ""^3.3.9""
      },
      ""scripts"": {
        ""test"": ""cross-env TS_NODE_FILES=true nyc mocha"",
        ""document"": ""jsdoc src -r -c ./.jsdoc.json -d docs""
      },
      ""nyc"": {
        ""include"": [
          ""src/**/*.ts"",
          ""src/**/*.tsx""
        ],
        ""extension"": [
          "".ts"",
          "".tsx""
        ],
        ""exclude"": [
          ""**/*.d.ts""
        ],
        ""reporter"": [
          ""text-summary"",
          ""html""
        ],
        ""all"": true
      },
      ""repository"": {
        ""type"": ""git"",
        ""url"": ""https://github.com/MiSchroe/klf-200-api""
      },
      ""keywords"": [
        ""klf-200"",
        ""IoT""
      ],
      ""license"": ""MIT"",
      ""bugs"": {
        ""url"": ""https://github.com/MiSchroe/klf-200-api/issues""
      },
      ""homepage"": ""https://mischroe.github.io/klf-200-api/""
    }
</code></pre>

<p>tsconfig.json:</p>

<pre class=""lang-js prettyprint-override""><code>{
  ""compilerOptions"": {
    /* Basic Options */
    ""target"": ""es6"",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
    ""module"": ""commonjs"",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    ""declaration"": true,                   /* Generates corresponding '.d.ts' file. */
    ""sourceMap"": true,                     /* Generates corresponding '.map' file. */
    ""outDir"": ""./dist"",                        /* Redirect output structure to the directory. */

    /* Strict Type-Checking Options */
    ""strict"": true,                           /* Enable all strict type-checking options. */
    ""noImplicitAny"": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */

    /* Module Resolution Options */
    ""esModuleInterop"": true                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
  },
  ""include"": [
    ""./src/**/*""
  ]
}
</code></pre>

<p>mocha.opts:</p>

<pre><code>--require ts-node/register
--require source-map-support/register
--recursive
--full-trace
--bail
test/**/*.ts
</code></pre>

<p>types\chai-bytes\index.d.ts:</p>

<pre class=""lang-js prettyprint-override""><code>/// &lt;reference types=""chai"" /&gt;

declare module ""chai-bytes"" {
    function chaiBytes(chai: any, utils: any): void;

    export = chaiBytes;
}

declare namespace Chai {

    // For BDD API
    interface Assertion extends LanguageChains, NumericComparison, TypeComparison {
        equalBytes(expected: string | Array&lt;number&gt; | ArrayLike&lt;number&gt;): void;
    }

}
</code></pre>

<p>BitArray-test.ts (only the relevant test):</p>

<pre class=""lang-js prettyprint-override""><code>import { expect } from ""chai"";
import { bitArrayToArray, arrayToBitArray } from ""../../src/utils/BitArray"";
import chaibytes from ""chai-bytes"";

'use strict';

chai.use(chaibytes);

describe(""..."", function() {
            it(""should return an the correctly filled buffer"", function() {
                const nums: number[] = [0, 2, 4, 6, 8, 10, 12, 14];
                const result = arrayToBitArray(nums, 2);

                expect(result).to.be.an.instanceof(Buffer);
                expect(result).to.be.equalBytes([0x55, 0x55]);
            });
});
</code></pre>

<p><code>npm --version</code>:
<code>3.10.10</code></p>

<p><code>node --version</code>:
<code>v6.11.1</code></p>

<p>I could use <code>Buffer.compare</code> as work-around instead, but then I wouldn't see the buffers' content in the error message but only a <code>-1</code>, <code>0</code> or <code>1</code>. (And it wouldn't solve the problem.)</p>

<p>Currently, I'm stuck at that point and any help is much appreciated.</p>
",https://stackoverflow.com/questions/53496973/typescript-could-not-find-a-declaration-file-for-module-in-unit-tests-only,"['node.js', 'typescript', 'mocha.js', 'chai', 'nyc']",26645,TRUE,6,1
How do I enable Code Coverage for .NET Standard Library (2.0) project in VSTS (CI),"<p>Please help me - How do I enable/show code coverage result for .NET Standard library project (2.0) in VSTS (CI). Have enable Test result through <strong>dotnet Test task</strong> (.NET Core 2.0 preview) and able to to see the passed Test cases. Next step I have added ""publish result"" task but it's showing the below warning during Build -
<strong><em>No test result files matching _temp*</em>/<em>.trx were found</strong>.</em>
Even I have modified the .csproj file and added <code>&lt;DebugType&gt;Full&lt;/DebugType&gt;</code>.</p>

<p>Using Visual Studio 2017 Professional (version - 15.5.2) 
Project - .NET Standard Library (2.0)
Unit Test - MSTest (inbuilt in Visual Studio)</p>

<p>What tasks / how tasks should I need to add/modify in Build Definition in VSTS, so that I can see Code Coverage against Unit Testing.</p>

<p>Tasks for Code Coverage -
<a href=""https://i.stack.imgur.com/e3o5m.png"" rel=""noreferrer"">TestAssemblies</a></p>

<p><a href=""https://i.stack.imgur.com/9KnSq.png"" rel=""noreferrer"">other option</a></p>

<p>Now I am able to see the Code Coverage (not sure whether correct code coverage is showing or not) but the tasks - Test Assemblies ***.test*.dll is failing with the below error -
<a href=""https://i.stack.imgur.com/F7Iq1.png"" rel=""noreferrer"">Code-Coverage-Result</a></p>

<ul>
<li><p>No test is available in .........$(BuildConfiguration)\netcoreapp2.0\Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.dll. Make sure test project has a nuget reference of package ""Microsoft.NET.Test.Sdk"" and framework version settings are appropriate and try again.</p>

<ul>
<li>No test is available in ...... $(BuildConfiguration)\netcoreapp2.0\Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.dll. Make sure test project has a nuget reference of package ""Microsoft.NET.Test.Sdk"" and framework version settings are appropriate and try again.</li>
</ul></li>
</ul>

<p>Thanks.</p>

<p>Regards,
Deb</p>
",https://stackoverflow.com/questions/48253711/how-do-i-enable-code-coverage-for-net-standard-library-2-0-project-in-vsts-c,"['.net', 'unit-testing', 'azure-devops', 'azure-pipelines', 'azure-pipelines-build-task']",2787,TRUE,5,1
UWP MVVM Template10: Access single instance of external API across application,"<p>I've been tasked with taking over a partially developed sizeable and complex UWP application using MVVM via Template 10.  The app needs to use an in-house developed webservices API and this needs to be used for practically every single function, starting with the initial login page.  </p>

<p>So given I need to access a single instance of the API everywhere how do I go about doing that correctly?  I've used MVVM a fair bit but never used Template10 and never had to share an instance of an object across an entire MVVM UWP app before.</p>

<p>So far I can think of three ways:</p>

<ol>
<li>Declare and instantiate API instance in Appl.xaml.cs and use it globally</li>
<li><p>Create a public Globals class and have the instance as a public static property:
<code>c#
public class Globals
{
    private static OurAPI _ourAPI;
    public static OurAPI API
    {
        get { return _ourAPI; }
        set { _ourAPI = value; }
    }
}
</code></p></li>
<li><p>Instantiate the API in the login page and then pass it as a parameter between ViewModels, presumably using the Navigation service.</p></li>
</ol>

<p>I'm thinking 1 or 2 are most likely not MVVM compliant and could cause unit testing issues so maybe 3 is the best option? Or is there another, more correct way to do this to adhere to Template10/MVVM concepts and also be able to unit test it?</p>

<p>EDIT: Sorry about the code not formatting, the edit box formats it Ok but when I save it it goes back to one long sentence :-(</p>
",https://stackoverflow.com/questions/52286523/uwp-mvvm-template10-access-single-instance-of-external-api-across-application,"['c#', 'mvvm', 'uwp', 'template10', 'uwp-navigation']",283,TRUE,3,1
Mock in unit test returns null at LINQ.Where,"<p>I have two classes <code>Beam</code> and <code>Treatment</code> that I want to match with their value <code>DateTime TimeStamp</code>. So in my code I have a LINQ <code>.Where()</code> to search for a special TimeStamp and compare it to a pre-sorted list. With real data it workes very good and without any errors, but now I was told to write a unit test for this class and with <code>Moq</code> I don't get the expected result.</p>

<p>The line in my code, where it doesn't work is this:</p>

<pre><code>Treatment searchedBeam = (Treatment)InputData.Treatments.
    Where(beam =&gt; beam.TimeStamp == sortingList[j + i * rangeOfBeams]).FirstOrDefault();
</code></pre>

<p>The <code>i,j</code> are indices from for-loops and run correctly as I saw in debug mode.</p>

<p>In my unit testing code I have this:</p>

<pre><code>Mock&lt;ITreatmentGroup&gt; treatGroupMock1;
[SetUp]
public override void Init()
{
    base.Init();

    // --- Create Plan Mock
    // some code here

    // --- Create Treatment Mock
    DateTime time1 = new DateTime(2000, 01, 01, 12, 00, 00);
    DateTime time2 = new DateTime(2000, 01, 01, 13, 00, 00);

    Mock&lt;ITreatment&gt; treatMock1 = new Mock&lt;ITreatment&gt;();
    treatMock1.Setup(t =&gt; t.TimeStamp).Returns(time1);
    Mock&lt;ITreatment&gt; treatMock2 = new Mock&lt;ITreatment&gt;();
    treatMock2.Setup(t =&gt; t.TimeStamp).Returns(time2);

    treatGroupMock1 = new Mock&lt;ITreatmentGroup&gt;();
    treatGroupMock1.Setup(tg =&gt; tg.Treatments).Returns(new List&lt;ITreatment&gt;() { treatMock1.Object, treatMock2.Object });
}
</code></pre>

<p>In debugging I checked that the mocked data are in same structure as the real data. But then comes my test code:</p>

<pre><code>[Test]
public void Matched_MatchedAndSortedPlan_FunctionCheck()
{
    IPlan result = Matched.MatchedAndSortedPlan(_planMock.Object, _treatGroupMock1.Object, out IList&lt;string&gt; errors);

    Assert.IsEmpty(errors);
    Assert.IsNotNull(result);
    Assert.IsTrue(result.FractionGroups[0].Beams.Any(f =&gt; f.BeamName == ""beamMock1""));              
}
</code></pre>

<p>So I'm calling my method with mocked data and as with real data it should work, but as I mentioned the line with the LINQ expression returns <code>null</code> so the <code>Assert</code> commands let the unit test fail.</p>

<p>The biggest hint I got is that there are some problems with mocking LINQ expressions, but I don't want to mock a LINQ expression but use it for my solution. Other questions here like <a href=""https://stackoverflow.com/questions/45013575/linq-firstordefault-on-a-mocked-list"">this</a> or <a href=""https://stackoverflow.com/questions/38714152/moq-unit-testing-of-linq-find-results-in-nullreferenceexception"">this</a> that Google presented me as first hits of my search, I think don't work here.</p>

<p>I hope you have another clue or hint for me.</p>
",https://stackoverflow.com/questions/49624763/mock-in-unit-test-returns-null-at-linq-where,"['c#', 'linq', 'unit-testing', 'mocking', 'moq']",883,TRUE,2,1
MyBatis - How to unit test result maps?,"<p>The mybatis documentation states:</p>

<blockquote>
  <p>Always build ResultMaps incrementally. Unit tests really help out here. If you try to build a gigantic resultMap like the one above all at once, it's likely you'll get it wrong and it will be hard to work with. Start simple, and evolve it a step at a time. And unit test! The downside to using frameworks is that they are sometimes a bit of a black box (open source or not). Your best bet to ensure that you're achieving the behaviour that you intend, is to write unit tests. It also helps to have them when submitting bugs. </p>
</blockquote>

<p>However at no point in the documentation do they explain how to unit test resultMaps. On their github wiki they have <a href=""https://github.com/mybatis/mybatis-3/wiki/Unit-Test"" rel=""nofollow noreferrer"">a page on unit testing</a> but it seems to be more geared towards contributors rather than users. How do I write unit tests for result maps as they recommend when it seems like I would need to build a fully functional in memory database just to test mappings? </p>

<p>Needing an in memory db sounds more like an integration test than a unit test and if any of my queries use db specific SQL statements like SQL Server T-SQL statements it couldn't properly test on an in memory db of a different type. Am I misunderstanding something?</p>
",https://stackoverflow.com/questions/53658154/mybatis-how-to-unit-test-result-maps,"['unit-testing', 'mybatis']",1123,TRUE,2,1
Mongodb aggregation is slow only on Spring Data,"<p>I am using Spring Boot 2 with Spring Data and a local Mongodb 3.4.
I currently have a collection with ~200k documents, properly indexed via Spring's annotations.</p>

<p>I've crafted an aggregation pipeline (seen at the bottom of this post) which takes around <strong>2000ms</strong> to complete in: Python, Studio3T, <strong>Spring Boot unit tests</strong>.</p>

<p>When I run the very same query normally on a <strong>deployed instance of my application(bootJar)</strong>, it takes <strong>8000ms</strong> which is not acceptable for my use case and is also very weird.</p>

<p>The database logs report query times of ~300ms in all cases so the db is performing fine.</p>

<p>It is very interesting to find out why this happens since the code in a normal deployment and during unit testing is exactly the same (also using the same parameters), and therefore should be comparable in performance.  </p>

<p>My guess goes as far as that the configuration differs between deployment and testing. I use the default settings on both environments (no specific bean declarations for mongo, just autowiring <code>MongoOperations</code> and enjoying the ""Boot magic"").</p>

<hr>

<p>Here are some samples:</p>

<p>A document looks like this:</p>

<pre><code>{ 
  ""_id"" : ObjectId(""5b4f76696d370f30d401f246""), 
  ""description"" : ""IoT420"", 
  ""timestamp"" : NumberLong(1530286316), 
  ""sensor"" : ""Temperature"", 
  ""value"" : 30.02, 
  ""class"" : ""net.derp.iot.piws.entities.dto.MongoMeasurementRepr""
}
</code></pre>

<p>The aggregation pipeline:</p>

<pre><code>Aggregation aggregation = newAggregation(
            match( where( ""description"" ).is( filterDescription ) ),
            match( where( ""sensor"" ).is( sensorName ) ),
            match( where( ""timestamp"" ).gte( tsFrom ).lte( tsTo ) ),
            sort( Sort.Direction.ASC, ""timestamp"" ));
</code></pre>

<p>This aggregation returns around 120k documents.</p>

<p>I use <code>System.nanoTime()</code> to measure time.</p>

<hr>

<p><strong>Update</strong>: After removing <code>runtime('org.springframework.boot:spring-boot-devtools')</code> the time dropped to <strong>5000ms</strong>, which is still slower than the testing case. I suspect some sort of ""validation"" that gets disabled during testing.</p>
",https://stackoverflow.com/questions/51410704/mongodb-aggregation-is-slow-only-on-spring-data,"['spring', 'mongodb', 'spring-boot', 'spring-data', 'spring-data-mongodb']",1667,TRUE,2,2
Undefined Reference to weak functions (Static Library + GCC),"<p><strong>Hello everybody.
First, I would like to introduce my problem to you all!</strong></p>

<p>I am using Atollic TrueStudio to develop an Embedded System. In this system, I have a driver layer (built as a static library. This library contains basically the STM32 HAL, and this library contains A LOT of weak functions).
These library is being compiled with ARM GCC and works great. I can link it in other projects and it does work as it should.</p>

<p><strong>The second part is the problem, because I want to implement Unit Testing in the project!</strong></p>

<p>For this, I have created another configuration for the same Driver Layer static library (the one with STM32 HAL code), but this time I'm compiling it with MinGW.
The compilation works, but when I Try to link this library into another project (an executable project). The Linker returns ""undefined reference to ..."" (Image below).</p>

<p>PS: The problem is with the Linker, since the project finds where the weak function is declared. It can not find where it's defined though!</p>

<p><strong>Edit</strong></p>

<p><strong>This is the main code</strong></p>

<pre><code>#include &lt;MbedOS/platform/mbed_error.h&gt;

int main(void)
{
   error(""Stream obj failure, errno=%d\r\n"",

   return 0;
}
</code></pre>

<p><strong>This is where the function is defined (inside the static library) mbed_error.c</strong></p>

<pre><code>#include &lt;MbedOS/platform/mbed_error.h&gt;

static uint8_t error_in_progress = 0;

WEAK void error(const char* format,
                ...)
{

   // Prevent recursion if error is called again
   if (error_in_progress)
   {
      return;
   }

   error_in_progress = 1;

   #ifndef NDEBUG
      va_list arg;
      va_start(arg,
               format);
      mbed_error_vfprintf(format,
                          arg);
      va_end(arg);
   #endif

   exit(1);
}
</code></pre>

<p><strong>This is mbed_error.h file</strong></p>

<pre><code>#ifdef __cplusplus
extern ""C""
{
#endif
void error(const char* format,
           ...);

#ifdef __cplusplus
}
#endif
</code></pre>

<p><strong>And this is the result from the console</strong></p>

<pre><code>13:45:44 **** Build of configuration Debug for project testeLINKER ****
make all 
gcc -o ""testeLINKER.elf""  ./src/main.o   -lSTM32F7_Driver_Layer -L""E:\TrueStudio_Projects\STM32F7_Driver_Layer\Projeto\TrueStudio\UnitTestLibrary""
./src/main.o: In function `main':
E:\TrueStudio_Projects\testeLINKER\Debug/../src/main.c:33: undefined reference to `error'
collect2.exe: error: ld returned 1 exit status
make: *** [testeLINKER.elf] Error 1

13:45:44 Build Finished (took 460ms)
</code></pre>

<p><strong>Edit 2 
 The nm output for the static library follows (just one of the files with a weak function)</strong> </p>

<pre><code>    C:\Program Files (x86)\Atollic\TrueSTUDIO for STM32 9.0.0\PCTools\bin&gt;nm E:\TrueStudio_Projects\STM32F7_Driver_Layer\Projeto\TrueStudio\UnitTestLibrary\Source\MbedOS\platform\mbed_error.o
00000000 b .bss
00000000 d .data
00000000 N .debug_abbrev
00000000 N .debug_aranges
00000000 N .debug_info
00000000 N .debug_line
00000000 r .eh_frame
00000000 r .rdata$zzz
00000000 t .text
00000000 T .weak._error.
         w _error
00000000 b _error_in_progress
         U _exit
         U _mbed_error_vfprintf
</code></pre>
",https://stackoverflow.com/questions/50105078/undefined-reference-to-weak-functions-static-library-gcc,"['c++', 'c', 'gcc', 'static', 'linker']",894,TRUE,1,1
xUnit testing Servicestack AutoQuery,"<p>first time using AutoQuery and I have this problem with unit testing after implementing AutoQuery. It works fine through Swagger manual testing. So I have a get method like this:</p>

<pre><code>public class ItemService : Service
{
public IAutoQueryDb AutoQuery { get; set; }
private readonly IRepository&lt;Item&gt; itemRepository;

public ItemService(IRepository&lt;Item&gt; itemRepository)
    {
        this.itemRepository = itemRepository;
    }

public ItemResponse Get(FindItems query)
    {
        var response = new ItemResponse();
        var q = AutoQuery.CreateQuery(query, Request);
        q.Where(x =&gt; !x.IsDeleted);
        response.Offset = q.Offset.GetValueOrDefault(0);
        response.Total = (int)itemRepository.CountByCondition(q);
        var queryResult = AutoQuery.Execute(query, q).Results;
        foreach (var item in queryResult)
        {
            response.MultipleResult.Add(item.ToDto());
        }
        return response;
    }
}
</code></pre>

<p>The request/response are built like this:</p>

<pre><code>[Route(""/item/{Id}"", ""GET"")]
public class Items : IReturn&lt;ItemResponse&gt;
{
    public Items() : base()
    {
    }
    public int Id { get; set; }
}

[Route(""/item"", ""GET"")]
public class FindItems : QueryDb&lt;Item&gt;
{
    public int[] Ids { get; set; }
    public string NameContains { get; set; }
}
public class ItemResponse : BaseResponse&lt;ItemDto&gt;
{
    public ItemResponse()
    {
        MultipleResult = new List&lt;ItemDto&gt;();
    }
}
</code></pre>

<p>and the test:</p>

<pre><code>public void GetAllItems()
    {
        SeedDatabase();
        var service = appHost.Container.Resolve&lt;ItemService&gt;();
        var request = new rq.FindItems();
        var response = service.Get(request);
        Assert.NotNull(response);
        Assert.Empty(response.MultipleResult);
    }
</code></pre>

<p>The problem is that Request inside CreateQuery method remains null (when I run the app, it's properly filled). So what should I do in xunit test to get Request to be proper object instead of null? Ofc I get null exception on test execution. Is there any mechanism to preset the Request? Thanks for any help.</p>

<p>//////UPDATE:
I tried different approach as suggested using built-in client:</p>

<pre><code>[Fact]
    public void CanGetAll()
    {
        var client = new JsonHttpClient(BaseUri);
        var all = client.Get(new FindItem());
        Assert.Empty(all.Results);
    }
</code></pre>

<p>The Request is not null anymore but CreateQuery still returns null. I feel like I'm still missing a parameter or a few but I have no idea where. I compared Request object when I run the app through IIS and the one created for unit tests and they look similiar, yet not the same.</p>

<p>//////SOLUTION<br>
JsonServiceClient finally worked. I needed to add AQ Plugin to test setup class and add Results property into Response class to pass the results to QueryResponse instance. No need to change built-in JasonServiceClient at all, default parameters work just fine. I wasn't able to make it work based on BasicRequest, tho. But I got what I needed, that's enough for now.</p>
",https://stackoverflow.com/questions/52496649/xunit-testing-servicestack-autoquery,"['servicestack', 'ormlite-servicestack', 'servicestack-autoquery']",178,TRUE,1,1
Get a mock Cairo::Context to test conditions on the path,"<p>this is a follow up on <a href=""https://stackoverflow.com/questions/48836671/checking-if-path-is-simple-and-closed-using-cairo/48840862#48840862"">this post</a>, in which I asked about checking some condition on the border of a shape drawn using Cairomm in a <code>Gtk::DrawingArea</code> derived widget. In my case, I have a <code>void drawBorder(const Cairo::RefPtr&lt;Cairo::Context&gt;&amp; p_context)</code> method which is virtual and is overriden to specify the shape's border. For example, if I wanted a circle, I could provide the following implementation:</p>

<pre><code>void drawBorder(const Cairo::RefPtr&lt;Cairo::Context&gt;&amp; p_context)
{
    const Gtk::Allocation allocation{get_allocation()};

    const int width{allocation.get_width()};
    const int height{allocation.get_height()};
    const int smallestDimension{std::min(width, height)};

    const int xCenter{width / 2};
    const int yCenter{height / 2};

    p_context-&gt;arc(xCenter,
                   yCenter,
                   smallestDimension / 2.5,
                   0.0,
                   2.0 * M_PI);
}
</code></pre>

<p>I would like to use this method to check my condition on the border curve, as suggested in <a href=""https://stackoverflow.com/a/48840862/6575139"">the answer</a>:</p>

<blockquote>
  <p>So, you would somehow get a cairo context (<code>cairo_t</code> in C), create your shape there (with <code>line_to</code>, <code>curve_to</code>, <code>arc</code> etc). Then you do not call <code>fill</code> or <code>stroke</code>, but instead <code>cairo_copy_path_flat</code>.</p>
</blockquote>

<p>So far, I am unable to get a usable <code>Cairo::Context</code> mock to perform the check. I don't need to draw anything to perform my check, I only need to get the underlying path and work on it.</p>

<p>So far, I have tried:</p>

<ol>
<li>passing <code>nullptr</code> as the <code>Cairo::Surface</code> (which of course failed);</li>
<li>get an equivalent surface to my widget.</li>
</ol>

<p>But it failed. This: <code>gdk_window_create_similar_surface</code> looked promising, but I have not found an equivalent for widgets.</p>

<p>How could one go about getting a minimal mock context to perform such checks? This would also help me very much in my unit testing, later on.</p>

<hr>

<p>So far I got this code:</p>

<pre><code>bool isTheBorderASimpleAndClosedCurve()
{
    const Gtk::Allocation allocation{get_allocation()};

    Glib::RefPtr&lt;Gdk::Window&gt; widgetWindow{get_window()};

    Cairo::RefPtr&lt;Cairo::Surface&gt; widgetSurface{widgetWindow-&gt;create_similar_surface(Cairo::Content::CONTENT_COLOR_ALPHA,
                                                                                     allocation.get_width(),                                                                            allocation.get_height()) };

    Cairo::Context nakedContext{cairo_create(widgetSurface-&gt;cobj())};
    const Cairo::RefPtr&lt;Cairo::Context&gt; context{&amp;nakedContext};

    drawBorder(context);

    // Would like to get the path and test my condition here...!
}
</code></pre>

<p>It compiles and links, but at runtime I get a segfault with this message and a bunch of garbage:</p>

<pre><code>double free or corruption (out): 0x00007ffc0401c740
</code></pre>
",https://stackoverflow.com/questions/48843411/get-a-mock-cairocontext-to-test-conditions-on-the-path,"['c++', 'gtk', 'cairo', 'gtkmm']",144,TRUE,1,1
operator [] overloading on vector class,"<p>I am trying to overload the [] operator so that when a programmer wishes to retrieve and set specific characters of a string, which is contained in a spot of a vector, the number passed into [] would reference the ith char from the beginning of the vector, to the end. </p>

<p>For example:
Here is a vector. Starting from the beginning (0), the contents are as follows:</p>

<pre><code>dog
cat
parrot
</code></pre>

<p>where 'dog' is the first string in the vector, and 'parrot' is the last. I want the [] operator to function as follows:</p>

<pre><code>searchable_vector vec;
vec.push_back(""dog"");
vec.push_back(""cat"");
vec.push_back(""parrot"");

std::cout &lt;&lt; vec[3] &lt;&lt; "" should say 'c' "";
</code></pre>

<p>Here is my searchable_vector.hpp:</p>

<pre><code>#pragma once
#include &lt;vector&gt;
class searchable_vector : public std::vector&lt;std::string&gt;
{
 public:
    char&amp; operator [] (int n);
 private:
    std::vector&lt;std::string&gt; vector;
};
</code></pre>

<p>Here is searchable_vector.cpp:</p>

<pre><code>char&amp; searchable_vector::operator[] (int i)
{
    // 'for each' string in vector member, count 
    // the length and add it to a counter until
    // the counter is at desired 'length' (given from i)
    unsigned int counter = 0;
    unsigned int spot_in_string = 0;
    std::string holding_string = """";

    std::vector&lt;std::string&gt;::iterator it;
    it = vector.begin();

    while (it != vector.end() &amp;&amp; counter != i)
      {
          if (counter == i) // it is where it needs to be
              break;
          else 
          {
              spot_in_string = it-&gt;length() - 1;
              if (counter != 0)
                  counter += spot_in_string + 1;
              else
                  counter += spot_in_string;

              if (counter &lt; i) // look in next string
              {
                it++;
              }
              else if (counter &gt; i)
              {
                while (counter != i)        // go 'back' one at a time
                {
                  counter--;
                  spot_in_string--;
                }
                break; //should break out of master while loop
              }
          }
      }
      holding_string = *it;
      return holding_string[spot_in_string];
}
</code></pre>

<p>I wouldn't worry too much about the logic going on inside of this code, but I don't think I've done something right with overloading, as I get a Linker 2019 error (using Visual Studio) in my test file for unit testing:</p>

<pre><code>TEST_CASE(""Test searchable_vector class [] operator"", ""[searchable_vector]"")
{
    searchable_vector vec;
    vec.push_back(""dog"");
    vec.push_back(""cat"");
    vec.push_back(""parrot"");
    char result = vec[3];
    REQUIRE(result == 'c');
}
</code></pre>

<p>The error reads:</p>

<pre><code>LNK2019 unresolved external symbol ""public: char &amp; __cdecl 
searchable_vector::operator[](int)"" (??Asearchable_vector@@QEAAAEADH@Z) 
referenced in function ""void __cdecl ____C_A_T_C_H____T_E_S_T____2(void)"" (?
____C_A_T_C_H____T_E_S_T____2@@YAXXZ)   unit_tests
</code></pre>

<p>followed by the directory which holds my VM_Module.obj</p>

<p>I think it's just something elementary with my over loading, not the logic itself. If that was broken this it should still link and run, just behave badly or crash. </p>

<p>Any constructive feedback would be appreciated.</p>

<p>Also, the reason I want to overload this is so that the code I am about to write will expect the searchable_vector object to behave as mentioned, returning the ith char in the vector, and if successfully implemented, should be clean and easy to write. Thanks.</p>
",https://stackoverflow.com/questions/49480335/operator-overloading-on-vector-class,"['c++', 'inheritance', 'vector', 'cmake', 'operator-overloading']",114,TRUE,1,1
EF Core 2.1 seeding guidance,"<p>Please provide some guidance for the following problem:</p>

<ul>
<li>I have two data configurations to support, each including different initial data. Imagine two types of customers, pet supply stores and book stores. We might have a list of products for each with which we want to initially seed the database when installing on a new machine (no need for dog food items for bookstore customers or mystery novel items for pet store customers). The table structure works for either just fine; only the seed data is different.</li>
</ul>

<p>Because of how EF Core 2.1 manages seed data, migrating it across new versions, etc., is it practical to seed one or the other or both datasets somehow? Or is this beyond the scope for HasData(), which seems well-suited for a single ""configuration"" but not well-adapted for two different sets of seed data depending on which product is being built/installed? If it is reasonable to do this, what about unit testing? Seems that I need to run some tests for one configuration and some for another; yes?</p>

<p>I have looked at this item:
<a href=""https://stackoverflow.com/questions/39131577/different-seed-for-development-and-production"">Different seed for development and production</a>
but am not sure this is a reasonable way to handle my situation. I appreciate your thoughts about how you'd approach this problem given EF Core 2.1/ASP NET Core/xUnit.</p>
",https://stackoverflow.com/questions/52143076/ef-core-2-1-seeding-guidance,"['seeding', 'ef-core-2.1']",99,FALSE,1,0
PowerMock &amp; Mockito seems to be unable to mock static fields soon enough,"<p>I'm currently trying to introduce unit testing on our project in order to test interaction with an API we are given. Unfortunately the API is quite old and ugly and contains weird things (such as implementation) :-(. In our code we use let's say objects of class A. </p>

<pre><code>public class A {
     static B b = new B();
     public int foo(){return 666;}
}
</code></pre>

<p>As you can see this class contains a static field b that is filled with a new instance of class B on it's initialization. However the construction of class B is not possible in the testing environment. It somehow works only in production environment. Let's simulate it by something like this.</p>

<pre><code>public class B {
    B(){
        throw new RuntimeException();
    }
}
</code></pre>

<p>In my tests I need to test interaction of my code with class A as this is my contract to the API and contains also some useful methods (foo() in this case). However I'm failing even on the mocking of the instance.</p>

<p>Here is what I tried.</p>

<pre><code>import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;


@RunWith(PowerMockRunner.class)
@PrepareForTest({A.class,B.class})
public class ATest {

    @Mock
    A a;

    @Mock
    B b;

    @BeforeClass
    public void setUp() throws Exception {
        PowerMockito.whenNew(B.class).withNoArguments().thenReturn(b);
    }

    @Test
    public void shouldBeCorrectlyInitialized() throws Exception {
        PowerMockito.whenNew(A.class).withNoArguments().thenReturn(a);
        A shouldBeMock = new A();
        Assert.assertEquals(a,shouldBeMock);
    }
} 
</code></pre>

<p>But it seems to me that definition of mocking class B instantiation is way too late in @BeforeClass (and I have no clue how to do it sooner) as the b field is assigned when @PrepareForTest annotation is being applied (which is obviously before the @BeforeClass method is executed) and thus the ""real"" constructor is used.</p>

<p>Do you have some idea how to overcome this issue?</p>

<p>Finally here is the stacktrace of my test execution</p>

<pre><code>java.lang.ExceptionInInitializerError
    at sun.reflect.GeneratedSerializationConstructorAccessor6.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.objenesis.instantiator.sun.SunReflectionFactoryInstantiator.newInstance(SunReflectionFactoryInstantiator.java:45)
    at org.objenesis.ObjenesisBase.newInstance(ObjenesisBase.java:73)
    at org.mockito.internal.creation.instance.ObjenesisInstantiator.newInstance(ObjenesisInstantiator.java:14)
    at org.powermock.api.mockito.repackaged.ClassImposterizer.createProxy(ClassImposterizer.java:149)
    at org.powermock.api.mockito.repackaged.ClassImposterizer.imposterise(ClassImposterizer.java:64)
    at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.createMethodInvocationControl(DefaultMockCreator.java:121)
    at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.createMock(DefaultMockCreator.java:69)
    at org.powermock.api.mockito.internal.mockcreation.DefaultMockCreator.mock(DefaultMockCreator.java:46)
    at org.powermock.api.mockito.PowerMockito.mock(PowerMockito.java:201)
    at org.powermock.api.extension.listener.AnnotationEnabler.standardInject(AnnotationEnabler.java:118)
    at org.powermock.api.extension.listener.AnnotationEnabler.beforeTestMethod(AnnotationEnabler.java:63)
    at org.powermock.tests.utils.impl.PowerMockTestNotifierImpl.notifyBeforeTestMethod(PowerMockTestNotifierImpl.java:82)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:308)
    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:87)
    at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:50)
    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:34)
    at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
    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.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 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: java.lang.NullPointerException
    at s.a.B.&lt;init&gt;(B.java:7)
    at s.a.A.&lt;clinit&gt;(A.java:10)
    ... 45 more
</code></pre>
",https://stackoverflow.com/questions/50170134/powermock-mockito-seems-to-be-unable-to-mock-static-fields-soon-enough,"['java', 'mockito', 'junit4', 'powermock', 'powermockito']",1367,TRUE,1,1
WCF Service added as a service reference shows up as a connected service with missing DataContracts,"<p>I have a solution where I add a <code>service reference</code> for a service and the service shows up as a <code>service reference</code> and everything works great. Very Happy.</p>

<p>In a separate solution I have created the service. Within this solution I have a project for unit testing the service. When I add a service reference for the service to the unit test project, the reference shows up as a <code>connected service</code> rather than the expected <code>service reference</code>, and I do not have access to classes specified by <code>[DataContract]</code> .</p>

<p>This behavior is not the same as installing the service on a different project, and it is preventing me from testing the service.</p>

<p>To recap, I have one service, installing it in two separate solutions produces different results. One solution the install works as expected and I have access to classes specified by <code>DataContract</code> and the other solution Installs the service and I do not have access to classes specified by <code>DataContract</code>. Both installed services provide all the methods exposed in the <code>interface</code>. </p>

<p>What can I add to help figure this out? I am not terribly familiar with services so please ask me questions to help improve this question.</p>

<p>****UPDATE****
What is working if I add a new project, then the service provides the data contracts. Something is going sour when I am updating the service references on an existing project. Obviously creating a new unit test project and moving everything in is a pain.....</p>
",https://stackoverflow.com/questions/53785812/wcf-service-added-as-a-service-reference-shows-up-as-a-connected-service-with-mi,['wcf'],56,FALSE,0,1
Slowness of multiprocessing.dummy.Pool&#39;s join/terminate method,"<p>While using the <code>join</code> (or <code>terminate</code>) method of the <code>multiprocessing.dummy.Pool</code> class, the call takes about 100 miliseconds, which seems to be slow to me. This example:</p>

<pre><code>from multiprocessing.dummy import Pool
import time

def foo():
    pass

pool = Pool(1)
pool.apply_async(foo)
pool.close()
start_time = time.time()
pool.join()
print(""%f"" % (time.time() - start_time))
</code></pre>

<p>displays a number that is always greater than 0.100 (seconds) whatever the version of python is used (I tried with 2.7, 3.4, 3.5, 3.6, 3.7).
I get the same result when I use <code>terminate</code> instead of <code>join</code>.</p>

<p>When I use <code>cProfile</code> to understand where the time is spent, I have this (I stripped all non-relevant entries):</p>

<pre class=""lang-none prettyprint-override""><code>18698 function calls (18434 primitive calls) in 0.125 seconds

Ordered by: cumulative time

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
  25/1    0.000    0.000    0.125    0.125 {built-in method builtins.exec}
     1    0.000    0.000    0.125    0.125 test_pool.py:1(&lt;module&gt;)
    22    0.101    0.005    0.101    0.005 {method 'acquire' of '_thread.lock' objects}
     1    0.000    0.000    0.100    0.100 pool.py:576(join)
     4    0.000    0.000    0.100    0.025 threading.py:1000(join)
     4    0.000    0.000    0.100    0.025 threading.py:1038(_wait_for_tstate_lock)
[...]
</code></pre>

<p>I understand from this that <code>Pool.join()</code> calls <code>Thread.join()</code> on 4 threads (I guess from reading code that is corresponds to <code>_worker_handler</code>, <code>_task_handler</code>, <code>_result_handler</code> of <code>multiprocessing.pool.Pool</code> class plus the number of requested threads in the pool), but I still can't figure out why <code>Thread.join()</code> takes a fixed 0.025 seconds duration to execute. It seems to be related to lock acquisition..</p>

<p>Please note that until Python 3.7.1, the <code>terminate()</code> function was not called automatically at garbage collection contrary to what was documented. Since Python 3.7.1 (<a href=""https://bugs.python.org/issue34172"" rel=""nofollow noreferrer"">https://bugs.python.org/issue34172</a>), <code>terminate()</code> is ""really"" called at garbage collection, meaning this slowness appears even if <code>terminate()</code> or <code>join()</code> have not been called explicitely.</p>

<p>Does anybody would have an explanation of this slowness and possibly a way to avoid it ?</p>

<p>In the context of the program I'm writing such a slow-down is not visible, but in unit testing where creating and terminating a pool is done hundreds of times, this makes test execution much, much slower.</p>
",https://stackoverflow.com/questions/53110465/slowness-of-multiprocessing-dummy-pools-join-terminate-method,"['python', 'multithreading']",154,FALSE,0,0
Returning the same generated UUID in a static and non-static method,"<p>I have an object which is defined like so:</p>

<p><strong>TestDriver.java</strong></p>

<pre><code>public void TestDriver extends FirefoxDriver implements SupportDownloads{

    public TestDriver(){
        super(TestDriver.service(), TestDriver.options());
    }

    private static service(){
        // implementation
    }

    private static options(){
        ..
        // attempting to generate a UUID which will be eventually be set as the folder where all downloads will go to. 
        // unique paths are needed as we will be using this class for multi-threaded runs and would like each browser to have its own unique download folder
        byte[] value = String.valueOf(Thread.currentThread().getId()).getBytes());
        String uniqueID = UUID.nameUUIDFromBytes(value).toString();
        ..
    }

    // purpose of this method is to return the path download folder 
    // note the repeated generation of the UUID because the above methods are static
    @Override
    public File getDownloadPath(){
        String value = String.valueOf(Thread.currentThread().getId());
        return new File(prop.getProperty(fileDirectory()) + File.separator + UUID.nameUUIDFromBytes(value.getBytes()));    
    }
}
</code></pre>

<p><strong>SupportsDownload.java</strong></p>

<pre><code>public interface SupportsDownload {
    public File getDownloadPath();
}
</code></pre>

<p>What I am trying to do is:</p>

<ol>
<li>To generate a UUID so that each thread created have unique download paths</li>
<li>To be able to also return this UUID in a public method which is accessible outside of this class (for unit-testing purposes and usage by the users)</li>
</ol>

<p>Even though the above code is already working, I will run into an issue which <a href=""https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#getId()"" rel=""nofollow noreferrer"">official Java docs</a> mention: </p>

<blockquote>
  <p>Returns the identifier of this Thread. The thread ID is a positive long number generated when this thread was created. The thread ID is unique and remains unchanged during its lifetime. <strong>When a thread is terminated, this thread ID may be reused.</strong></p>
</blockquote>

<p>As such, the above method is not foolproof because basing the UUID seed only on Thread.currentThread().getId() may yield the same ID if it is reused, causing the UUID generated to be the same.</p>

<p>I then tried to modify it to include time in millis, i.e.:</p>

<pre><code>        byte[] value = String.valueOf(Thread.currentThread().getId() + Calendar.getInstance().getTimeInMillis()).getBytes());
</code></pre>

<p>However, as time value always changes, I wouldn't be able to grab the exact same value in the return method <code>getDownloadPath()</code>.</p>

<p>If I were to generate the time value once, and store it in a variable, i.e.:</p>

<p><code>private final long timeInMillis = Calendar.getTime().getTimeInMillis();</code></p>

<p>I will not be able to utilize this variable for both the static and non-static methods.</p>

<p>I'm at a loss, any suggestions would be great :-)</p>
",https://stackoverflow.com/questions/53372196/returning-the-same-generated-uuid-in-a-static-and-non-static-method,"['java', 'multithreading']",1354,TRUE,0,1
"Anonymous classes, accessing private properties of extended class","<p>Fully aware that things like Mockery exist, I'm trying to see what testing in PHPUnit would be like using straight PHP. This is only possible with the advent of anonymous classes. What I have works perfectly, unless the property I want to override in my extended class is private, then it of course fails. Here's a small example of how a test might look like:</p>

<pre><code>$test = new class() extends ClassImExtending {
        // user is protected in ClassImExtending, and its value is 
        // injected User
        public $user;

        public function __construct() {
            // Overwrites ClassImExtending constructor so that I don't 
            // have to inject all the same dependencies for the purpose 
            // of my test

            // By extending User, it forces any methods I'm overriding 
            // to accept the same number and type of arguments
            $this-&gt;user = new class() extends User {
                public function getUser() {
                    $user = new User;
                    $user-&gt;id = 1;
                    return $user;
                }
            };
        }
}
</code></pre>

<p>So essentially, as long as the property $user in ClassImExtending is protected or public, and the method I'm testing doesn't use any other ClassImExtending properties besides $user, then the following will work great:</p>

<pre><code>$result = $test-&gt;methodImTestingInClassImExtending();
</code></pre>

<p>But like I said previously, if $user is private, methodImTestingInClassImExtending() of course won't even look at my anonymous class override property $user at all, it'll look at $user within ClassImExtending, which of course the value of is null since my anonymous class overrides the class constructor where $user is given a value in ClassImExtending.</p>

<p>I've been trying to play around with Closures or anything similar to try and see if I could make this setup somehow have access to the private property of the class I'm extending so that I can override the value. I recognize that this defeats the purpose of private properties and isn't a typical use case. But for the purposes of testing what I'm doing within the concept of unit testing... does anyone have any ideas or thoughts?</p>
",https://stackoverflow.com/questions/50219161/anonymous-classes-accessing-private-properties-of-extended-class,['php'],47,FALSE,0,0
"NUnit tests work in ReSharper (Unit Testing Session window), but Visual Studio, and Hosted VSTS build agent don&#39;t find any tests","<p>I've just picked up an old (ish) project, which had a load of unit tests commented out. I want to revive the tests, and increase the code coverage so we can crack on with TDD.</p>

<p>I'm running VS2017 (15.5.7), ReSharper 2017.3.2, dotCober 2017.3.2 - all the latest versions. The project is Framework v4.7.1 (upgraded from 4.5.2). I've got the NUnit3 Test Runner Extension installed in VS.</p>

<p>It's a clean Windows installation so no old gunk left on it.</p>

<p>An example packages.config:</p>

<pre><code>&lt;?xml version=""1.0"" encoding=""utf-8""?&gt;
&lt;packages&gt;
  &lt;package id=""Castle.Core"" version=""3.3.3"" targetFramework=""net452"" /&gt;
  &lt;package id=""Castle.Windsor"" version=""3.3.0"" targetFramework=""net452"" /&gt;
  &lt;package id=""EntityFramework"" version=""6.1.3"" targetFramework=""net452"" /&gt;
  &lt;package id=""Microsoft.CodeCoverage"" version=""1.0.3"" targetFramework=""net471"" /&gt;
  &lt;package id=""Microsoft.NET.Test.Sdk"" version=""15.6.0"" targetFramework=""net471"" /&gt;
  &lt;package id=""Microsoft.VisualStudio.TestPlatform"" version=""14.0.0.1"" targetFramework=""net471"" /&gt;
  &lt;package id=""Moq"" version=""4.2.1510.2205"" targetFramework=""net452"" /&gt;
  &lt;package id=""NUnit"" version=""3.9.0"" targetFramework=""net471"" /&gt;
  &lt;package id=""NUnit.Console"" version=""3.8.0"" targetFramework=""net471"" /&gt;
  &lt;package id=""NUnit.ConsoleRunner"" version=""3.8.0"" targetFramework=""net471"" /&gt;
  &lt;package id=""NUnit.Extension.NUnitProjectLoader"" version=""3.5.0"" targetFramework=""net471"" /&gt;
  &lt;package id=""NUnit.Extension.NUnitV2Driver"" version=""3.6.0"" targetFramework=""net471"" /&gt;
  &lt;package id=""NUnit.Extension.NUnitV2ResultWriter"" version=""3.5.0"" targetFramework=""net471"" /&gt;
  &lt;package id=""NUnit.Extension.TeamCityEventListener"" version=""1.0.3"" targetFramework=""net471"" /&gt;
  &lt;package id=""NUnit.Extension.VSProjectLoader"" version=""3.7.0"" targetFramework=""net471"" /&gt;
  &lt;package id=""NUnit3TestAdapter"" version=""3.9.0"" targetFramework=""net471"" /&gt;
&lt;/packages&gt;
</code></pre>

<p>This is after I upgraded all the packages to the latest version. </p>

<p>The .csproj to go with it is:</p>

<pre><code>&lt;?xml version=""1.0"" encoding=""utf-8""?&gt;
&lt;Project ToolsVersion=""14.0"" DefaultTargets=""Build"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""&gt;
  &lt;Import Project=""..\packages\Microsoft.NET.Test.Sdk.15.6.0\build\net45\Microsoft.Net.Test.Sdk.props"" Condition=""Exists('..\packages\Microsoft.NET.Test.Sdk.15.6.0\build\net45\Microsoft.Net.Test.Sdk.props')"" /&gt;
  &lt;Import Project=""..\packages\NUnit3TestAdapter.3.9.0\build\net35\NUnit3TestAdapter.props"" Condition=""Exists('..\packages\NUnit3TestAdapter.3.9.0\build\net35\NUnit3TestAdapter.props')"" /&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;Platform Condition="" '$(Platform)' == '' ""&gt;AnyCPU&lt;/Platform&gt;
    &lt;ProjectGuid&gt;{F46BC342-E486-4EF2-8C52-6B7CEF6D9565}&lt;/ProjectGuid&gt;
    &lt;OutputType&gt;Library&lt;/OutputType&gt;
    &lt;AppDesignerFolder&gt;Properties&lt;/AppDesignerFolder&gt;
    &lt;RootNamespace&gt;MyProject.ServiceTests&lt;/RootNamespace&gt;
    &lt;AssemblyName&gt;MyProject.ServiceTests&lt;/AssemblyName&gt;
    &lt;TargetFrameworkVersion&gt;v4.7.1&lt;/TargetFrameworkVersion&gt;
    &lt;FileAlignment&gt;512&lt;/FileAlignment&gt;
    &lt;TargetFrameworkProfile /&gt;
    &lt;NuGetPackageImportStamp&gt;
    &lt;/NuGetPackageImportStamp&gt;
  &lt;/PropertyGroup&gt;
  &lt;PropertyGroup Condition="" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ""&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;TRACE&lt;/DefineConstants&gt;
    &lt;ErrorReport&gt;prompt&lt;/ErrorReport&gt;
    &lt;WarningLevel&gt;4&lt;/WarningLevel&gt;
  &lt;/PropertyGroup&gt;
  &lt;PropertyGroup Condition="" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ""&gt;
    &lt;DebugType&gt;pdbonly&lt;/DebugType&gt;
    &lt;Optimize&gt;true&lt;/Optimize&gt;
    &lt;OutputPath&gt;bin\Release\&lt;/OutputPath&gt;
    &lt;DefineConstants&gt;TRACE&lt;/DefineConstants&gt;
    &lt;ErrorReport&gt;prompt&lt;/ErrorReport&gt;
    &lt;WarningLevel&gt;4&lt;/WarningLevel&gt;
  &lt;/PropertyGroup&gt;
  &lt;PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Development|AnyCPU'""&gt;
    &lt;DebugSymbols&gt;true&lt;/DebugSymbols&gt;
    &lt;OutputPath&gt;bin\Development\&lt;/OutputPath&gt;
    &lt;DefineConstants&gt;DEBUG;TRACE&lt;/DefineConstants&gt;
    &lt;DebugType&gt;full&lt;/DebugType&gt;
    &lt;PlatformTarget&gt;AnyCPU&lt;/PlatformTarget&gt;
    &lt;ErrorReport&gt;prompt&lt;/ErrorReport&gt;
    &lt;CodeAnalysisRuleSet&gt;MinimumRecommendedRules.ruleset&lt;/CodeAnalysisRuleSet&gt;
  &lt;/PropertyGroup&gt;
  &lt;PropertyGroup Condition=""'$(Configuration)|$(Platform)' == 'Test|AnyCPU'""&gt;
    &lt;DebugSymbols&gt;true&lt;/DebugSymbols&gt;
    &lt;OutputPath&gt;bin\Test\&lt;/OutputPath&gt;
    &lt;DefineConstants&gt;DEBUG;TRACE&lt;/DefineConstants&gt;
    &lt;DebugType&gt;full&lt;/DebugType&gt;
    &lt;PlatformTarget&gt;AnyCPU&lt;/PlatformTarget&gt;
    &lt;ErrorReport&gt;prompt&lt;/ErrorReport&gt;
    &lt;CodeAnalysisRuleSet&gt;MinimumRecommendedRules.ruleset&lt;/CodeAnalysisRuleSet&gt;
  &lt;/PropertyGroup&gt;
  &lt;ItemGroup&gt;
    &lt;Reference Include=""Castle.Core, Version=3.3.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL""&gt;
      &lt;HintPath&gt;..\packages\Castle.Core.3.3.3\lib\net45\Castle.Core.dll&lt;/HintPath&gt;
      &lt;Private&gt;True&lt;/Private&gt;
    &lt;/Reference&gt;
    &lt;Reference Include=""Castle.Windsor, Version=3.3.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL""&gt;
      &lt;HintPath&gt;..\packages\Castle.Windsor.3.3.0\lib\net45\Castle.Windsor.dll&lt;/HintPath&gt;
      &lt;Private&gt;True&lt;/Private&gt;
    &lt;/Reference&gt;
    &lt;Reference Include=""EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL""&gt;
      &lt;HintPath&gt;..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll&lt;/HintPath&gt;
      &lt;Private&gt;True&lt;/Private&gt;
    &lt;/Reference&gt;
    &lt;Reference Include=""EntityFramework.SqlServer, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL""&gt;
      &lt;HintPath&gt;..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.SqlServer.dll&lt;/HintPath&gt;
      &lt;Private&gt;True&lt;/Private&gt;
    &lt;/Reference&gt;
    &lt;Reference Include=""ImageResizer, Version=4.0.0.0, Culture=neutral, processorArchitecture=MSIL""&gt;
      &lt;HintPath&gt;..\packages\ImageResizer.4.0.5\lib\net45\ImageResizer.dll&lt;/HintPath&gt;
      &lt;Private&gt;True&lt;/Private&gt;
    &lt;/Reference&gt;
    &lt;Reference Include=""Microsoft.AspNet.Identity.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL""&gt;
      &lt;HintPath&gt;..\packages\Microsoft.AspNet.Identity.Core.2.2.1\lib\net45\Microsoft.AspNet.Identity.Core.dll&lt;/HintPath&gt;
      &lt;Private&gt;True&lt;/Private&gt;
    &lt;/Reference&gt;
    &lt;Reference Include=""Microsoft.AspNet.Identity.EntityFramework, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL""&gt;
      &lt;HintPath&gt;..\packages\Microsoft.AspNet.Identity.EntityFramework.2.2.1\lib\net45\Microsoft.AspNet.Identity.EntityFramework.dll&lt;/HintPath&gt;
      &lt;Private&gt;True&lt;/Private&gt;
    &lt;/Reference&gt;
    &lt;Reference Include=""Microsoft.VisualStudio.CodeCoverage.Shim, Version=15.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL""&gt;
      &lt;HintPath&gt;..\packages\Microsoft.CodeCoverage.1.0.3\lib\netstandard1.0\Microsoft.VisualStudio.CodeCoverage.Shim.dll&lt;/HintPath&gt;
      &lt;Private&gt;True&lt;/Private&gt;
    &lt;/Reference&gt;
    &lt;Reference Include=""Microsoft.VisualStudio.TestPlatform.TestFramework, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL""&gt;
      &lt;HintPath&gt;..\packages\Microsoft.VisualStudio.TestPlatform.14.0.0.1\lib\net20\Microsoft.VisualStudio.TestPlatform.TestFramework.dll&lt;/HintPath&gt;
    &lt;/Reference&gt;
    &lt;Reference Include=""Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL""&gt;
      &lt;HintPath&gt;..\packages\Microsoft.VisualStudio.TestPlatform.14.0.0.1\lib\net20\Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions.dll&lt;/HintPath&gt;
    &lt;/Reference&gt;
    &lt;Reference Include=""Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL""&gt;
      &lt;HintPath&gt;..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll&lt;/HintPath&gt;
      &lt;Private&gt;True&lt;/Private&gt;
    &lt;/Reference&gt;
    &lt;Reference Include=""Moq, Version=4.2.1510.2205, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL""&gt;
      &lt;HintPath&gt;..\packages\Moq.4.2.1510.2205\lib\net40\Moq.dll&lt;/HintPath&gt;
      &lt;Private&gt;True&lt;/Private&gt;
    &lt;/Reference&gt;
    &lt;Reference Include=""nunit.framework, Version=2.6.3.13283, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL""&gt;
      &lt;HintPath&gt;..\packages\nunit.framework.2.63.0\lib\nunit.framework.dll&lt;/HintPath&gt;
    &lt;/Reference&gt;
    &lt;Reference Include=""Postal, Version=1.0.0.0, Culture=neutral, PublicKeyToken=45719375b8b4d528, processorArchitecture=MSIL""&gt;
      &lt;HintPath&gt;..\packages\Postal.Mvc5.1.2.0\lib\net45\Postal.dll&lt;/HintPath&gt;
      &lt;Private&gt;True&lt;/Private&gt;
    &lt;/Reference&gt;
    &lt;Reference Include=""RazorEngine, Version=3.7.7.0, Culture=neutral, PublicKeyToken=9ee697374c7e744a, processorArchitecture=MSIL""&gt;
      &lt;HintPath&gt;..\packages\RazorEngine.3.7.7\lib\net45\RazorEngine.dll&lt;/HintPath&gt;
      &lt;Private&gt;True&lt;/Private&gt;
    &lt;/Reference&gt;
    &lt;Reference Include=""System"" /&gt;
    &lt;Reference Include=""System.ComponentModel.DataAnnotations"" /&gt;
    &lt;Reference Include=""System.Core"" /&gt;
    &lt;Reference Include=""System.Drawing"" /&gt;
    &lt;Reference Include=""System.Web"" /&gt;
    &lt;Reference Include=""System.Web.Helpers, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL""&gt;
      &lt;HintPath&gt;..\packages\Microsoft.AspNet.WebPages.3.2.3\lib\net45\System.Web.Helpers.dll&lt;/HintPath&gt;
      &lt;Private&gt;True&lt;/Private&gt;
    &lt;/Reference&gt;
    &lt;Reference Include=""System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL""&gt;
      &lt;HintPath&gt;..\packages\Microsoft.AspNet.Mvc.5.2.3\lib\net45\System.Web.Mvc.dll&lt;/HintPath&gt;
      &lt;Private&gt;True&lt;/Private&gt;
    &lt;/Reference&gt;
    &lt;Reference Include=""System.Web.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL""&gt;
      &lt;HintPath&gt;..\packages\Microsoft.AspNet.Razor.3.2.3\lib\net45\System.Web.Razor.dll&lt;/HintPath&gt;
      &lt;Private&gt;True&lt;/Private&gt;
    &lt;/Reference&gt;
    &lt;Reference Include=""System.Web.WebPages, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL""&gt;
      &lt;HintPath&gt;..\packages\Microsoft.AspNet.WebPages.3.2.3\lib\net45\System.Web.WebPages.dll&lt;/HintPath&gt;
      &lt;Private&gt;True&lt;/Private&gt;
    &lt;/Reference&gt;
    &lt;Reference Include=""System.Web.WebPages.Deployment, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL""&gt;
      &lt;HintPath&gt;..\packages\Microsoft.AspNet.WebPages.3.2.3\lib\net45\System.Web.WebPages.Deployment.dll&lt;/HintPath&gt;
      &lt;Private&gt;True&lt;/Private&gt;
    &lt;/Reference&gt;
    &lt;Reference Include=""System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL""&gt;
      &lt;HintPath&gt;..\packages\Microsoft.AspNet.WebPages.3.2.3\lib\net45\System.Web.WebPages.Razor.dll&lt;/HintPath&gt;
      &lt;Private&gt;True&lt;/Private&gt;
    &lt;/Reference&gt;
    &lt;Reference Include=""System.Xml.Linq"" /&gt;
    &lt;Reference Include=""System.Data.DataSetExtensions"" /&gt;
    &lt;Reference Include=""Microsoft.CSharp"" /&gt;
    &lt;Reference Include=""System.Data"" /&gt;
    &lt;Reference Include=""System.Net.Http"" /&gt;
    &lt;Reference Include=""System.Xml"" /&gt;
  &lt;/ItemGroup&gt;
  &lt;ItemGroup&gt;
    &lt;Compile Include=""MyProjectReadService\AuthoriseToAdministerTests.cs"" /&gt;
    &lt;Compile Include=""MyProjectReadService\MyProjectTests.cs"" /&gt;
    &lt;Compile Include=""MyProjectReadService\CapabilityTests.cs"" /&gt;
    &lt;Compile Include=""MyProjectReadService\CollectionTests.cs"" /&gt;
    &lt;Compile Include=""MyProjectReadService\DiagnosisTests.cs"" /&gt;
    &lt;Compile Include=""MyProjectReadService\LogoTests.cs"" /&gt;
    &lt;Compile Include=""MyProjectReadService\MaterialPreservationDetailsTests.cs"" /&gt;
    &lt;Compile Include=""MyProjectReadService\NetworkTests.cs"" /&gt;
    &lt;Compile Include=""MyProjectReadService\OrganisationTypeTests.cs"" /&gt;
    &lt;Compile Include=""MyProjectReadService\RegisterRequestTests.cs"" /&gt;
    &lt;Compile Include=""MyProjectReadService\SampleSetTests.cs"" /&gt;
    &lt;Compile Include=""MyProjectReadService\ServiceOfferingTests.cs"" /&gt;
    &lt;Compile Include=""EmailServiceTests.cs"" /&gt;
    &lt;Compile Include=""Properties\AssemblyInfo.cs"" /&gt;
    &lt;Compile Include=""SqlServerLogoStorageProviderTests.cs"" /&gt;
    &lt;Compile Include=""WindsorInstaller.cs"" /&gt;
  &lt;/ItemGroup&gt;
  &lt;ItemGroup&gt;
    &lt;None Include=""app.config"" /&gt;
    &lt;None Include=""packages.config"" /&gt;
    &lt;None Include=""Views\Emails\_ViewStart.cshtml"" /&gt;
  &lt;/ItemGroup&gt;
  &lt;ItemGroup&gt;
    &lt;ProjectReference Include=""..\MyProject.Caching\MyProject.Caching.csproj""&gt;
      &lt;Project&gt;{ff0409c6-92bd-49d0-ba39-d3c63cb42c9c}&lt;/Project&gt;
      &lt;Name&gt;MyProject.Caching&lt;/Name&gt;
    &lt;/ProjectReference&gt;
    &lt;ProjectReference Include=""..\MyProject.Data\MyProject.Data.csproj""&gt;
      &lt;Project&gt;{d029f30a-f65a-46b5-9e5d-d0b2251858d0}&lt;/Project&gt;
      &lt;Name&gt;MyProject.Data&lt;/Name&gt;
    &lt;/ProjectReference&gt;
    &lt;ProjectReference Include=""..\MyProject.Identity.Contracts\MyProject.Identity.Contracts.csproj""&gt;
      &lt;Project&gt;{F24B10E2-0F6F-40ED-8CE4-0BD587D6827E}&lt;/Project&gt;
      &lt;Name&gt;MyProject.Identity.Contracts&lt;/Name&gt;
    &lt;/ProjectReference&gt;
    &lt;ProjectReference Include=""..\MyProject.Search.Contracts\MyProject.Search.Contracts.csproj""&gt;
      &lt;Project&gt;{7121ef03-7230-4b37-af55-a3ee03ba41a0}&lt;/Project&gt;
      &lt;Name&gt;MyProject.Search.Contracts&lt;/Name&gt;
    &lt;/ProjectReference&gt;
    &lt;ProjectReference Include=""..\MyProject.Services\MyProject.Services.csproj""&gt;
      &lt;Project&gt;{dc6a8e03-361c-4f85-8d31-5ba9c237c33e}&lt;/Project&gt;
      &lt;Name&gt;MyProject.Services&lt;/Name&gt;
    &lt;/ProjectReference&gt;
    &lt;ProjectReference Include=""..\MyProject.TestUtils\MyProject.TestUtils.csproj""&gt;
      &lt;Project&gt;{0e050ea1-d815-492e-9b9b-7c69b4c6f2c0}&lt;/Project&gt;
      &lt;Name&gt;MyProject.TestUtils&lt;/Name&gt;
    &lt;/ProjectReference&gt;
    &lt;ProjectReference Include=""..\MyProject.Utils\MyProject.Utils.csproj""&gt;
      &lt;Project&gt;{28432D0C-565A-4F39-8F41-B97BAE061186}&lt;/Project&gt;
      &lt;Name&gt;MyProject.Utils&lt;/Name&gt;
    &lt;/ProjectReference&gt;
  &lt;/ItemGroup&gt;
  &lt;Import Project=""$(MSBuildToolsPath)\Microsoft.CSharp.targets"" /&gt;
  &lt;Target Name=""EnsureNuGetPackageBuildImports"" BeforeTargets=""PrepareForBuild""&gt;
    &lt;PropertyGroup&gt;
      &lt;ErrorText&gt;This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.&lt;/ErrorText&gt;
    &lt;/PropertyGroup&gt;
    &lt;Error Condition=""!Exists('..\packages\NUnit3TestAdapter.3.9.0\build\net35\NUnit3TestAdapter.props')"" Text=""$([System.String]::Format('$(ErrorText)', '..\packages\NUnit3TestAdapter.3.9.0\build\net35\NUnit3TestAdapter.props'))"" /&gt;
    &lt;Error Condition=""!Exists('..\packages\Microsoft.NET.Test.Sdk.15.6.0\build\net45\Microsoft.Net.Test.Sdk.props')"" Text=""$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.NET.Test.Sdk.15.6.0\build\net45\Microsoft.Net.Test.Sdk.props'))"" /&gt;
    &lt;Error Condition=""!Exists('..\packages\Microsoft.NET.Test.Sdk.15.6.0\build\net45\Microsoft.Net.Test.Sdk.targets')"" Text=""$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.NET.Test.Sdk.15.6.0\build\net45\Microsoft.Net.Test.Sdk.targets'))"" /&gt;
  &lt;/Target&gt;
  &lt;Import Project=""..\packages\Microsoft.NET.Test.Sdk.15.6.0\build\net45\Microsoft.Net.Test.Sdk.targets"" Condition=""Exists('..\packages\Microsoft.NET.Test.Sdk.15.6.0\build\net45\Microsoft.Net.Test.Sdk.targets')"" /&gt;
  &lt;!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
       Other similar extension points exist, see Microsoft.Common.targets.
  &lt;Target Name=""BeforeBuild""&gt;
  &lt;/Target&gt;
  &lt;Target Name=""AfterBuild""&gt;
  &lt;/Target&gt;
  --&gt;
&lt;/Project&gt;
</code></pre>

<p>ReSharper/dotCover pick up 254 just fine in the Unit Testing Session/Continuous Testing Session. So if I right-click a project or solution and tell it to run tests it runs them fine, and they all pass. Lovely.</p>

<p>For some reason Visual Studio has no idea about them. If I check the Tests output in VS, I get 0 results:</p>

<pre><code>[23/02/2018 22:54:40 Informational] ------ Discover test started ------
[23/02/2018 22:54:41 Informational] NUnit Adapter 3.9.0.0: Test discovery starting
[23/02/2018 22:54:41 Informational] Assembly contains no NUnit 3.0 tests: C:\Users\Dummy\source\repos\MyProjects.initial\MyProjects\MyProjects.Caching\bin\Debug\MyProjects.Caching.dll
[23/02/2018 22:54:41 Informational] Assembly contains no NUnit 3.0 tests: C:\Users\Dummy\source\repos\MyProjects.initial\MyProjects\MyProjects.DataTests\bin\Debug\MyProjects.DataTests.dll
[23/02/2018 22:54:41 Informational] Assembly contains no NUnit 3.0 tests: C:\Users\Dummy\source\repos\MyProjects.initial\MyProjects\MyProjects.Data\bin\Debug\MyProjects.Data.dll
[23/02/2018 22:54:41 Informational] Assembly contains no NUnit 3.0 tests: C:\Users\Dummy\source\repos\MyProjects.initial\MyProjects\MyProjects.DTOTests\bin\Debug\MyProjects.DTOTests.dll
[23/02/2018 22:54:41 Informational] Assembly contains no NUnit 3.0 tests: C:\Users\Dummy\source\repos\MyProjects.initial\MyProjects\MyProjects.ElasticSearch\bin\Debug\MyProjects.ElasticSearch.dll
[23/02/2018 22:54:41 Informational] Assembly contains no NUnit 3.0 tests: C:\Users\Dummy\source\repos\MyProjects.initial\MyProjects\MyProjects.ExtensionsTests\bin\Debug\MyProjects.ExtensionsTests.dll
[23/02/2018 22:54:41 Informational] Assembly contains no NUnit 3.0 tests: C:\Users\Dummy\source\repos\MyProjects.initial\MyProjects\MyProjects.Extensions\bin\Debug\MyProjects.Extensions.dll
[23/02/2018 22:54:41 Informational] Assembly contains no NUnit 3.0 tests: C:\Users\Dummy\source\repos\MyProjects.initial\MyProjects\MyProjects.Identity.Contracts\bin\Debug\MyProjects.Identity.Contracts.dll
[23/02/2018 22:54:41 Informational] Assembly contains no NUnit 3.0 tests: C:\Users\Dummy\source\repos\MyProjects.initial\MyProjects\MyProjects.Identity\bin\Debug\MyProjects.Identity.dll
[23/02/2018 22:54:41 Informational] Assembly contains no NUnit 3.0 tests: C:\Users\Dummy\source\repos\MyProjects.initial\MyProjects\MyProjects.Search.Contracts\bin\Debug\MyProjects.Search.Contracts.dll
[23/02/2018 22:54:41 Informational] Assembly contains no NUnit 3.0 tests: C:\Users\Dummy\source\repos\MyProjects.initial\MyProjects\MyProjects.Search.DTOs\bin\Debug\MyProjects.Search.DTOs.dll
[23/02/2018 22:54:41 Informational] Assembly contains no NUnit 3.0 tests: C:\Users\Dummy\source\repos\MyProjects.initial\MyProjects\MyProjects.Services\bin\Debug\MyProjects.Services.dll
[23/02/2018 22:54:41 Informational] Assembly contains no NUnit 3.0 tests: C:\Users\Dummy\source\repos\MyProjects.initial\MyProjects\MyProjects.ServiceTests\bin\Debug\MyProjects.ServiceTests.dll
[23/02/2018 22:54:41 Informational] Assembly contains no NUnit 3.0 tests: C:\Users\Dummy\source\repos\MyProjects.initial\MyProjects\MyProjects.TestUtils\bin\Debug\MyProjects.TestUtils.dll
[23/02/2018 22:54:41 Informational] Assembly contains no NUnit 3.0 tests: C:\Users\Dummy\source\repos\MyProjects.initial\MyProjects\MyProjects.UtilsTests\bin\Debug\MyProjects.UtilsTests.dll
[23/02/2018 22:54:41 Informational] Assembly contains no NUnit 3.0 tests: C:\Users\Dummy\source\repos\MyProjects.initial\MyProjects\MyProjects.Utils\bin\Debug\MyProjects.Utils.dll
[23/02/2018 22:54:41 Informational] Assembly contains no NUnit 3.0 tests: C:\Users\Dummy\source\repos\MyProjects.initial\MyProjects\MyProjects.ViewModelTests\bin\Debug\MyProjects.ViewModelTests.dll
[23/02/2018 22:54:41 Informational] Assembly contains no NUnit 3.0 tests: C:\Users\Dummy\source\repos\MyProjects.initial\MyProjects\MyProjects.Web\bin\MyProjects.Web.dll
[23/02/2018 22:54:41 Informational] Assembly contains no NUnit 3.0 tests: C:\Users\Dummy\source\repos\MyProjects.initial\MyProjects\edmxbuilder\bin\Debug\edmxbuilder.exe
[23/02/2018 22:54:41 Informational] NUnit Adapter 3.9.0.0: Test discovery complete
[23/02/2018 22:54:41 Informational] ========== Discover test finished: 0 found (0:00:01.4894578) ==========
</code></pre>

<p>The same happens if I Get the MS Hosted VS2017 build agent to try running the tests in VSTS.</p>

<p>One thing I did notice is that some people online say there should be an nunittest.exe (or similar) in each test project's bin/Debug directory, which my projects don't.</p>

<p>I've disabled ReSharper to try and sort this out but currently hit a brick wall.</p>
",https://stackoverflow.com/questions/48957477/nunit-tests-work-in-resharper-unit-testing-session-window-but-visual-studio,"['visual-studio', 'unit-testing', 'visual-studio-2017', 'nunit', 'nunit-3.0']",591,TRUE,0,2
ASP.NET Identity - making actions on behalf of someone,"<p>I have few BL functions that checking who is invoking a method by reading the data from httpContext.User property. It works great when the user really SignIn to the system.</p>

<p>I would like to allow users to schedule an action to be run on a later time. Once the user asks to send an email later, i am writing the request to the DB and the automation service i developed will execute it on the right time by making an http call like: <a href=""https://mysystem.lan/SendEmail/?Requestid=122d8f273465"" rel=""nofollow noreferrer"">https://mysystem.lan/SendEmail/?Requestid=122d8f273465</a>.</p>

<p>since the automation process not happens in the client side, the user is not logged in to the system so the action SendEmail will not run because the httpContext.User property will be null.</p>

<p>Thanks to the parameter Requestid in the url, i can resolve the UserId who created the request and i want to mock the ASP.NET Identity to be the identity of that user and that the GetUserId() extension method will work too (since mocking not affects that kind of methods).</p>

<p>All the answers i saw here explaining how to mock the identity by creating an instance of the controller for unit testing but this situation is different because i need to mock the identity inside inside the controller action when the server is getting the request <a href=""https://mysystem.lan/SendEmail/?Requestid=122d8f273465"" rel=""nofollow noreferrer"">https://mysystem.lan/SendEmail/?Requestid=122d8f273465</a>.</p>

<p>Can you suggest how to do that?</p>
",https://stackoverflow.com/questions/50240550/asp-net-identity-making-actions-on-behalf-of-someone,"['c#', 'asp.net-mvc', 'asp.net-identity']",162,FALSE,0,0
Unit test for a sub-method which called from main method and include http-request authoraztion,"<p>I faced to a really complicated scenario, hope you guys give me a hint. </p>

<p>So I have a main method, which is a api endpoint, this method call another method to check if  the user is authorized to use this endpoint or not. 
The sub-endpoint which I called it apiAuthorazation send a get request to a thirdparty url, and this third-party return a response which says this user is authorized, or not! </p>

<p>So I already have a unit test for the main method, but now I want add this authorization part to it. I know I can use muck libs like <a href=""https://scotch.io/tutorials/nodejs-tests-mocking-http-requests"" rel=""nofollow noreferrer"">Nock</a> or other similar libraries, but my problem is how can I add this sub-method to my uit test.</p>

<p>This is my api endpoint method : </p>

<pre><code>module.exports.api = (event, context, callback) =&gt; {
     // Authorization
     let getBearertoken = event.headers.Authorization.replace(""Bearer "", '');
     let isAuhtorized = utilities.apiAuthorazation(getBearertoken);
     //Some other Codes
}
</code></pre>

<p>As you can see I passed a bearer token to my sub-method, and apiAuthorazation method will going to send this token to a third-party api, and  the method is like this : </p>

<pre><code>module.exports.apiAuthorazation = function (token){
    let url = process.env.authApiUrl 
    requestLib(`${url}/${token}`, function (error, response, body) {
        if (error) console.log('Error while checking token :', error);
        if(response.isValidUser){
           return true;
        }
        else{
           return false;
        }
    });
}
</code></pre>

<p>Now my question is how can I include this sub-method to my main method unit test. I use mocha and chai for unit testing, bceause the berear token will expire soon, so when I run the test, I send a sample event which have the berear token in it, but it's already expired, so its kind of useless.</p>
",https://stackoverflow.com/questions/50828799/unit-test-for-a-sub-method-which-called-from-main-method-and-include-http-reques,"['javascript', 'node.js', 'unit-testing', 'mocking', 'mocha.js']",115,TRUE,0,1
In the TDD how do you write tests for code that inherently have side effects?,"<p>If a function's side effects are inherent within the design how do I develop such a function?</p>

<p>For instance if I wanted to implement a function like http.get( ""url"" ), and I stubbed the side effects as a service with dependency injection it would look like:</p>

<pre><code>var http = {
  ""get"": function( url, service ) {
    return promise(function( resolve ) {
      service( url ).then(function( Response ) {
        resolve( Response );
      });
    });
  }
}
</code></pre>

<p>...but I would then need to implement the service which is identical to the original http.get(url) and therefore would have the same side effects and therefore put me in a development loop. Do I have to mock a server to test such a function and if so what part of the TDD development cycle does that fall under? Is it integration testing, or is it still unit testing?</p>

<p>Another example would be a model for a database. If I'm developing code that works with a database, I'll design an interface, abstract a model implementing that interface, and pass it into my code using dependency injection. As long as my model implements the interface I can use any database and easily stub it's state and responses to implement TDD for other functions which interact with a database. What about that model though? It's going to interact with a database- it seems like that side effect is inherent within the design, and abstracting it away puts me into a development loop when I go to implement that abstraction. How do I implement the model's methods without being able to abstract them away?</p>
",https://stackoverflow.com/questions/49418491/in-the-tdd-how-do-you-write-tests-for-code-that-inherently-have-side-effects,"['tdd', 'side-effects']",1249,TRUE,6,2
"Why is the purpose for setup, teardown, and cycles in Benchmark.js?","<p>I know the formal descriptions:</p>

<blockquote>
  <p><strong>Setup</strong>: create the expected state for the test.<br>
  <strong>Teardown</strong>: Do necessary clean-up operations.  </p>
</blockquote>

<p>However, why is this necessary, especially in Benchmark.js ? Why the need for different test cycles (as defined in Benchmark.js in <a href=""http://monsur.hossa.in/2012/12/11/benchmarkjs.html"" rel=""nofollow noreferrer"">this</a> article) ?
I've observed that in all cases I can think of (and I think in all other cases as well), you can just move the set-up code to the preparation code (code outside of the benchmark/test), and perhaps the teardown code to the end of your code, and the functionality is essentially the same (I've looked at a few jsperf.com tests as well, and as far as I know, this is true of them as well).</p>

<p>For example, here is a benchmark I created, this version uses Setups and Teardowns:  </p>

<pre><code>const bench = new Benchmark(
  'TicTacToeBenchmark',
  // The function to test
  () =&gt; {
    ticTacToe.addEvent(
      'turn',
      player =&gt; {
        turnText.innerHTML =
          'It\'s ' + (player['id'] === 1 ? 'X' : 'O') + '\'s turn.';
      }
    );
  },
  {
    'setup': () =&gt; {
      const players = [
        {
          char: '&amp;#10005;',
          className: 'playerX',
          id: 1,
        },
        {
          char: '&amp;#9711;',
          className: 'playerY',
          id: 2,
        },
      ];
      const ticTacToe = new TicTacToe(3, players);
    }
  }
);

bench.run();

console.log(bench); // 'mean' is 5e-7 seconds
</code></pre>

<p>Same example, except, everything necessary for the test is declared with the rest of the page:</p>

<pre><code>const players = [
  {
    char: '&amp;#10005;',
    className: 'playerX',
    id: 1,
  },
  {
    char: '&amp;#9711;',
    className: 'playerY',
    id: 2,
  },
];
const ticTacToe = new TicTacToe(3, players);

const bench = new Benchmark(
  'TicTacToeBenchmark',
  // The function to test
  () =&gt; {
    ticTacToe.addEvent(
      'turn',
      player =&gt; {
        turnText.innerHTML =
          'It\'s ' + (player['id'] === 1 ? 'X' : 'O') + '\'s turn.';
      }
    );
  }
);

bench.run();

console.log(bench); // 'mean' is 7e-7 seconds
</code></pre>

<p>Mayhaps the difference is more discernible in Unit Testing ? I don't know. Could you please provide a few cases where this would be different ? Or explain why the tests have to be run within iterations which are run within cycles (essentially, like 2 loops, cycles being the outer one) ?</p>

<p>All content that I can find online on this topic is basically a re-utterance of the definitions of Setup and Teardown with different wording, and unfortunately, there is no Wikipedia entry for this topic.</p>
",https://stackoverflow.com/questions/50471459/why-is-the-purpose-for-setup-teardown-and-cycles-in-benchmark-js,"['javascript', 'unit-testing', 'benchmarking', 'benchmark.js']",359,TRUE,5,1
How can pytest-cov report coverage of python code that is executed as a result of pexpect.spawn?,"<p>I have a Python project that uses pytest-cov for unit testing and code coverage measurement.</p>

<p>The directory structure for my project is:</p>

<pre><code>rift-python
+- rift                        # The package under test
|  +- __init__.py
|  +- __main__.py
|  +- cli_listen_handler.py
|  +- cli_session_handler.py
|  +- table.py
|  +- ...lots more...
+- tests                       # The tests 
|  +- test_table.py
|  +- test_sys_2n_l0_l1.py
|  +- ...more...
+- README.md
+- .travis.yml
+- ...
</code></pre>

<p>I use Travis to run <code>pytest --cov=rift tests</code> for every checkin, and I use codecov to view the code coverage results.</p>

<p>The package under test offer a command line interface (CLI) which reads commands from stdin and produces output on stdout. It is started as <code>python rift</code>.</p>

<p>The tests directory contains two types of tests.</p>

<p>The first type of tests is traditional unit tests that test an individual class. For example, the test test_table.py imports table.py, and performs traditional pytest tests (using assert etc.) Code coverage measurement works as expected for these tests: codecov accurately reports which lines in the rift package are or are not covered by the test.</p>

<pre><code># test_table.py (codecov works)

import table

def test_simple_table():
    tab = table.Table()
    tab.add_row(['Animal', 'Legs'])
    tab.add_rows([['Ant', 6]])
    ...
    tab_str = tab.to_string()
    assert (tab_str == ""+--------+------+\n""
                       ""| Animal | Legs |\n""
                       ""+--------+------+\n""
                       ""| Ant    | 6    |\n""
                       ""+--------+------+\n""
                       ...
                       ""+--------+------+\n"")
</code></pre>

<p>The second type of test uses pexpect: it uses <code>pexpect.spawn(""python rift"")</code> to start the rift package. It then uses <code>pexpect.sendline</code> to inject commands into the CLI (stdin) and it used <code>pexpect.expect</code> to check the output of the commands on the CLI (stdout). The test functionality is working fine, but codecov is not reporting the code coverage for these tests.</p>

<pre><code># test_sys_2n_l0_l1.py (codecov does not pick up coverage of rift package)
# Greatly simplified example

import pexpect

def test_basic():
    rift = pexpect.spawn(""python rift"")
    rift.sendline(""cli command"")
    rift.expect(""expected output"")  # Throws exception if expected output not seen
</code></pre>

<p>QUESTION: How can I get code coverage measurements to report the covered line in the spawned rift package for the 2nd type of test using pexpect?</p>

<p>Note: I omitted several what I believe to be non-relevant details, full source code at <a href=""https://github.com/brunorijsman/rift-python"" rel=""nofollow noreferrer"">https://github.com/brunorijsman/rift-python</a> (UPDATE: this repo now contains the working solution suggested in the answer)</p>
",https://stackoverflow.com/questions/51662884/how-can-pytest-cov-report-coverage-of-python-code-that-is-executed-as-a-result-o,"['python', 'unit-testing', 'pytest', 'pexpect', 'pytest-cov']",3526,TRUE,4,2
Adding a resource file to iOS in a native react native module,"<p>I'm working on a native react native module, where I need a JSON resource file. I cannot figure out how to make this file available for the iOS side for either unit testing in the module or when serving a react native application.</p>

<p>I've been trying to put the file into a folder (<code>Resources</code> or <code>SupportFiles</code> as folder name makes no difference) on the root level of the ios-folder of the module. When I drag it to the XCode (9.3.1) project navigator, it gets added to the ""Tests""-target of the module (the lego brick icon), under <code>Build Phases</code> --> <code>Copy Bundle Resources</code>. I have also tried adding it to <code>Build Phases</code> --> <code>Copy Files</code> under the real module build targets (the ones with facade-icons).</p>

<p>Running <code>NSLog(@""%@"", [[NSBundle mainBundle] bundlePath]);</code> using a unit test I get a path:
<code>/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Xcode/Agents</code></p>

<p>Neither my file nor the folder get transferred to that path. If I manually copy the file there it opens without problems from my code (as accessed from the <code>mainBundle</code>, but that is not a sustainable solution.</p>

<p>I was wondering whether the resource files would only be copied to destination during a full build operation? The module builds successfully for the unit tests, but a full build has not been defined, as the module is not intended to run by itself. I also tried building my test app, which exercises the module, but couldn't find the file in any of the build results there either.</p>

<p>All in all this should be trivial (and on the Android-side it was). What am I missing?</p>
",https://stackoverflow.com/questions/50647770/adding-a-resource-file-to-ios-in-a-native-react-native-module,"['ios', 'objective-c', 'xcode', 'react-native']",1699,FALSE,3,1
Don&#39;t mock domain objects rule?,"<p>The most experienced developer in my current team has set a few hard rules based on best practices we should follow. Among them is ""You never ever mock domain object"". I asked him why we couldn't but he never had time to give me a proper answer. Now he's away for a week, and I reached a peak distrust to that rule, here's my situation.</p>

<p>My domain object has an <code>Update</code> method with several parameters, one being an interface for a calculator. It then updates a few fields, runs the calculators and assign its results to some other of its fields.</p>

<p>The proper unit test for the <code>Update</code> method itself is reasonably long.</p>

<p>Now I have some piece of code which do a few things then call <code>Update</code> on such a domain object.</p>

<p>I would normally mock the objects, and just check the <code>Update</code> method is being called with the proper arguments. But now, I have to test it's being properly called, by checking its fields and mocking the calculator then same way I did when unit testing the <code>Update</code> method itself. And I would have to do that everywhere the <code>Update</code> methods gets called.
How fun will it be when the <code>Update</code> method change a bit, and every of those tests suddenly break and need refactoring... I feels this rule is just like shooting myself in the foot..</p>

<p>So I need to know, why You never ever mock domain object""?</p>
",https://stackoverflow.com/questions/53371495/dont-mock-domain-objects-rule,"['unit-testing', 'domain-driven-design']",774,TRUE,3,3
How to instantiate UrlHelper for a Controller Unit Test in Asp.Net Core 2.0,"<p>I am writing unit tests for my Asp.Net Core 2.0 controllers. Each controller is injected with an IUrlHelper service to facilitate creating Hateoas links. This service is registered in the ConfigureServices method in the Startup class. Here a snapshot of my Startup class:</p>

<pre><code>using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Infrastructure;

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton&lt;IActionContextAccessor, ActionContextAccessor&gt;();
        services.AddScoped&lt;IUrlHelper, UrlHelper&gt;(implementationFactory =&gt;
        {
            var actionContext = 
                implementationFactory.GetService&lt;IActionContextAccessor&gt;()
                .ActionContext;
            return new UrlHelper(actionContext);
        });
    }
}
</code></pre>

<p>Sample Controller:</p>

<pre><code>using Microsoft.AspNetCore.Mvc;

public class MyApiController : Controller
{
    private readonly IUrlHelper _urlHelper;

    public MyApiController(IUrlHelper urlHelper)
    {
        _urlHelper = urlHelper;
    }

    // At least 5 actions and each requires _urlHelper to create Hateoas links
}
</code></pre>

<p>Where I am stuck is I don't know how to initialize the UrlHelper class inside an unit test class.</p>

<p>What I have tried so far:</p>

<hr>

<p><strong>Mocking UrlHelper</strong></p>

<p>I found <a href=""https://rovani.net/Mock-Controller-Url/"" rel=""nofollow noreferrer"">this article</a>, but I prefer to <em>not</em> mock the UrlHelper service and instead initialize it for the real API under test, because mocking requires too much effort to write out all mocked paths. The effort to test my whole API would be <em>number of controllers</em> * <em>number of actions</em> * <em>number of links per action</em>.</p>

<p><strong>Starting a TestServer</strong></p>

<p>I found <a href=""https://learn.microsoft.com/en-us/aspnet/core/testing/integration-testing?view=aspnetcore-2.0"" rel=""nofollow noreferrer"">this MS article</a> on creating a TestServer. However, this would already be an integration test and I would like to stick to unit testing as long as possible. If there is no way to avoid starting a test server, which I am currently playing around with, then I don't know how to get an instance of UrlHelper from the test server.</p>

<hr>

<p>Is there any way to get an instance of UrlHelper for the API under test in my test classes, preferably without starting a test server, and if the test server is unavoidable, how do I get the UrlHelper instance from the test server?</p>
",https://stackoverflow.com/questions/50307933/how-to-instantiate-urlhelper-for-a-controller-unit-test-in-asp-net-core-2-0,"['c#', 'unit-testing', 'asp.net-core-2.0']",1512,TRUE,2,1
SQL Server: Table-value UDF with table-value parameter from inside view,"<p>I'm building a database-contained unit-testing framework.<br>
The details aren't important, but this premise has led me into some unusual situations.</p>

<p>Right now, I'm trying to create a view for some specific unit test data, and I'm trying to:<br>
<code>CREATE VIEW [foo] AS SELECT * FROM TableValueUDF ( TableValueParam )</code><br>
(Side note: moving the UDF logic into the view itself, would result in huge amounts of code duplication across dozens of database objects, if not hundreds - which is why I'm avoiding it.)</p>

<p>The obvious problem here is, you can't pass a variable into the view.<br>
But the unit test data is technically static ... so I reverted to:<br>
<code>CREATE VIEW [foo] AS SELECT * FROM TableValueUDF ( ( SELECT * FROM ( VALUES ... ) ) )</code><br>
... where the end-user-developer can manually define their desired unit tests, for every test view.</p>

<p>And of course SQL server is very unhappy with this. <em>(Error messages indicated in code below.)</em><br>
But I've never encountered this scenario before, and I have no idea how to rearrange this query to accomplish what I'm trying to do.<br>
(Is this a situation where <code>CROSS APPLY</code> would be helpful? I don't really understand cross apply.)</p>

<p>My actual code is much larger and more complex than this, so I've been testing with a simple example scenario to help isolate the problem in repro.</p>

<p>Naturally, the error messages don't make any sense. <em>(Indicated inside the code where they appear)</em><br>
And Googling these error messages yields completely different situations, unhelpful here.</p>

<p>Example UDT and UDF definitions:</p>

<pre><code>/* Table-value UDT */
CREATE TYPE [dbo].[IntNameList]
AS TABLE
(
    [Value]    INT             NOT NULL ,
    [NameText] NVARCHAR ( 48 ) NOT NULL
)

GO

/* Table-value UDF with table-value parameter */
CREATE FUNCTION [dbo].[ProcessData]
(
    @tableValueParam [IntNameList] READONLY
)
RETURNS TABLE AS RETURN
(
    SELECT
        [Value]    ,
        [NameText] ,

        /* Simple example calculation: Is [Value] odd or even? */
        CAST ( IIF ( [Value] % 2 &lt;&gt; 0 , 1 , 0 ) AS BIT )
     AS [ValueOdd]

    FROM @tableValueParam
)

GO
</code></pre>

<p>Testing with a declared variable, to ensure UDF operates as expected:</p>

<pre><code>DECLARE @param [IntNameList]

INSERT INTO @param VALUES

    ( /* Value    */ 110 ,
      /* NameText */ N'Steve'
    ) ,

    ( /* Value    */ 111 ,
      /* NameText */ N'Mason'
    ) ,

    ( /* Value    */ 112 ,
      /* NameText */ N'Kimberly'
    )

/* Works as expected */
SELECT * FROM [dbo].[ProcessData] ( @param )

GO
</code></pre>

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

<p>Testing with <code>CREATE VIEW</code>, which is the actual scenario I'm trying to achieve:</p>

<pre><code>/*  Errors:

    1) ""Only one expression can be specified in the select list
            when the subquery is not introduced with EXISTS.""

    2) ""Operand type clash: int is incompatible with IntNameList""
*/

CREATE VIEW [dbo].[ProcessExampleData] AS

SELECT * FROM [dbo].[ProcessData] ( ( SELECT * FROM ( VALUES

        ( /* Value    */ 110 ,
          /* NameText */ N'Steve'
        ) ,

        ( /* Value    */ 111 ,
          /* NameText */ N'Mason'
        ) ,

        ( /* Value    */ 112 ,
          /* NameText */ N'Kimberly'
        )

    ) AS [ExampleData] ( [Value]    ,
                         [NameText] ) ) )
</code></pre>
",https://stackoverflow.com/questions/52771303/sql-server-table-value-udf-with-table-value-parameter-from-inside-view,"['sql', 'sql-server', 'view', 'user-defined-functions', 'sql-server-2017']",480,FALSE,2,0
"How to avoid hard-coding database path using flask, SQLAlchemy, and declarative_base","<p>Flask-SQLAlchemy suggests the <a href=""http://flask.pocoo.org/docs/1.0/patterns/sqlalchemy/#declarative"" rel=""nofollow noreferrer"">Declarative</a> pattern for setting up a database connection. The example hard-codes a single database path, and it seems like I should avoid that, so that I can configure different databases for unit testing, local development, and then eventually production. </p>

<p>this is their database.py:</p>

<pre><code>from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine('sqlite:////tmp/test.db', convert_unicode=True)
db_session = scoped_session(sessionmaker(autocommit=False,
                                     autoflush=False,
                                     bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()

def init_db():
    # import all modules here that might define models so that
    # they will be registered properly on the metadata.  Otherwise
    # you will have to import them first before calling init_db()
    import yourapplication.models
    Base.metadata.create_all(bind=engine)
</code></pre>

<p>But I haven't been able to figure out how to avoid hard-coding this db path. </p>

<h2>Environment variables:</h2>

<p>I could just replace the <code>sqlite:///....</code> path with an environment variable. But that would require some way to have <code>pytest</code> run with one set of environment vars and <code>flask run</code> use a different set. I'd much rather have my unit tests keep track of their own temporary database.[2] I'd also like <code>create_app()</code> that creates the Flask app to take a database path that's a config variable. </p>

<h2>Import database.py within an application context</h2>

<p>I thought I could replace the database path with <code>current_app.config['DB']</code>, and import the database within <code>with app.app_context()</code>. But the Model classes need to import Base, and I can't subclass Base within the application context. So when the models get loaded, they're loaded outside the application context and that throws runtime errors. </p>

<h2>So what's the right way to use declarative_base in a flask app with unit tests?</h2>

<p>Thanks for your help!</p>

<p>[2]: If that's what I should do, then I can live with it. But it seems messy to be using env vars there, when I'm configuring a flask app with its own config vars too.</p>
",https://stackoverflow.com/questions/51010285/how-to-avoid-hard-coding-database-path-using-flask-sqlalchemy-and-declarative,"['python', 'flask', 'flask-sqlalchemy']",1324,TRUE,2,1
Repeatably hashing an arbitrary Python tuple,"<p>I'm writing a specialised unit testing tool that needs to save the results of tests to be compared against in the future. Thus I need to be able to consistently map parameters that were passed to each test to the test result from running the test function with those parameters for each version. I was hoping there was a way to just hash the tuple and use that hash to name the files where I store the test results.</p>

<p>My first impulse was just to call <code>hash()</code> on the tuple of parameters, but of course that won't work since <code>hash</code> is randomized between interpreter instances now.</p>

<p>I'm having a hard time coming up with a way that works for whatever arbitrary elements that might be in the tuple (I guess restricting it to a mix of ints, floats, strings, and lists\tuples of those three would be okay). Any ideas?</p>

<p>I've thought of using the <code>repr</code> of the tuple or pickling it, but repr isn't guaranteed to produce byte-for-byte same output for same input, and I don't think pickling is either (is it?)</p>

<p>I've seen <a href=""https://stackoverflow.com/questions/5884066/hashing-a-dictionary"">this</a> already, but the answers are all based on that same assumption that doesn't hold anymore and don't really translate to this problem anyway, a lot of the discussion was about making the hash not depend on the order items come up and I do want the hash to depend on order.</p>
",https://stackoverflow.com/questions/48513058/repeatably-hashing-an-arbitrary-python-tuple,"['python', 'hash']",780,TRUE,2,2
react-redux 4.0: testing mapStateToProps and mapDispatchToProps?,"<p>react-redux 4.0 now uses the context API, which is great! However, when trying to update a project of mine, everything is working but my unit tests starting failing.</p>

<p>For context, this is a very barebones ""boilerplate"" project I work on for fun. For demo-purposes, it is basically a to-do app (we all love todos, right?).</p>

<p>Now, for my containers I do some unit testing, but very basic. Basically, I want to make sure that both mapStateToProps and mapDispatchToProps are receiving what they should be receiving. I don't care how, just that they are in.</p>

<p>Here's my ""ConnectedToDos"" component:</p>

<pre><code>import { injectIntl } from 'react-intl'
import { connect } from 'react-redux'
import { createStructuredSelector } from 'reselect'

import {
  addTodo,
  completeTodo,
  deleteTodo,
  loadTodos,
  makeGetTodos,
} from './duck'

import ToDos from './view'

const mapStateToProps = createStructuredSelector({
  todos: makeGetTodos(),
})

const mapDispatchToProps = {
  handleComplete: completeTodo,
  handleSubmit: addTodo,
  handleDelete: deleteTodo,
  requestTodos: loadTodos,
}

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(ToDos))
</code></pre>

<p>Now, to test this I used to do the following:</p>

<pre><code>import React from 'react'
import PropTypes from 'prop-types'
import configureStore from 'redux-mock-store'
import { shallow, mount } from 'enzyme'
import { fromJS } from 'immutable'
import { MemoryRouter } from 'react-router-dom'
import { IntlProvider } from 'react-intl'

import ConnectedToDos from 'modules/ToDos'

describe('Connected &lt;ToDos /&gt;', () =&gt; {
  const initialState = fromJS({
    resources: {
      todos: [
        { title: 'A todo', description: 'Do me!', id: '1', done: false },
        { title: 'A todo', description: 'Do me!', id: '2', done: true },
        { title: 'A todo', description: 'Do me!', id: '3', done: false },
        { title: 'A todo', description: 'Do me!', id: '4', done: true },
      ],
    },
  })

  let mockStore
  let store

  beforeAll(() =&gt; {
    mockStore = configureStore([])
    store = mockStore(initialState)
  })

  it('props should match mapStateToProps', () =&gt; {
    const wrapper = shallow(&lt;ConnectedToDos store={store} /&gt;)

    expect(wrapper.prop('todos')).toEqual(initialState.getIn(['resources', 'todos']))
  })

  it('props should match mapDispatchToProps', () =&gt; {
    const wrapper = mount(
      &lt;IntlProvider locale=""en"" messages={{ en: {} }}&gt;
        &lt;MemoryRouter&gt;
          &lt;ConnectedToDos /&gt;
        &lt;/MemoryRouter&gt;
      &lt;/IntlProvider&gt;,
      {
        context: { store },
        childContextTypes: { store: PropTypes.object.isRequired },
      },
    )

    wrapper.find('input[type=""checkbox""]').first().simulate('change')
    wrapper.find('form').simulate('submit')
    wrapper.find('Icon[name=""DELETE""]').first().simulate('click')

    const actions = store.getActions()
    const todosActions = actions.filter(action =&gt; action.type.includes('/todos/'))

    expect(todosActions).toHaveLength(4)
  })
})
</code></pre>

<p>However, this throws a nice warning now:</p>

<blockquote>
  <p>Invariant Violation: Could not find ""store"" in the context of
  ""Connect(InjectIntl(ToDos))"". Either wrap the root component in a
  <code>&lt;Provider&gt;</code>, or pass a custom React context provider to <code>&lt;Provider&gt;</code> and
  the corresponding React context consumer to <code>Connect(InjectIntl(ToDos))</code>
  in connect options.</p>
</blockquote>

<p>Cool. But now I'm wondering what's the best way to test my containers?</p>

<p>I've tried a myriad of ways, the latest one looks as follows:</p>

<pre><code>  it('props should match mapStateToProps', () =&gt; {
    const wrapper = shallow(&lt;ConnectedToDos /&gt;, { context: { store } })

    expect(wrapper.prop('todos')).toEqual(initialState.getIn(['resources', 'todos']))
  })
</code></pre>

<p>But it fails. It seems that, whatever I do, the <code>wrapper.context()</code> is always an empty object.</p>

<p>I can't copy-paste ALL my code here, but I have a repository that you can clone and play with yourself: <a href=""https://github.com/enrique-ramirez/react-redux-boilerplate"" rel=""nofollow noreferrer"">https://github.com/enrique-ramirez/react-redux-boilerplate</a></p>

<p>The test that's failing is on <code>src/modules/ToDos/tests/index.test.js</code>. </p>

<p><strong>TL;DR</strong> How can I test my <code>mapStateToProps</code> and <code>mapDispatchToProps</code> using the new react-redux?</p>
",https://stackoverflow.com/questions/53887623/react-redux-4-0-testing-mapstatetoprops-and-mapdispatchtoprops,"['reactjs', 'redux', 'react-redux']",1238,TRUE,1,1
cannot see how to mock or write unit tests without marking too many methods virtual,"<p>We are starting to add unit testing to our solution and I am writing unit tests using Moq.</p>

<p>I wrote my first 10 tests without mocking and was fine, but now that I have reached tests that require mocking, every method I try to test seems to require partial mocking (well; the method I am testing needs to have actual implementation and every other inner method it calls need to be faked).</p>

<p>Problem is to write my tests I have to make too many changes to the original code to make it testable. Adding interfaces to every class is one thing, and removing dependencies from method and having them as parameters might be acceptable, too (though I guess is going to happen way too often), but it seems aslo that I need to mark every dependency method I need to fake as virtual. This is way too much changes to the original code just to make it testable.</p>

<p>So; my question is, is this how I am supposed to do this, or is there a way of writing unit tests without this many changes, and virtualizing the methods also?</p>

<p>Here is example of 1 unit test I am writing:</p>

<pre><code>public class ContrastControlViewModel : ViewModelBase, IContrastControlViewModel
{
    public void UpdateCompositePropertyValues(String propertyName)
    {
        if (SelectedVideoProcessingSubstream != null)
        {
            switch (propertyName)
            {
                case ""ContrastCurve"":
                    if (_enableContrastControlUpdate)
                    {
                        UpdateContrastCurve();  // Only updates the local line graph display of the contrast controls
                        _enableContrastControlUpdate = false;
                    }
                    break;
                default:
                    break;
            }
        }
    }
    public IVideoProcessingSubstreamViewModel SelectedVideoProcessingSubstream
    {
        get {...}
        set {...}
    }
}

[TestClass]
public class ContrastControlViewModelTests
{
    [TestMethod]
    public void UpdateCompositePropertyValues()
    {
        //scenarios:                8 tests, could be separated
        foreach (String input_propertyName in new string[]{""ContrastCurve"", ""other""})
            foreach (var input_SelectedVideoProcessingSubstream in new IVideoProcessingSubstreamViewModel[] { null, (IVideoProcessingSubstreamViewModel)(new Mock&lt;IVideoProcessingSubstreamViewModel&gt;()).Object})
                foreach (bool input_enableContrastControlUpdate in new bool[]{ true, false})
                {
                    //Arrange:
                    bool UpdateContrastCurve_called = false;
                    var vm = new Mock&lt;ContrastControlViewModel&gt;(10, 10, 200, 200, 240, 240) { CallBase = true };
                    vm.SetupProperty(m =&gt; m.SelectedVideoProcessingSubstream);          //throws NotSupportedException
                    vm.SetupProperty(m =&gt; m._enableContrastControlUpdate);
                    vm.Setup(m =&gt; m.UpdateContrastCurve()).Callback(() =&gt; UpdateContrastCurve_called = true);

                    //Act:
                    vm.Object._enableContrastControlUpdate = input_enableContrastControlUpdate;
                    vm.Object.SelectedVideoProcessingSubstream = input_SelectedVideoProcessingSubstream;
                    vm.Object.UpdateCompositePropertyValues(input_propertyName);

                    //Assert:
                    Assert.IsTrue(UpdateContrastCurve_called == (input_propertyName == ""ContrastCurve"" 
                        &amp;&amp; input_SelectedVideoProcessingSubstream != null &amp;&amp; input_enableContrastControlUpdate == true));
                }         
    }
}
</code></pre>

<p>So; right now I get a NotSupportedException because ""SelectedVideoProcessingSubstream"" has to be virtual to be faked. If I start doing that everything ends up getting marked virtual. Later, I end up even marking methods of other classes virtual.</p>
",https://stackoverflow.com/questions/48591388/cannot-see-how-to-mock-or-write-unit-tests-without-marking-too-many-methods-virt,"['c#', 'unit-testing', 'moq']",102,TRUE,1,1
How to get host name when testing using GAE?,"<p>When using the local development server, the port for my default service always defaults to 8080. However, when I use <code>aetest</code>, the port number always changes. The command used to start the local server when unit testing specifies <code>--port=0</code>. However, since this is in the app engine package, I do not want to modify it. I also can't specify the port number manually since tests are run using <code>go test</code> and not <code>dev_appserver.py</code>.</p>

<p><strong>What I need</strong></p>

<p>The code I am testing requires a particular response from a different microservice to continue execution successfully. To keep testing to this microservice, I am trying to set up a fake endpoint to provide me with the response I need. </p>

<p><em>Sample of code being tested</em></p>

<pre><code>func Sample(c *gin.Context) {
    ...
    url := os.Getenv(""some_service"") + ""/some-endpoint""
    req, err := http.NewRequest(""POST"", url, r.Body)
    if err != nil {
        // error handling
    }
    ...
}
</code></pre>

<p>I need the host of the current service being tested to be able to set dummy environment variables for another microservice it interacts with. The host url should be the url of the service currently undergoing tests. This way I can use factory responses since I am not testing the other services in this set of tests.</p>

<p><strong>What I've Tried</strong></p>

<ul>
<li>Using <code>appengine.DefaultVersionHostname()</code>, however this returns an empty string</li>
<li>Using the http request I create to get the url from that, however it does not include the host as needed (just the path)</li>
</ul>

<p><strong>Question</strong></p>

<p>Is there any way to obtain the host for the local development server when running unit tests in GAE? Or, is there a way to specify the port number for app engine tests?</p>
",https://stackoverflow.com/questions/51368456/how-to-get-host-name-when-testing-using-gae,"['unit-testing', 'google-app-engine', 'go']",259,TRUE,1,1
"Ruby: require vs include/extend: Using a module inside another, but not exposing to users","<p>I was having trouble understanding an error while unit testing my module, which is a mixin.</p>

<p>Suppose the mixin to be tested is module A:</p>

<pre class=""lang-rb prettyprint-override""><code>require 'path/b'    
module A
    def methodA()
        puts methodB.attr1 
    end
end
</code></pre>

<p>And it depends on another mixin B which was defined in a file at path/b.rb</p>

<pre class=""lang-rb prettyprint-override""><code>module B
    def methodB
       return someObject #that has property 'attr1'
    end       
end
</code></pre>

<p>Now, we have a class to unit test module A</p>

<pre class=""lang-rb prettyprint-override""><code>require 'path/moduleA'
class TestA
    include Path::moduleA
end

describe 'test moduleA.methodA'
  it 'does something'
     testObject = TestA.new
     testObject.methodA()
     expect(....)
  end
end  
</code></pre>

<p>I get following error on running the rspec test</p>

<pre><code>NameError:
   undefined local variable or method `methodB' for #&lt;TestA:0x00007f77a03db9a8&gt;
</code></pre>

<p>I am able to resolve it by one of following ways:</p>

<ol>
<li>including module B in module A</li>
<li>including module B in class TestA</li>
</ol>

<p><strong>Questions</strong></p>

<ol>
<li><p>I am not clear why include is required to get access to methodB in 
module A and class TestA when 'require' was already added in  module A.</p></li>
<li><p>My intention is to use methods of module B in module A, but not let users of module A access module B methods automatically. </p>

<ul>
<li><p>resolution 1 above gives users of A, access to B's methods</p></li>
<li><p>resolution 2 forces users of A (user -> the unit test class in this example)  to include A's dependency B directly, even though user is only interested in accessing A's methods.</p></li>
</ul></li>
</ol>

<p>Hence, both resolutions don't achieve what I want. Is there a way to achieve it?</p>

<p>I'm new to Ruby so may be it doesn't support this. I'm from Java background where I would model A and B as two classes, make an instance of B as field of A, then expose A's own public methods to users of A. But since they are mixins, I need to use modules in ruby.</p>
",https://stackoverflow.com/questions/52797777/ruby-require-vs-include-extend-using-a-module-inside-another-but-not-exposing,['ruby'],1827,TRUE,1,3
Angular DI - useFactory - Provider : Is there a way to invoke Provider Factory function second time when local State gets updated?,"<p>The scenario goes as follows:</p>

<p><strong>1. App has root module and it's constructor resolves a Promise and returns a Constant.</strong></p>

<pre><code>@NgModule({
    ....,
    providers : [
    ...
    { 
      provide: SAMPLE_INJECTOR_TOKEN,
      useFactory: sampleFactoryFn(SAMPLE_GLOBAL_CONSTANT.DATA)
    }
       ]
})
export class AppModule {
 constructor() {
  // To be clear: This code runs on window.onLoad(). window argument is actually window object
  setupPromiseAPI(window).then(data =&gt; {
   SAMPLE_GLOBAL_CONSTANT.DATA = data; // Once promise resolves this gets expected value. [ Step 3 ]
  }).catch({
      ...
  })

}
</code></pre>

<p><strong>2. As this value is an object and also, as it will be available at run time, I have created a Injection Token using ""useFactory"" and registered at the module level.</strong></p>

<pre><code>// Injector Token    
export SAMPLE_INJECTOR_TOKEN = new InjectionToken&lt;CustomDataType&gt;('SampleInjectorToken');

// Factory Function
export function sampleFactoryFn(data: CustomDataType) {
       return (/* No deps to be passed */): CustomDataType =&gt; data; // simply return what ever it received.
            }
</code></pre>

<p><strong>3. I have created a global constant initialized to null and passed as argument to the factory function, using which angular is constructing the Injector Token and assigning the value null (initial state) at bootstrap.</strong></p>

<pre><code>export const SAMPLE_GLOBAL_CONSTANT = {
    DATA: null // Initial State
}
</code></pre>

<p><strong>4. When promise gets resolved from Step 1, I am capturin the returned constant value from Promise and assiging to this declared Global Constant, as its a constant, obviously that is being updated and available all through the app.</strong></p>

<p>Also, angular documentation states that useFactory provider creates its value lazily, which I am understanding that it will created when its injected. If so, by the time code injects my Injection Token,  the global constant is updated. Still the injector token is having null.</p>

<p><strong>Q1. Is there a way, to invoke provider factory function with the updated local state, so that my injector token will have received value?</strong></p>

<p><strong>Q2. As am using global constant, its making the code work, but its not loosely coupled which also making unit testing hard. Are there any alternatives to consume received constant and use it in code, so that it will be loosely coupled?</strong></p>
",https://stackoverflow.com/questions/52010295/angular-di-usefactory-provider-is-there-a-way-to-invoke-provider-factory-f,"['angular', 'dependency-injection', 'angular-di']",1986,TRUE,0,1
How to validate values in a mocked async method with xunit?,"<p>I'd like to be able to validate the parameters passed to an async method in my unit tests. But since the method is async, the task that is performing the asserts has no affect on the unit test overall. The asserted exception isn't passed to the unit test framework (xunit). I'm mocking my repository methods, which are being called by an MVC IHostedService.</p>

<p>Example:</p>

<pre><code>CancellationTokenSource sourceToken = new CancellationTokenSource();

var repositoryMock = new Mock&lt;IRepository&gt;();
repositoryMock.Setup(x =&gt; x.BulkUpdate(It.IsAny&lt;IEnumerable&lt;MyDocument&gt;&gt;(), It.IsAny&lt;bool&gt;()))
    .ReturnsAsync((IEnumerable&lt;MyDocument&gt; notifications, bool upsert) =&gt;
{
    // verify all the event Ids are in the newly created Notifications (these will actually all be NULL since we can't set the eventIds in the Event object
    Assert.True(notifications.All(x =&gt; x.Detail != null));
    Assert.True(notifications.All(x =&gt; x.Map != null));

    sourceToken.Cancel();

    return notifications.Select(x =&gt; x.Id);
});

await Assert.ThrowsAsync&lt;TaskCanceledException&gt;(async () =&gt; await Task.Delay(20000, sourceToken.Token));
Assert.True(sourceToken.IsCancellationRequested);
</code></pre>

<p>The example here doesn't include starting up the MVC service, but the Startup creates my IHostedService as a singleton, which also starts it running immediately. It will eventually call this BulkUpdate method, and I want to be able to validate that the IHostedService is calling the BulkUpdate with the correct data. The CancellationTokenSource is used to signal the test can exit since the IHostedService has completed the work I want to be tested.</p>

<p>How the background service is started:
In unit test startup class:</p>

<pre><code>public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton&lt;IHostedService, MyBackgroundService&gt;();
}
</code></pre>

<p>We have a method that generates a IWebHostBuilder...</p>

<pre><code>internal static IWebHostBuilder GetWebHostBuilder(Mock&lt;IIRepository&gt; repositoryMock = null)
{
    var environment = ""Development""; //

    var builder = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile(""appsettings.json"", optional: false, reloadOnChange: true)
        .AddJsonFile($""appsettings.{environment}.json"", optional: true, reloadOnChange: true)
        .AddEnvironmentVariables();

    var configuration = builder.Build();

    var webHostBuilder = new WebHostBuilder()
            .UseEnvironment(environment)
            .UseConfiguration(configuration)
            .ConfigureServices(services =&gt;
            {
                // Add the repository mocks and the type of user thats needed for authentications in the Controller being tested
                // These will be added before the IntegrationTestStartup.ConfigureTransientServices method runs and adds
                // the repository objects.

                if(repositoryMock != null)
                    services.AddTransient&lt;IRepository&gt;((y) =&gt; { return repositoryMock.Object; });
            })
            .UseStartup&lt;UnitTestStartup&gt;(); // This is the Startup of AHENS

    return webHostBuilder;
}
</code></pre>

<p>That we use in out unit tests to inject mocked repositories for testing of the background services...</p>

<pre><code>TestServer testServer = new TestServer(TestBase.GetWebHostBuilder(repositoryMock));
</code></pre>

<p>This all ""works"", unless one of the asserts fail (throw an exception). How can I get the asserts to roll up to the unit test to fail the test? Is there a better way of doing this? We have test cases where we want to validate that the mocked repository methods DON'T get called, or get called multiple times. This is a unit testing of multithreaded application problem. </p>
",https://stackoverflow.com/questions/49514019/how-to-validate-values-in-a-mocked-async-method-with-xunit,"['asp.net-mvc', 'unit-testing', 'task', 'moq', 'xunit']",726,FALSE,0,1
OLE DB exception &quot;Class not registered&quot; only when running Unit Test,"<p>I have a Windows based C++ application/library which uses Excel environment as interface. The library retrieves information from an Access database. </p>

<p>The C++ library classes are based on Active Template Library for COM.</p>

<p>When I run/debug the library, everything works fine. The class function responsible for retrieving data from the Access database though COM, has no problem setting up the connection.</p>

<p>But when I run a unit cases (Microsoft C++ Unit Testing Framework), it fails when reaching the function OpenFromInitializationString in atldbcli.h.</p>

<pre><code>HRESULT OpenFromInitializationString(
                _In_z_ LPCOLESTR szInitializationString,
                _In_ bool fPromptForInfo = false) throw()
{
  CComPtr&lt;IDataInitialize&gt; spDataInit;

  HRESULT hr = CoCreateInstance(__uuidof(MSDAINITIALIZE), NULL, CLSCTX_INPROC_SERVER, __uuidof(IDataInitialize), (void**)&amp;spDataInit);

  if (FAILED(hr))
    return hr;

  hr = spDataInit-&gt;GetDataSource(NULL, CLSCTX_INPROC_SERVER, szInitializationString, __uuidof(IDBInitialize), (IUnknown**)&amp;m_spInit);

  if (FAILED(hr))
    return hr;
</code></pre>

<p>The latter call to GetDataSource fails, and returns ""class not registered"", when running the unit test. Same code succeeds when running or debbuging the whole application/library. <strong>What is even more puzzling is that the same solution runs on my colleagues computer, both the unit test and the actual applicaiton/library.</strong></p>

<p>I'm running Windows 10 64-bit and Office 365 ProPlus. I have Visual Studio 2017 installed. </p>

<p>I would greatly appreciate if anyone would know what's going on. Keep these in mind.</p>

<ul>
<li>The unit tests are not within a separate project, but only a separate file on in the main project.</li>
<li>Oledb32.dll is installed in following location C:\Program Files (x86)\Common Files\System\Ole DB\oledb32.dll (version 10.0.16299.15) </li>
</ul>

<p>The szInitializationString looks like this in both cases:</p>

<pre><code>L""Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;Data Source = C:\\Repos\\Xerf\\XerfLib\\XerfData.accdb;Mode = Share Deny None;Extended Properties = \""\"";Jet OLEDB:System database=\""\"";Jet OLEDB:Registry Path=\""\"";Jet OLEDB:Database Password=\""\"";Jet OLEDB:Engine Type=6;Jet OLEDB:Database Locking Mode=1;Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Global Bulk Transactions=1;Jet OLEDB:New Database Password=\""\"";Jet OLEDB:Create System Database=False;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica Repair=False;Jet OLEDB:SFP=False;Jet OLEDB:Support Complex Data=False;Jet OLEDB:Bypass UserInfo Validation=False;Jet OLEDB:Limited DB Caching=False;Jet OLEDB:Bypass ChoiceField Validation=False""
</code></pre>

<p>I have tried create a minimal project and it returns the same error. Here is the minimal code. </p>

<pre><code>#include ""stdafx.h""
#include &lt;string.h&gt;

int main()
{
    WCHAR  m_DBInitializationString[1024]{};
    WCHAR  m_DatabasePath[_MAX_PATH]{};
    int iTmp;

    CDataSource db;
    HRESULT hr;

    CoInitialize(NULL);

    size_t wclen = (sizeof m_DBInitializationString) / (sizeof m_DBInitializationString[0]);
    wcscpy_s(m_DatabasePath, _MAX_PATH, L""C:\\Repos\\Xerf\\XerfLib\\XerfData.accdb"");

    iTmp = swprintf_s(m_DBInitializationString, wclen, L""%s"", L""Provider=Microsoft.ACE.OLEDB.16.0;"");
    iTmp += swprintf_s(&amp;m_DBInitializationString[iTmp], wclen - iTmp, L""%s"", L""User ID=Admin;"");
    iTmp += swprintf_s(&amp;m_DBInitializationString[iTmp], wclen - iTmp, L""Data Source = %s;"", m_DatabasePath);
    iTmp += swprintf_s(&amp;m_DBInitializationString[iTmp], wclen - iTmp, L""%s"", L""Mode = Share Deny None;"");
    iTmp += swprintf_s(&amp;m_DBInitializationString[iTmp], wclen - iTmp, L""%s"", L""Extended Properties = \""\"";"");
    iTmp += swprintf_s(&amp;m_DBInitializationString[iTmp], wclen - iTmp, L""%s"", L""Jet OLEDB:System database=\""\"";"");
    iTmp += swprintf_s(&amp;m_DBInitializationString[iTmp], wclen - iTmp, L""%s"", L""Jet OLEDB:Registry Path=\""\"";"");
    iTmp += swprintf_s(&amp;m_DBInitializationString[iTmp], wclen - iTmp, L""%s"", L""Jet OLEDB:Database Password=\""\"";"");
    iTmp += swprintf_s(&amp;m_DBInitializationString[iTmp], wclen - iTmp, L""%s"", L""Jet OLEDB:Engine Type=6;"");
    iTmp += swprintf_s(&amp;m_DBInitializationString[iTmp], wclen - iTmp, L""%s"", L""Jet OLEDB:Database Locking Mode=1;"");
    iTmp += swprintf_s(&amp;m_DBInitializationString[iTmp], wclen - iTmp, L""%s"", L""Jet OLEDB:Global Partial Bulk Ops=2;"");
    iTmp += swprintf_s(&amp;m_DBInitializationString[iTmp], wclen - iTmp, L""%s"", L""Jet OLEDB:Global Bulk Transactions=1;"");
    iTmp += swprintf_s(&amp;m_DBInitializationString[iTmp], wclen - iTmp, L""%s"", L""Jet OLEDB:New Database Password=\""\"";"");
    iTmp += swprintf_s(&amp;m_DBInitializationString[iTmp], wclen - iTmp, L""%s"", L""Jet OLEDB:Create System Database=False;"");
    iTmp += swprintf_s(&amp;m_DBInitializationString[iTmp], wclen - iTmp, L""%s"", L""Jet OLEDB:Encrypt Database=False;"");
    iTmp += swprintf_s(&amp;m_DBInitializationString[iTmp], wclen - iTmp, L""%s"", L""Jet OLEDB:Don't Copy Locale on Compact=False;"");
    iTmp += swprintf_s(&amp;m_DBInitializationString[iTmp], wclen - iTmp, L""%s"", L""Jet OLEDB:Compact Without Replica Repair=False;"");
    iTmp += swprintf_s(&amp;m_DBInitializationString[iTmp], wclen - iTmp, L""%s"", L""Jet OLEDB:SFP=False;"");
    iTmp += swprintf_s(&amp;m_DBInitializationString[iTmp], wclen - iTmp, L""%s"", L""Jet OLEDB:Support Complex Data=False;"");
    iTmp += swprintf_s(&amp;m_DBInitializationString[iTmp], wclen - iTmp, L""%s"", L""Jet OLEDB:Bypass UserInfo Validation=False;"");
    iTmp += swprintf_s(&amp;m_DBInitializationString[iTmp], wclen - iTmp, L""%s"", L""Jet OLEDB:Limited DB Caching=False;"");
    iTmp += swprintf_s(&amp;m_DBInitializationString[iTmp], wclen - iTmp, L""%s"", L""Jet OLEDB:Bypass ChoiceField Validation=False"");

    hr = db.OpenFromInitializationString(m_DBInitializationString);

    return hr;
}
</code></pre>

<p>This code is included in the precompiled header stdafx.h</p>

<pre><code>#pragma once

#ifndef STRICT
#define STRICT
#endif

#include ""targetver.h""

#define m_dwRef                m_dwRefAtl
#define m_pOuterUnknown        m_pOuterUnknownAtl
#define InternalQueryInterface InternalQueryInterfaceAtl
#define InternalAddRef         InternalAddRefAtl
#define InternalRelease        InternalReleaseAtl

//#define _ATL_DEBUG_INTERFACES //Writes, to the output window, any interface leaks that are detected when _Module.Term is called.
//#define _ATL_DEBUG_QI         //Writes all calls to QueryInterface to the output window.
#define _ATL_APARTMENT_THREADED
#define _ATL_NO_AUTOMATIC_NAMESPACE
#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS  // some CString constructors will be explicit

//#define ATL_NO_ASSERT_ON_DESTROY_NONEXISTENT_WINDOW

#include &lt;atlbase.h&gt;
#include &lt;atlcom.h&gt;
#include &lt;atlctl.h&gt;
#include &lt;AtlConv.h&gt;

// DB access
#include &lt;atldbcli.h&gt;
#include &lt;atldb.h&gt;

using namespace ATL;
</code></pre>

<p>Best regards,
Johan</p>
",https://stackoverflow.com/questions/49255023/ole-db-exception-class-not-registered-only-when-running-unit-test,"['c++', 'com', 'oledb', 'atl']",1936,TRUE,0,1
Factory Method vs Constructor with ServletContext as Parameter,"<p>To test the health of all our applications we are including a Healthcheck servlet in each application. These healthchecks simply test the dependencies of each application. One of these dependency types are Sql server connections. To test the connections we have a method called <code>HealthCheckRunner.Result run()</code>. (Shown in the code below). The method will take a url, username, and password and attempt to connect to the server. </p>

<p>This method works fine but I have found that across all our apps I am still repeating a lot of code to retrieve the url, username, password, and driver from the context.xml. To save time and repetition I would like to refactor with either another constructor or a factory method, shown below in Options 1 and 2.</p>

<p>Neither method seems very appealing to me though. First the constructor is pretty messy and doesn't seem very user friendly. Second, the static method may be difficult to test. And lastly, they both take a ServletContext as a parameter. </p>

<p>Will unit testing the static method be difficult? For simplicity I'd rather stay away from PowerMock and only use Mockito. And also, will copies of ServletContext be created for every SqlHealthCheck I create? Or will they all use the same reference? And, since I'm only using a few values from the context would it be better to create another class and pass only the values I need? The solutions I have come up with are not great and I know there must be a better way.</p>

<pre><code>public class SqlHealthCheck extends HealthCheck {
private String url;
private String username;
private String password;
private String driver;

// Option 1: Constructor with ServletContext as parameter.
public SqlHealthCheck (ServletContext context, String prefix) {
    this.url = context.getInitParameter(prefix + "".db-url"");
    this.username = context.getInitParameter(prefix + "".db-user"");
    this.password = context.getInitParameter(prefix + "".db-passwd"");
    setType(""sqlcheck"");
    setDescription(""SQL database check: "" + this.url);
    this.decodePassword();
    this.setDriver(context.getInitParameter(prefix + "".db-driver""));
}

// Option 2: Static factory method with ServletContext as parameter
public static HealthCheck createHealthCheck(ServletContext context, String prefix) {
    String dbUrl = context.getInitParameter(prefix + "".db-url"");
    String username = context.getInitParameter(prefix + "".db-user"");
    String password =  context.getInitParameter(prefix + "".db-passwd"");
    String sqlDriver = context.getInitParameter(prefix + "".db-driver"");

    SqlHealthCheck healthCheck = new SqlHealthCheck(""SQL database check: "" + dbUrl, dbUrl, username, password);
    healthCheck.decodePassword();
    healthCheck.setDriver(sqlDriver);

    return healthCheck;
}

public HealthCheckRunner.Result run() {
    Connection connection = null;
    Statement statement = null;

    try {
        if (driver != null) { Class.forName(driver); }
        connection = DriverManager.getConnection(this.url, this.username, this.password);
        statement = connection.createStatement();
        statement.executeQuery(""SELECT 1"");
        return HealthCheckRunner.Result.Pass;
    } catch (SQLException | ClassNotFoundException  ex) {
        setMessage(ex.getMessage());
        return getFailureResult();
    }
    finally {
        try {
            if (statement != null) {statement.close();}
            if (connection != null) {connection.close();}
        } catch (SQLException ex) {
            setMessage(ex.getMessage());
        }
    }
}

public void decodePassword() {
    // Decode password
    try {
        if (password != null &amp;&amp; !"""".equals(password)) {
            password = new String(Base64.decode(password.getBytes()));
        }
    } catch (Exception e) {
        if (e.getMessage()!=null) {
            this.setMessage(e.getMessage());}
    }
}
</code></pre>

<p>}</p>
",https://stackoverflow.com/questions/52361357/factory-method-vs-constructor-with-servletcontext-as-parameter,"['java', 'unit-testing', 'servlets']",112,FALSE,0,1
How to use Json (C#) to serialize an object ignoring certain properties,"<p>This should be easy, but after a day of experiments I more confused.
This would be so useful in test scenarios
Basically I want to easily compare a object created in a test against a what I would expect, but ignoring insignificant properties.
The object is The WPF App and I am refactoring the crucial initialization code, so The scenario would be: </p>

<ul>
<li>I want to make a Json copy of the object initialized in the old way (without any unimportant properties) as a json string and saved to a ""gold"" file</li>
<li>Run The Test - initialising the object the new way</li>
<li>Serialise the new object to json string - and to file without the unimportant properties</li>
<li><p>Load the gold file -> string</p></li>
<li><p>Compare the two strings</p></li>
<li>voila</li>
</ul>

<p>Essentially a dictionary of top level important properties (nae - values as a string) is what I want. I am not interested in hierarchical complexity as I can do that in the code if I need.
Keeping it simple ...
There are many Json nugets out there and the filtering is ""hidden"" in the JSon encapsulation.
This is such a useful idea for unit testing, but I am struggling to get a (simple) way to do this. I don't wan't to use attributes in main class - as this is just for a specific test.</p>

<p>I  have looked at many posts and tried various ideas, but it aint getting there.
Please help if you can  thanks</p>

<p>Terry</p>
",https://stackoverflow.com/questions/50293316/how-to-use-json-c-to-serialize-an-object-ignoring-certain-properties,"['c#', 'json']",78,FALSE,0,1
Consuming WCF service from Business Logic Layer,"<p>I have a solution with the following structure:</p>

<ol>
<li>Domain (.NET 4.6.1)</li>
<li>DAL (.NET 4.6.1)</li>
<li>BLL (.NET Core 2.0)</li>
<li>API  (.NET Core 2.0)</li>
</ol>

<p>I have a requirement to submit data to an external WCF service. I personally do not have a lot of experience with WCF as I have been working with REST APIs. So to try out consuming a WCF service, I have set up a .NET core console application in and added a connected service reference to it. This resulted in a generated <code>Reference.cs</code> with the following classes:</p>

<ul>
<li>IWebService</li>
<li>IWebServiceChannel</li>
<li>SendResponse </li>
<li>GetResponse</li>
<li>WebServiceClient (implementing IWebService)</li>
</ul>

<p>I was thinking about creating a <code>SubmissionService</code> class in the BLL layer to submit data to the WCF service, so I moved <code>IWebService</code> from the console app to the BLL layer to inject into the class and perform unit testing. The attributes defined on the <code>IWebService</code> requires a reference to <code>System.ServiceModel</code> which comes with a lot of baggage and it does not make sense to reference it in my BLL layer. </p>

<p>I am not sure where to put the WCF client in my project structure. I have been investigating this issue and the only viable solution I can think of is to create a class library project purely for the WCF client and reference that in my BLL layer to have access to IWebService and mock it for testing. Has anyone been in the same situation? Any help is greatly appreciated.</p>
",https://stackoverflow.com/questions/48924001/consuming-wcf-service-from-business-logic-layer,"['c#', 'unit-testing', 'wcf', 'dependency-injection', '.net-core']",326,TRUE,0,1
ArgumentCaptor captures wrong class,"<p>SOLVED: Even if the getValue() on the Argument Captor shows you this, it is normal. To be honest I was expecting to see and instance on the OnLoginWithEmailCallback interface here. The problem on my side was related to a method call on mView which was generating a NPE. Works like a charm now.</p>

<p>ORIGINAL PROBLEM:</p>

<p>I am implementing my first unit test using Mockito in my MVP app and I need to mock the behaviour of a callback when the user is logging in. I am using Firebase to handle the authentication.</p>

<p>I followed a very good tutorial from here : <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>

<p>I am calling method on class under test. This method calls another one on the Auth Presenter which does the actual work</p>

<pre><code>mPresenter.performLoginWithEmail(EMAIL, PASSWORD);
</code></pre>

<p>Then I am verifying that an underlining method in the Auth Presenter class was called. I try to capture the callback interface.</p>

<pre><code>verify(mAuthPresenter, times(1)).login(mOnLoginWithEmailCallbackArgumentCaptor.capture(),
            eq(EMAIL), eq(PASSWORD));
</code></pre>

<p>The problem is that getValue() from the Argument Captor returns an instance of the mPresenter (class under test) instead of the OnLoginWithEmailCallback interface class. Therefore I get an NPE.       </p>

<pre><code>mOnLoginWithEmailCallbackArgumentCaptor.getValue().onLoginWithEmailSuccess();
</code></pre>

<p>Here is the complete test class:</p>

<pre><code>@RunWith(MockitoJUnitRunner.class)  
public class LoginPresenterTest {  

    private static String EMAIL = ""test@rmail.com"";  
    private static String PASSWORD = ""1234"";  

    //class under test  
  private LoginPresenter mPresenter;  

    @Mock  
  AuthPresenter mAuthPresenter;  

    @Captor  
  private ArgumentCaptor&lt;OnLoginWithEmailCallback&gt; mOnLoginWithEmailCallbackArgumentCaptor;  

    @Mock  
  ILoginActivityView mView;  

    @Before  
  public void setupLoginPresenter() {  
        MockitoAnnotations.initMocks(this);  

        // Get a reference to the class under test  
  mPresenter = new LoginPresenter(mView, mAuthPresenter);  
    }  

    @Test  
  public void performLoginWithEmail() {  

        mPresenter.performLoginWithEmail(EMAIL, PASSWORD);  

        //wanting to have control over the callback object. therefore call capture to then call methods on the interface  
  verify(mAuthPresenter, times(1)).login(mOnLoginWithEmailCallbackArgumentCaptor.capture(),  
                eq(EMAIL), eq(PASSWORD));  

        mOnLoginWithEmailCallbackArgumentCaptor.getValue().onLoginWithEmailSuccess();  

        InOrder inOrder = Mockito.inOrder(mView);  
        inOrder.verify(mView).goToMap();  
        inOrder.verify(mView).hideProgressBar();  
    }  
}
</code></pre>

<p><strong>EDIT</strong>: This is the call to <strong>mAuthPresenter.login</strong>:</p>

<p><strong>SOLVED</strong>: getLoginActivityView() was causing an NPE</p>

<pre><code>public void performLoginWithEmail(String email, String password) {  
    mAuthPresenter.login(new OnLoginWithEmailCallback() {  
        @Override  
  public void onLoginWithEmailSuccess() {  
            getLoginActivityView().goToMap();  
            getLoginActivityView().hideProgressBar();  
        }  

        @Override  
  public void onLoginWithEmailFailed(String error) {  
            getLoginActivityView().hideProgressBar();  
            getLoginActivityView().showToast(error);  
        }  
    }, email, password);  
}
</code></pre>

<p>I also tried using using doAnswer from Mockito:</p>

<pre><code>    doAnswer(new Answer() {  
    @Override  
  public Object answer(InvocationOnMock invocation) throws Throwable {  
        ((OnLoginWithEmailCallback)invocation.getArguments()[0]).onLoginWithEmailSuccess();  
        return null;  
    }  
}).when(mAuthPresenter).login(  
        any(OnLoginWithEmailCallback.class, EMAIL, PASSWORD));
</code></pre>

<p>Still, invocation.getArguments() return an instance of the class under test (LoginPresenter), so the same problem as before. Can you help me?</p>
",https://stackoverflow.com/questions/51797291/argumentcaptor-captures-wrong-class,"['android', 'unit-testing', 'testing', 'mockito']",421,TRUE,0,1
Alembic migrate with existing SQLAlchemy engine,"<p>I have a certain SQLAlchemy declarative Base that I create on a sqlite memory DB:</p>

<pre><code>engine = create_engine('sqlite:///:memory:')
Base.metadata.create_all(engine)
</code></pre>

<p>I'm using this for unit testing logic.</p>

<p>With this I have my tables in the DB. But now I wish to migrate certain things using alembic.</p>

<p>AFAIK alembic migrations use the <code>env.py</code> run_migrations_online and there uses a SQLAlchemy function called <code>engine_from_config</code> creating a new engine here.</p>

<p>The problem I wish to solve is to have a way to use the previously created connection, which holds the recently created tables, for the alembic migrations.</p>

<p>I used this on my test scripts: <a href=""https://stackoverflow.com/questions/24622170/using-alembic-api-from-inside-application-code"">Using Alembic API from inside application code</a>, so that my script does the following after the previous <code>create_all</code> call:</p>

<pre><code>import alembic.config
alembicArgs = ['--raiseerr', '-x', 'dbPath=sqlite:///:memory:', 'upgrade', 'head']
alembic.config.main(argv=alembicArgs
</code></pre>

<p>[Please mind, I would just create my schemas with the <code>Base.metadata.create_all(engine)</code> call but my alembic versions not only hold schema changes, they also have some filling of catalog tables data, that's why I intend to use alembic here. In fact, if my alembic migrations hold some ""create tables"" logic, these two would conflict. So I can safely remove the <code>create_all</code> call and depend on alembic alone to create my schemas here.]</p>

<p>Having already modified my alembic's <code>env.py</code>:</p>

<pre><code>def run_migrations_online():
    ini_section = config.get_section(config.config_ini_section)

    db_path = context.get_x_argument(as_dictionary=True).get('dbPath')

    if db_path:
        ini_section['sqlalchemy.url'] = db_path

    connectable = engine_from_config(
        ini_section,
        prefix ... # everything from here the same as default env.py
</code></pre>

<p>As far as I can tell the <code>connectable=engine_from_config</code> creates a connection to a new engine on a new <code>sqlite:///:memory:</code> database, and that's why I can't upgrade via alembic the previously created DB on my script with <code>create_all(engine)</code>.</p>

<p>So... TLDR; is there a way to pass my previously existing engine connection (with my created tables) to alembic so that it can migrate it? (I'm pretty sure that the dbPath arg I created is useless here, in fact, I'm just copying what the other post I referenced uses).</p>
",https://stackoverflow.com/questions/48350091/alembic-migrate-with-existing-sqlalchemy-engine,"['python', 'sqlite', 'sqlalchemy', 'database-migration', 'alembic']",3326,TRUE,11,1
Quick start learning Python following industrial standards,"<p>Aside from learning the <a href=""https://stackoverflow.com/questions/2573135/python-progression-path-from-apprentice-to-guru"">Python language itself</a>, I have to learn on the go during daily business how to solve real-life problems with Python and share solutions with other colleagues.</p>

<p>Therefore I want while starting my projects from scratch, bootstrap them already with an advanced level for good readability<sup>1</sup> and unit testing and have a more or less convenient efficient environment (besides what is the matter of taste, error-prone and well-readable code is here in focus).</p>

<p>Here is what I have found so far - what else would you add?</p>

<ul>
<li>Install not Python itself but the <a href=""https://www.anaconda.com/download/"" rel=""nofollow noreferrer"">Anaconda distro</a></li>
<li>Organize project in a comprehensive well-explained structure:

<ul>
<li><a href=""http://infinitemonkeycorps.net/docs/pph/#id5"" rel=""nofollow noreferrer"">Python project HowTo</a> - Anatomy of a Python project and test methods</li>
<li><a href=""https://www.python.org/dev/peps/pep-0257/"" rel=""nofollow noreferrer"">Document your code</a> - docstring conventions (PEP 257)</li>
</ul></li>
<li>If you are coming from an object-oriented language, consider <a href=""https://www.programiz.com/python-programming/class"" rel=""nofollow noreferrer"">Python object and classes</a></li>
<li>Control code quality:

<ul>
<li>Use <a href=""https://www.pylint.org/"" rel=""nofollow noreferrer"">pylint</a> to check the quality of code, Anaconda has it already on-board</li>
<li>Read about <a href=""https://docs.quantifiedcode.com/python-anti-patterns"" rel=""nofollow noreferrer"">Python anti-patterns</a></li>
</ul></li>
<li>Consider to add a Dockerfile will required dependencies to demo how your tests run through in a given operating system environment</li>
</ul>

<p>There is also a <a href=""https://www.reddit.com/r/Python/comments/1bbbwk/whats_your_opinion_on_what_to_include_in_init_py/"" rel=""nofollow noreferrer"">useful info</a> on what modules' <code>__init__.py</code> file could contain.</p>

<p>Answers welcome also pointing out what are Python specific but tool-neutral aspects to consider while integrating with a DevOps toolchain i.e. source control, continuous integration and binary package management.</p>

<p><sup>1</sup> I've noticed that the tag <code>clean code</code> and related are leading to opinionated discussions; so I have decided to follow where possible recommendations available from Google, PEP, and pylint.</p>
",https://stackoverflow.com/questions/52421063/quick-start-learning-python-following-industrial-standards,"['python', 'unit-testing', 'coding-style']",183,FALSE,4,0
Mixin as class decorator in TypeScript does not update class property,"<h2>Intro</h2>

<p>I have a project in TS that requires some classes to implement the following interface:</p>

<pre><code>interface IStylable {
  readonly styles: {
    [property: string]: string
  };
  addStyles (styles: { [property: string]: string }): void;
  updateStyles (styles: { [property: string]: string }): void;
  removeStyles (styles: Array&lt;string&gt;): void;
}
</code></pre>

<p>To avoid boilerplate code I decided to create a <a href=""https://www.typescriptlang.org/docs/handbook/mixins.html"" rel=""nofollow noreferrer"">Mixin</a> and apply it in each class I need it. (I could use an abstract class but my problem requires multiple inheritance solution, something that is not offered by TS.) Bellow is the class implementation of <code>IStylable</code> interface:</p>

<pre><code>export class StylableClass implements IStylable {
  private readonly _styles: { [property: string]: string } = {};

  // For each property provided in styles param, check if the property
  // is not already present in this._styles and add it. This way we
  // do not overide existing property values.
  public addStyles (styles: { [property: string]: string }): void {
    for (const [property, value] of Object.entries(styles)) {
      if (!this._styles.hasOwnProperty(property)) {
        this._styles[property] = value;
      }
    }
  }

  // For each property provided in styles param, check if the property
  // is already present in this._styles and add it. This way we
  // do add property values values that do not exist.
  public updateStyles (styles: { [property: string]: string }): void {
    for (const [property, value] of Object.entries(styles)) {
      if (this._styles.hasOwnProperty(property)) {
        this._styles[property] = value;
      }
    }
  }

  // For each property in styles param, check if it is present in this._styles
  // and remove it.
  public removeStyles (styles: Array&lt;string&gt;): void {
    for (const property of styles) {
      if (this._styles.hasOwnProperty(property)) {
        delete this._styles[property];
      }
    }
  }

  public set styles (styles: { [property: string]: string }) {
    this.addStyles(styles);
  }

  public get styles (): { [property: string]: string } {
    return this._styles;
  }
}
</code></pre>

<p>For something I'm really excited about and looking forward is standardized of decorator specification in ES6. Typescript allow this experimental feature by setting the <code>experimentalDecorators</code> flag in <code>tsconfig.json</code>. I wanted the <code>StylableClass</code> to be used as a class decorator (<code>@Stylable</code>) to make the code cleaner, so I created a function that takes a class and transforms it to decorator:</p>

<pre><code>export function makeDecorator (decorator: Function) {
  return function (decorated: Function) {
    const fieldCollector: { [key: string]: string } = {};
    decorator.apply(fieldCollector);
    Object.getOwnPropertyNames(fieldCollector).forEach((name) =&gt; {
      decorated.prototype[name] = fieldCollector[name];
    });

    Object.getOwnPropertyNames(decorator.prototype).forEach((name) =&gt; {
      decorated.prototype[name] = decorator.prototype[name];
    });
  };
}
</code></pre>

<p>and used it like so:</p>

<pre><code>export const Stylable = () =&gt; makeDecorator(StylableClass);
</code></pre>

<h2>The problem</h2>

<p>Now it's time for Unit testing. I created a dummy class to apply my decorator and wrote a simple test for <code>addStyles()</code> method.</p>

<pre><code>@Stylable()
class StylableTest {
  // Stylable
  public addStyles!: (styles: {
    [prop: string]: string;
  }) =&gt; void;

  public updateStyles!: (styles: {
    [prop: string]: string;
  }) =&gt; void;

  public removeStyles!: (styles: string[]) =&gt; void;

  public styles: { [property: string]: string } = {};
}

describe('Test Stylable mixin', () =&gt; {
  it('should add styles', () =&gt; {
    const styles1 = {
      float: 'left',
      color: '#000'
    };

    const styles2 = {
      background: '#fff',
      width: '100px'
    };

    // 1
    const styles = new StylableTest();
    expect(styles.styles).to.be.an('object').that.is.empty;

    // 2
    styles.addStyles(styles1);
    expect(styles.styles).to.eql(styles1);

    // 3
    styles.addStyles(styles2);
    expect(styles.styles).to.eql(Object.assign({}, styles1, styles2));
  });
});
</code></pre>

<p>The problem is that the second expect statement fails. After executing <code>styles.addStyles(styles1);</code> the <code>styles.styles</code> array is still empty when it should contain the <code>styles1</code> object. When I debugged my code I found that the <code>push</code> statement in <code>addStyles()</code> method is executed as expected, thus the loop is not problematic, but the array is not updated after the execution of the method ends. Can you provide me a hint or a solution on what did I missed? The first thing I checked is maybe something is going wrong with the <code>makeDecorator</code> function but as long as I can execute the methods I cannot find some other clue to look for.</p>
",https://stackoverflow.com/questions/50986378/mixin-as-class-decorator-in-typescript-does-not-update-class-property,"['typescript', 'decorator', 'mixins']",1097,TRUE,3,1
Dependency Injection for Static Functions for Unit Test in Swift,"<p>I know this looks like a common question but after reading 10-15 tutorial and looking how can I write test for my service class. I can't solve moving static functions to protocol or etc.. for dependency injection</p>

<p>I have a network layer like below image. All my function classes (like fetch users, news, media etc..) calls ""Service Caller"" class and after that If response is error; calls ""Service Error"" class to handle error and If not error, decode the JSON. </p>

<p>My problem is that I'm calling service class as a static function like ""ServiceCaller.performRequest"" and If It gets error I'm also calling error class as static like ""ServiceError.handle"". Also It calls URLCache class to get path of request url. I'm not sure <strong>how can I make them dependency inject and mock in test class.</strong> As I find in tutorials, I should write it like;</p>

<pre><code>protocol MyProtocol{
    func myfunction() -&gt; Void
}
class A{
    let testProtocol = MyProtocol!
    init(pro: MyProtocol){
        testProtocol = pro
    }
}
</code></pre>

<p>and in setup function in test class it probably;</p>

<pre><code>myMockProtocol = ...
myTestclass = A.init(pro: myMockProtocol)
</code></pre>

<p><a href=""https://i.stack.imgur.com/HFymQ.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/HFymQ.png"" alt=""How My Network layer works""></a></p>

<p>but I can't find how can I get ride of static calls like ServiceCaller.performRequest or ServiceError.handle..; (Simplified version in the bottom part of question)</p>

<pre><code>class AppInitService{

static func initAppRequest(_ completion: @escaping (_ appInitRecevingModel: Result&lt;AppInitRecevingModel&gt;) -&gt; Void) {

    let sendingModel = AppInitSendingModel(cmsVersion: AppDefaults.instance.getCMSVersion())
    let route = ServiceRouter(method: .post, path: URLCache.instance.getServiceURL(key: URLKeys.initApp), parameters: (sendingModel.getJSONData()), timeoutSec: 1)
    ServiceCaller.performRequest(route: route) { (result) in
        if let error = result.error{
            if let statusCode = result.response?.statusCode{
                completion(.error(ServiceError.handle(error: error, statusCode: statusCode)))
            }else{
                completion(.error(ServiceError.handle(error: error, statusCode: error._code)))
            }
        }else{
            if let data = result.data{
                do{
                    var responseJson = JSON(data)
                    responseJson[""idleTimeoutInMinutes""] = 10
                    let input = try AppInitRecevingModel(data: responseJson.rawData())
                    completion(.success(input))
                }catch let error{
                    completion(.error(ServiceError.handle(error: error, statusCode: -1002)))
                }
            }
        }}
}
 }
</code></pre>

<p>My Test class:</p>

<pre><code>class MyProjectAppInitTests: XCTestCase {

var appInitTest: AppInitService!

override func setUp() {
    super.setUp()
    // Put setup code here. This method is called before the invocation of each test method in the class.
    appInitTest = AppInitService.init()
}

override func tearDown() {
    // Put teardown code here. This method is called after the invocation of each test method in the class.
    appInitTest = nil
    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.
    let testParamater = [""string"":""test""]
    let route = ServiceRouter(method: .post, path: ""/testPath"", parameters: testParamater.getJSONData(), timeoutSec: 10)
    appInitTest. //cant call anything in here
}
</code></pre>

<p>Tutorials I looked for Unit Test;</p>

<p><a href=""https://www.raywenderlich.com/150073/ios-unit-testing-and-ui-testing-tutorial"" rel=""nofollow noreferrer"">https://www.raywenderlich.com/150073/ios-unit-testing-and-ui-testing-tutorial</a></p>

<p><a href=""https://www.swiftbysundell.com/posts/time-traveling-in-swift-unit-tests"" rel=""nofollow noreferrer"">https://www.swiftbysundell.com/posts/time-traveling-in-swift-unit-tests</a></p>

<p><a href=""https://marcosantadev.com/test-doubles-swift"" rel=""nofollow noreferrer"">https://marcosantadev.com/test-doubles-swift</a></p>

<p><a href=""http://merowing.info/2017/04/using-protocol-compositon-for-dependency-injection/"" rel=""nofollow noreferrer"">http://merowing.info/2017/04/using-protocol-compositon-for-dependency-injection/</a></p>

<p>EDIT: One solution maybe writing init class for whole network layer and service classes then get rid of static functions? But I'm not sure If It will be a good approach.</p>

<p>EDIT 2: Simplified Code;</p>

<pre><code>class A{

static func b(completion:...){
    let paramater = ObjectModel(somevariable: SomeClass.Singleton.getVariable()) //Data that I sent on network request
    let router = ServiceRouter(somevariable: SomeClassAgain.Singleton.getsomething()) //Router class which gets parameters, http method etc..

    NetworkClass.performNetworkRequest(sender: object2){ (result) in
        //Result - What I want to test (Write UnitTest about)
    }
}
}
</code></pre>
",https://stackoverflow.com/questions/50251997/dependency-injection-for-static-functions-for-unit-test-in-swift,"['ios', 'swift', 'unit-testing', 'dependency-injection']",2017,TRUE,2,1
Testing razor pages app,"<p>I am writing a Razor Pages app for a University project, which I am required to test. I couldn't find many sources and examples online on testing Razor Pages and I'm trying to follow the examples on this link : <a href=""https://learn.microsoft.com/en-us/aspnet/core/testing/razor-pages-testing?view=aspnetcore-2.1"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/aspnet/core/testing/razor-pages-testing?view=aspnetcore-2.1</a>  </p>

<p>My first problem is unit testing:<br>
This is the test method I wrote, it's supposed to check that a value that is filled in the OnGet method on my model is receiving the correct value:    </p>

<pre><code>[Fact]
    public void OnGet_ViewStores()
    {
        // Arrange
        var httpContext = new DefaultHttpContext();
        var modelState = new ModelStateDictionary();
        var actionContext = new ActionContext(httpContext, new RouteData(), new PageActionDescriptor(), modelState);
        var modelMetadataProvider = new EmptyModelMetadataProvider();
        var viewData = new ViewDataDictionary(modelMetadataProvider, modelState);
        var pageContext = new PageContext(actionContext)
        {
            ViewData = viewData
        };
        var storesModel = new StoresModel()
        {
            PageContext = pageContext,
            Url = new UrlHelper(actionContext)
        };

        #region snippet2
        // Act
        storesModel.OnGet();
        #endregion

        #region snippet3
        // Assert
        var actualStores = wsep1.Services.ViewAllStores(1);
        Assert.Equal(storesModel.StoreDetails, actualStores);
        #endregion
    }
</code></pre>

<p>And this is the model which is being checked:</p>

<pre><code>public class StoresModel : PageModel
{
    public List&lt;string&gt; StoreDetails { get; set; }
    public string Message { get; set; }
    public int clientId;

    public void OnGet()
    {
        clientId = (int)HttpContext.Session.GetInt32(""clientId"");
        Message = ""Your clientId id is "" + clientId;
        StoreDetails = wsep1.Services.ViewAllStores(clientId);
    }
}
</code></pre>

<p>The problem is that the test throws an exception because I am using an HttpContext.Session which is not configures properly in the test. In my real project it is configured beforehand in Startup.cs in this method: </p>

<pre><code>public void ConfigureServices(IServiceCollection services)
    {
        services.AddWebSocketManager();
        services.AddMvc();
        services.AddDistributedMemoryCache();
        services.AddTransient&lt;ShoppingHandler&gt;();
        services.AddSession(options =&gt;
        {
            // Set a short timeout for easy testing.
            options.IdleTimeout = TimeSpan.FromSeconds(1000);
            options.Cookie.HttpOnly = true;
        });
    }
</code></pre>

<p>But I can't seem to find a way to configure this in my test.  </p>

<p>My second problem is with integration testing:<br>
I am trying to run a very basic test with the Test Server, this is my test class:  </p>

<pre><code>   public class IndexPageTest : IClassFixture&lt;TestFixture&lt;Client.Startup&gt;&gt;
{
    private readonly HttpClient _client;

    public IndexPageTest(TestFixture&lt;Client.Startup&gt; fixture)
    {
        _client = fixture.Client;
    }

    #region snippet1
    [Fact]
    public async Task Request_ReturnsSuccess()
    {
        // Act
        var response = await _client.GetAsync(""/"");

        // Assert
        response.EnsureSuccessStatusCode();
    }
    #endregion
}  
</code></pre>

<p>I hardly changed the TextFixture class that was included in the demo project in the link I gave at the beginning of the post, all I did was add my services to the configuration method (as I said before, I'm using a Session object and also WebSocketManager in my app).<br>
_client.GetAsync(""/"") returns a status of ""500 - internal server error"" and I have no idea why and how to configure these tests to work.<br>
Any ideas would be appreciated, Thanks.</p>
",https://stackoverflow.com/questions/50065040/testing-razor-pages-app,"['asp.net', 'testing', 'razor', '.net-core', 'razor-pages']",1232,FALSE,2,0
How can I decouple system design from unit tests (as suggested by Uncle Bob)?,"<p>Uncle Bob (Bob Martin) mentioned in his <a href=""https://blog.cleancoder.com/uncle-bob/2017/03/03/TDD-Harms-Architecture.html"" rel=""nofollow noreferrer"">blog</a> that in order to decouple our system's design from unit tests, we should not expose our concrete classes directly to the unit tests. Rather, we should just expose an API that represents our system, and then use this API for unit testing.</p>

<p><a href=""https://i.stack.imgur.com/FGkzl.png"" rel=""nofollow noreferrer"">A rough representation of Uncle Bob's suggestion</a></p>

<p>According to my understanding, I think that by an API, he meant an <em>interface</em>. So the unit tests should be interacting with interfaces instead of real classes.</p>

<p>My question is this: If we are exposing only interfaces to our unit tests, how do these unit tests get access to the actual implementations to verify their behavior? Should we use DI in our tests to inject the real classes at run time? Is there any way for the code below to work?</p>

<p>ILoanEligibility.cs</p>

<pre><code>public interface ILoanEligibility
{
    bool HasCorrectType(string loanType);
}
</code></pre>

<p>LoanEligibility.cs</p>

<pre><code>public class LoanEligibility : ILoanEligibility
{
    public bool HasCorrectType(string loanType)
    {
        if(loanType.Equals(""Personal""))
        {
            return true;
        }
        return false;
    }
}
</code></pre>

<p>Unit Test</p>

<pre><code>[TestClass]
public class LoanEligibilityTest
{
    ILoanEligibility _loanEligibility;
    [TestMethod]
    public void TestLoanTypePersonal()
    {
        //Arrange
        string loanType = ""Personal"";

        //Act
        bool expected = _loanEligibility.HasCorrectType(loanType);

        //Assert
        Assert.IsTrue(expected);
    }
}
</code></pre>

<p>The above unit test tries to see if LoanEligibility.HasCorrectType() method works properly for ""Personal"" type. Obviously, the test will fail as we are not using a concrete class, but rather an interface, in accordance with Uncle Bob's suggestion (if I understood it correctly).  </p>

<p>How do I make this test pass? Any suggestions would be helpful.</p>

<p><strong>Edit 1</strong>
Thank you @bleepzter for suggesting Moq. Following is the modified unit test class, testing both valid and invalid cases.</p>

<pre><code>[TestClass]
public class LoanEligibilityTest
{
    private Mock&lt;ILoanEligibility&gt; _loanEligibility;

    [TestMethod]
    public void TestLoanTypePersonal()
    {
        SetMockLoanEligibility();
        //Arrange
        string loanType = ""Personal"";
        //Act
        bool expected = _loanEligibility.Object.HasCorrectType(loanType);
        //Assert
        Assert.IsTrue(expected);
    }

    [TestMethod]
    public void TestLoanTypeInvalid()
    {
        SetMockLoanEligibility();
        //Arrange
        string loanType = ""House"";
        //Act
        bool expected = _loanEligibility.Object.HasCorrectType(loanType);
        //Assert
        Assert.IsFalse(expected);
    }

    public void SetMockLoanEligibility()
    {
        _loanEligibility = new Mock&lt;ILoanEligibility&gt;();
        _loanEligibility.Setup(loanElg =&gt; loanElg.HasCorrectType(""Personal""))
                        .Returns(true);
    }
}
</code></pre>

<p>But now I am confused. Since we are not <em>really</em> testing our concrete class but rather its mock, are these unit tests really telling us anything, other than probably that our mocks are working fine?</p>
",https://stackoverflow.com/questions/52522965/how-can-i-decouple-system-design-from-unit-tests-as-suggested-by-uncle-bob,"['c#', 'asp.net', 'unit-testing', 'tdd']",1384,TRUE,1,3
ClaimsIdentity user is not recognized as logged in during test,"<p>I am trying to get unit testing established in a new project that I'm working on. I'm using ASP.NET Boilerplate (.NET Core, Multi Page Application) with pre-built authentication as my starting point. Since <a href=""https://stackoverflow.com/questions/52559572/what-happened-to-web-tests-project-in-startup-project"">Web.Tests is not included in this template</a>, I am attempting to create my own, pulling from what was provided in <a href=""https://github.com/aspnetboilerplate/aspnet-core-template/tree/8659b97f960a04eacdd5d148bdb48ef6f352bf97/test/AbpCompanyName.AbpProjectName.Web.Tests"" rel=""nofollow noreferrer"">the ASP.NET Core template</a>. I've been able to establish a <code>Startup</code> class that uses <code>InMemoryDatabase</code> for testing. However, the most basic of tests does not pass. I'm getting stuck on having a test user who is fully authenticated and recognized as being 'logged in'. The code under test is this:</p>

<pre><code>[AbpMvcAuthorize]
public class HomeController : ProjectControllerBase
{
    public ActionResult Index()
    {
        return View();
    }
}
</code></pre>

<p>The test is written as such:</p>

<pre><code>[Fact]
public async Task Index_Test()
{            
    // Added as part of suggestions made by 'https://medium.com/@zbartl/authentication-and-asp-net-core-integration-testing-using-testserver-15d47b03045a'
    Client.DefaultRequestHeaders.Add(""my-name"", ""admin"");
    Client.DefaultRequestHeaders.Add(""my-id"", ""2"");

    // Act
    var response = await GetResponseAsStringAsync(
        GetUrl&lt;HomeController&gt;(nameof(HomeController.Index))
    );

    // Assert
    response.ShouldNotBeNullOrEmpty();
}
</code></pre>

<p>The blog referenced <a href=""https://medium.com/@zbartl/authentication-and-asp-net-core-integration-testing-using-testserver-15d47b03045a"" rel=""nofollow noreferrer"">here</a> allowed me to provide a <code>ClaimsPrincipal</code> with <code>ClaimsIdentity</code> using a <code>Middleware</code> class. The middleware class looks like this:</p>

<pre><code>public class TestAuthenticationMiddleware
{
    private readonly RequestDelegate _next;

    public TestAuthenticationMiddleware(RequestDelegate next, IAuthenticationSchemeProvider schemas)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        if (context.Request.Headers.Keys.Contains(""my-name""))
        {
            if (context.Request.Headers[""my-name""].First().Equals(""admin""))
            {
                ClaimsIdentity claimsIdentity = new ClaimsIdentity(new List&lt;Claim&gt;
                    {
                        new Claim(ClaimTypes.Name, ""admin""),
                        new Claim(ClaimTypes.NameIdentifier, context.Request.Headers[""my-id""].First()),
                        new Claim(ClaimTypes.Role, ""Admin""),
                        new Claim(""http://www.aspnetboilerplate.com/identity/claims/tenantId"", ""1"", ""int""),
                        new Claim(""AspNet.Identity.SecurityStamp"", Guid.NewGuid().ToString())

                    },
                    ""Identity.Application"");

                ClaimsPrincipal principal = new ClaimsPrincipal(claimsIdentity);
                context.User = principal;
                await context.SignInAsync(""Identity.Application"", principal);
            }
        }

        await _next(context);
    }
}
</code></pre>

<p>So, what I get when I run the test is a failed test.</p>

<pre><code>Shouldly.ShouldAssertException : response.StatusCode
    should be
HttpStatusCode.OK
    but was HttpStatusCode.Redirect
</code></pre>

<p>I think what is happening is that we are getting stuck in the <code>[AbpMvcAuthorize]</code> functionality and are getting redirected to the login page. If I remove the <code>AbpMvcAuthorize</code> from the controller, then I get a different fail state. I get a null reference error. The <code>View</code> is attempting to render and is failing in a subsequent view model when <code>GetShownLoginName()</code> is called:</p>

<pre><code>public class SideBarUserAreaViewModel
{
    public GetCurrentLoginInformationsOutput LoginInformations { get; set; }

    public bool IsMultiTenancyEnabled { get; set; }

    public string GetShownLoginName()
    {
        var userName = ""&lt;span id=\""HeaderCurrentUserName\""&gt;"" + LoginInformations.User.UserName + ""&lt;/span&gt;"";

        if (!IsMultiTenancyEnabled)
        {
            return userName;
        }

        return LoginInformations.Tenant == null
            ? "".\\"" + userName
            : LoginInformations.Tenant.TenancyName + ""\\"" + userName;
    }
}
</code></pre>

<p>I want to be able to test my controller logic, to ensure that changes to views, changes to view models, and changes to services do not inadvertently cause page load errors. Is there a way, outside of creating instances of <code>UserManager</code>, <code>LogInManager</code> and <code>SignInManager</code> in my <code>TestBase</code> class and programmatically logging in the user?</p>
",https://stackoverflow.com/questions/52611449/claimsidentity-user-is-not-recognized-as-logged-in-during-test,"['c#', 'unit-testing', 'asp.net-identity', 'claims-based-identity', 'aspnetboilerplate']",799,TRUE,1,1
Is it possible to bypass certain exception in unit test?,"<p>Is it even possible to bypass certain exceptions in <code>mockito</code>? This sounds crazy. You want to catch expected exceptions in the unit testing I assume. However I decided to give a try asking this question. Here is my scenario hope I could improve my understanding on <code>mockito</code> and general <code>unit test</code> principals via this.</p>

<p>I have to build a simple unit test for a particular class <code>Foo</code> in an enterprise web application using <code>mockito</code> unit test framework.</p>

<p>This <code>Foo</code> class requires <code>ldap</code> and <code>database</code> connections however due to a reason, I can not use development environment specific <code>ldap</code> and <code>database</code> in the unit test. </p>

<p>I just need to test part accessing <code>ldap</code> so that I decided to use <code>unboundid in memory ldap</code> which allows to create light weight directory at run time and remove it from memory after testing is done. </p>

<p>My question is during the instantiation of <code>Foo</code> class via <code>@InjectedMocks</code> annotation, it triggers chain reaction of calling many other classes and their methods. It threw many exceptions which I expected.</p>

<p>I am trying to find a way to somehow ignore some specific exceptions such as loading/reading environment specific properties files or database access and etc.</p>

<p>For my goal, I don't need reading prop files nor database access.</p>

<p>I read upon <code>ExpectedException</code> junit provides which is subset of <code>mockito</code> if I am not mistaken however I don't think its aim aligns with my intention of bypassing some of the exceptions. I could be wrong on this.</p>

<p>All I want to accomplish is:</p>

<ol>
<li>Instantiate <code>Foo</code> class</li>
<li>Call one of its methods that would read a list of group from <code>In memory ldap</code></li>
<li>Verify returned data</li>
</ol>

<p>Here is water downed version of test class:</p>

<pre><code>@RunWith(MockitoJUnitRunner.class)
public class FooTest {

    private static InMemoryDirectoryServer ldapServer;
    private static Integer ldapPort = xxxxx;

    @InjectedMocks
    Foo footester = Foo.getInstance();

    @BeforeClass
    public static void setUpBeforeClass() {
        try {
            // execute instantiate in memory ldap..
        } catch (Exception e) {
           // do print out
        }
    }

    @Test
    public void testLdap() {
       // before it reaches here exceptions were thrown
    }

    @AfterClass
    public static void tearDownAfterClass() throws Exception {
        // do tear down execution
    }
}
</code></pre>
",https://stackoverflow.com/questions/53767064/is-it-possible-to-bypass-certain-exception-in-unit-test,"['java', 'unit-testing', 'ldap']",2000,FALSE,1,1
Python intra-package imports and unit tests,"<p>I've searched for a solution here and on other sites, but it feels like all import problems I come across are subtly different.</p>

<p>I have a project with the following setup:</p>

<ul>
<li>/

<ul>
<li>__init__.py</li>
<li>package1

<ul>
<li>___init__.py</li>
<li>a.py</li>
<li>b.py</li>
<li>tests/

<ul>
<li>test_a.py</li>
<li>test_a.py</li>
</ul></li>
</ul></li>
<li>package2</li>
<li>package3</li>
</ul></li>
</ul>

<p>In b.py:</p>

<p><code>from .a import Foo
</code></p>

<p>In the tests:
<code>import a, b</code></p>

<p>package1, package2, and package3 are essentially smaller packages that are bundled together in the same project/super-package as utilities. The purpose of this project is to be nested inside another package (say, package4) and to have these packages/modules imported by package4. Hence, relative imports to other files in the package are required, if I don't want to modify the path.</p>

<p>As an example, package4:</p>

<ul>
<li>/

<ul>
<li>main.py</li>
<li>src/

<ul>
<li>external/

<ul>
<li>project_from_above

<ul>
<li>package1</li>
<li>package2</li>
<li>package3</li>
</ul></li>
</ul></li>
</ul></li>
</ul></li>
</ul>

<p>I'm omitting the __init__.py's in the hierarchy above. In main.py, I might do:</p>

<p><code>import src.external.project_from_above.package1.a</code></p>

<p><strong>My problem</strong>: this structure works fine, except for unit testing. I am in the habit of running <code>python3 -m unittest discover tests</code> from each package (package1, package2, package3). This works fine when there are not relative imports. However, running with relative imports will yield the following error: ""SystemError: Parent module '' not loaded, cannot perform relative import""</p>

<p><strong>I desire</strong>:
A way of running the unit tests in package1/tests from the package1 directory, with no imports changing (or at least, maintaining the ability to use this entire project inside the aforementioned package4 as a sub-package). I'd like to avoid any manipulation of the path, but if we can restrict it to a run_tests.py file in package1, then that is okay.</p>
",https://stackoverflow.com/questions/48675200/python-intra-package-imports-and-unit-tests,"['python-3.x', 'python-import']",334,TRUE,1,1
Using jMeter for functional e2e testing,"<p>We're using JMeter for e2e testing of a GraphQL API and have some problems that only the GUI shows us the test results, when running from the console there is no useful ""test summary"" visible, and jMeter always exits with a ""0"" exit code indicating ""success"" to our CI.</p>

<p>I've reproduced a minimal example included below to indicate what I'm trying to do:</p>

<ul>
<li>use an HTTP sampler to make a request to a JSON API </li>
<li>make a ""JSON Assertion"" on the result</li>
<li>Print results of failed samplers or assertions to a file or console with a bean shell listener</li>
</ul>

<p>My goal is to print something like the ""View Results Tree"" as a passed/failed summary to the console where jMeter was run, or write it to a file.</p>

<p>Our tests make use of simple HTTP samplers with JSON Assertions, my goal was to try and use a Bean Shell Listener and check if any samplers or JSON assertions had errors, and write to a file in either case.</p>

<pre><code>&lt;?xml version=""1.0"" encoding=""UTF-8""?&gt;
&lt;jmeterTestPlan version=""1.2"" properties=""4.0"" jmeter=""4.0 r1823414""&gt;
&lt;hashTree&gt;
    &lt;TestPlan guiclass=""TestPlanGui"" testclass=""TestPlan"" testname=""Test Plan"" enabled=""true""&gt;
    &lt;stringProp name=""TestPlan.comments""&gt;&lt;/stringProp&gt;
    &lt;boolProp name=""TestPlan.functional_mode""&gt;false&lt;/boolProp&gt;
    &lt;boolProp name=""TestPlan.tearDown_on_shutdown""&gt;true&lt;/boolProp&gt;
    &lt;boolProp name=""TestPlan.serialize_threadgroups""&gt;false&lt;/boolProp&gt;
    &lt;elementProp name=""TestPlan.user_defined_variables"" elementType=""Arguments"" guiclass=""ArgumentsPanel"" testclass=""Arguments"" testname=""User Defined Variables"" enabled=""true""&gt;
        &lt;collectionProp name=""Arguments.arguments""/&gt;
    &lt;/elementProp&gt;
    &lt;stringProp name=""TestPlan.user_define_classpath""&gt;&lt;/stringProp&gt;
    &lt;/TestPlan&gt;
    &lt;hashTree&gt;
    &lt;ThreadGroup guiclass=""ThreadGroupGui"" testclass=""ThreadGroup"" testname=""Thread Group"" enabled=""true""&gt;
        &lt;stringProp name=""ThreadGroup.on_sample_error""&gt;continue&lt;/stringProp&gt;
        &lt;elementProp name=""ThreadGroup.main_controller"" elementType=""LoopController"" guiclass=""LoopControlPanel"" testclass=""LoopController"" testname=""Loop Controller"" enabled=""true""&gt;
        &lt;boolProp name=""LoopController.continue_forever""&gt;false&lt;/boolProp&gt;
        &lt;stringProp name=""LoopController.loops""&gt;1&lt;/stringProp&gt;
        &lt;/elementProp&gt;
        &lt;stringProp name=""ThreadGroup.num_threads""&gt;1&lt;/stringProp&gt;
        &lt;stringProp name=""ThreadGroup.ramp_time""&gt;1&lt;/stringProp&gt;
        &lt;boolProp name=""ThreadGroup.scheduler""&gt;false&lt;/boolProp&gt;
        &lt;stringProp name=""ThreadGroup.duration""&gt;&lt;/stringProp&gt;
        &lt;stringProp name=""ThreadGroup.delay""&gt;&lt;/stringProp&gt;
    &lt;/ThreadGroup&gt;
    &lt;hashTree&gt;
        &lt;HTTPSamplerProxy guiclass=""HttpTestSampleGui"" testclass=""HTTPSamplerProxy"" testname=""HTTP Request"" enabled=""true""&gt;
        &lt;elementProp name=""HTTPsampler.Arguments"" elementType=""Arguments"" guiclass=""HTTPArgumentsPanel"" testclass=""Arguments"" testname=""User Defined Variables"" enabled=""true""&gt;
            &lt;collectionProp name=""Arguments.arguments""/&gt;
        &lt;/elementProp&gt;
        &lt;stringProp name=""HTTPSampler.domain""&gt;jsonplaceholder.typicode.com&lt;/stringProp&gt;
        &lt;stringProp name=""HTTPSampler.port""&gt;&lt;/stringProp&gt;
        &lt;stringProp name=""HTTPSampler.protocol""&gt;https&lt;/stringProp&gt;
        &lt;stringProp name=""HTTPSampler.contentEncoding""&gt;&lt;/stringProp&gt;
        &lt;stringProp name=""HTTPSampler.path""&gt;/posts/1&lt;/stringProp&gt;
        &lt;stringProp name=""HTTPSampler.method""&gt;GET&lt;/stringProp&gt;
        &lt;boolProp name=""HTTPSampler.follow_redirects""&gt;true&lt;/boolProp&gt;
        &lt;boolProp name=""HTTPSampler.auto_redirects""&gt;false&lt;/boolProp&gt;
        &lt;boolProp name=""HTTPSampler.use_keepalive""&gt;true&lt;/boolProp&gt;
        &lt;boolProp name=""HTTPSampler.DO_MULTIPART_POST""&gt;false&lt;/boolProp&gt;
        &lt;stringProp name=""HTTPSampler.embedded_url_re""&gt;&lt;/stringProp&gt;
        &lt;stringProp name=""HTTPSampler.connect_timeout""&gt;&lt;/stringProp&gt;
        &lt;stringProp name=""HTTPSampler.response_timeout""&gt;&lt;/stringProp&gt;
        &lt;/HTTPSamplerProxy&gt;
        &lt;hashTree/&gt;
        &lt;JSONPathAssertion guiclass=""JSONPathAssertionGui"" testclass=""JSONPathAssertion"" testname=""JSON Assertion"" enabled=""true""&gt;
        &lt;stringProp name=""JSON_PATH""&gt;$.userID&lt;/stringProp&gt;
        &lt;stringProp name=""EXPECTED_VALUE""&gt;&lt;/stringProp&gt;
        &lt;boolProp name=""JSONVALIDATION""&gt;false&lt;/boolProp&gt;
        &lt;boolProp name=""EXPECT_NULL""&gt;false&lt;/boolProp&gt;
        &lt;boolProp name=""INVERT""&gt;false&lt;/boolProp&gt;
        &lt;boolProp name=""ISREGEX""&gt;true&lt;/boolProp&gt;
        &lt;/JSONPathAssertion&gt;
        &lt;hashTree/&gt;
    &lt;/hashTree&gt;
    &lt;BeanShellListener guiclass=""TestBeanGUI"" testclass=""BeanShellListener"" testname=""BeanShell Listener"" enabled=""true""&gt;
        &lt;boolProp name=""resetInterpreter""&gt;false&lt;/boolProp&gt;
        &lt;stringProp name=""parameters""&gt;&lt;/stringProp&gt;
        &lt;stringProp name=""filename""&gt;&lt;/stringProp&gt;
        &lt;stringProp name=""script""&gt;&lt;/stringProp&gt;
    &lt;/BeanShellListener&gt;
    &lt;hashTree/&gt;
    &lt;/hashTree&gt;
&lt;/hashTree&gt;
&lt;/jmeterTestPlan&gt;
</code></pre>

<p>I tried a Bean Shell Listener with the following contents, but I don't find the JSON Assertion results in the variables/context available to the Bean Shell Listener.</p>

<pre><code>import org.apache.jmeter.services.FileServer;

// Open File(s)
f = new FileOutputStream(FileServer.getFileServer().getBaseDir()+""/results.txt"", true); 
p = new PrintStream(f); 

// Write data to file 
p.println( ""sampleResult "" + sampleResult.toString() + "": "" + sampleResult.isSuccessful() );
p.println( ""sampleEvent  "" + sampleEvent.toString());
p.println( ""prev  "" + prev.toString());
p.println( ""props  "" + props.toString());
p.println( ""ctx  "" + ctx.toString());
p.println( ""vars  "" + vars.toString());

// Close File(s)
p.close();f.close();
</code></pre>

<p>We are not a Java shop, we use GitLab/etc for our CI, and the ideal case would be to be able to run our jMeter tests in the console, and see a summary of output as one would see when doing unit testing of a scripting language or similar, with a red/green summary of passed and failed tests.</p>
",https://stackoverflow.com/questions/49748683/using-jmeter-for-functional-e2e-testing,"['jmeter', 'functional-testing', 'e2e-testing', 'beanshell']",839,TRUE,0,1
Trying to get angular mock to work with teaspoon-jasmine,"<p>So i'm working in ruby on rails, and I've using it with AngularJS 1 for the first time, and therefore am setting up the unit testing for angularjs inside rails for the first time. I can test rails with rspec no problem, but i've been struggling to test angularjs, currently I'm working with teaspoon-jasmine and angular-mocks to test a simple angular controller, but I run into several problems. The first file below is my test file, I currently have it using angular.mock.module/inject and the error i'm getting is ""Failed to instantiate module angularrApp due to..."" it's basically saying I haven't created or loaded angularApp anywhere, I though mock was supposed to create a test module? If I the module to ""angular.module(""name"", [])"" like I would normally create an angular app, I run into more problems such as the mainController hasn't been created. I'm just overall having issues getting this to work properly, any suggestions? I'm trying to get just the simple first expect to work before I move on to the actual tests. And I am requiring angular and angular-mocks in the spec_helper.js file, all the files below. Would it help to require the file that creates the angular app in my spec_helper.js? I've tried but can't get it to work since one is in the spec directory, while my angular app is in app/assets. Also if it helps, here is the link to the tutorial I based this code off of <a href=""http://angular-rails.com/find_and_browse.html"" rel=""nofollow noreferrer"">http://angular-rails.com/find_and_browse.html</a> </p>

<p>mainController_spec.js (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>'use strict';


describe(""mainController"", function() {

	var scope,
			ctrl,
			location,
			resource;

	var setupController = function() {
		angular.mock.inject( function($rootScope, $resource, $controller) {
			scope = $rootScope.$new();
      resource = $resource;
      ctrl = $controller('mainController', {$scope: scope, $resource: resource });
    })
	}


	beforeEach(function(){
		angular.mock.module(""angularApp"");
		setupController();
	})

	it('should work', function(){
		expect(true).toBe(true);
		// expect(scope.games).toBe([])
	})

});</code></pre>
</div>
</div>
</p>

<p>mainController.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';


myApp.controller('mainController', [ 'mainFactory', '$scope', '$resource', (factory, scope, resource) =&gt; {

	scope.games = [];

	
	factory.populateTable((data) =&gt; {
		scope.games = data;
	})

}]);</code></pre>
</div>
</div>
</p>

<p>angular-app.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';


const myApp = angular.module('angularApp', ['ngRoute', 'ngResource']);
// routes in another file</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/49355229/trying-to-get-angular-mock-to-work-with-teaspoon-jasmine,"['ruby-on-rails', 'angularjs', 'jasmine', 'angular-mock', 'teaspoon']",141,FALSE,0,1
Synchronous Testing with Celery in Flask App,"<p>I have a Flask-based web API, that uses the Asynchronous Task Manager <a href=""https://github.com/celery/celery"" rel=""nofollow noreferrer"">celery</a>. I created an API endpoint that simply runs my desired asynchronous task, and then added another endpoint that exposes the status &amp; results of this task. </p>

<p>Integration Testing through this API endpoint works fine &amp; passes, however I would also like to test these functions synchronously using the <code>task_always_eager</code> setting in celery. But no matter how I try to set this config setting, the application still runs the tasks asynchronously (I know this by observing the celery logs while the tests are running; celery is still booting up workers and assigning them to this task.</p>

<h3>I've Tried modifying the config variables mid-test file</h3>

<pre><code># TEST STATISTICS API
current_app.config.update(task_always_eager=True)
</code></pre>

<h3>As well as in the config.py &amp; <strong>init</strong>.py files</h3>

<pre><code>&lt;config.py, next to the rest of the working config settings&gt;
task_always_eager = True

&lt;__init__.py, I use the ""application factory"" pattern&gt;
celery = Celery(__name__, broker=Config.CELERY_BROKER_URL)
def create_app(config_name):
    app = Flask(__name__)
    celery.conf.update(app.config)
</code></pre>

<p>Yet still, celery continues to run workers on this task. This is a problem for unit testing (can't effectively test the function on it's own bc of the bind=True param), and because tested celery tasks don't show up on our test coverage suite with the coverage.py module. Any help would be greatly appreciated!</p>

<h3>The API</h3>

<p>Exposed API Endpoint:</p>

<pre><code>@api.route('/stats/&lt;start_time&gt;/&lt;end_time&gt;', methods=['GET'])
def stats_endpoint(start_time, end_time):
    task = async_stats.delay(start_time, end_time)
    return jsonify({}), 202, {'Location': url_for('api.stats_status', task_id=task.id)}
</code></pre>

<p>Backend Async API Task:</p>

<pre><code>@celery.task(bind=True)
def async_stats(self, start_time, end_time):
    &lt;do stuff, update task state, do more stuff&gt;
    return
</code></pre>

<p>Async Task Status/Result Endpoint:</p>

<pre><code>@api.route('/stats/status/&lt;task_id&gt;')
def stats_status(task_id):
    task = async_stats.AsyncResult(task_id)
    result = task.result['result']
    status = task.result['status']
    if task.state in ('PENDING', 'STARTED', 'PROGRESS', 'SUCCESS'):
        # task was created, in various stages of completion
        response = jsonify(result)
        response.status_code = status
    &lt;more response handling...&gt;
    return response
</code></pre>

<p>UPDATE: setting the <code>CELERY_ALWAYS_EAGER</code> variable to True during config successfully runs my test scripts synchronously. However trying to do so mid-script with <code>current_app.config.update</code> doesn't work, I suspect bc the workers that are running are already configured a certain way by the time the test script runs. Would love some insight on this, if anyone has experience in this field. Having both Unit &amp; Integration tests side by side would require on-demand config changing, but would be ideal</p>
",https://stackoverflow.com/questions/51600596/synchronous-testing-with-celery-in-flask-app,"['python', 'unit-testing', 'asynchronous', 'flask', 'celery']",1337,FALSE,5,0
How can I use requests_mock to unit test a file upload?,"<p>I'm writing a Python (3) wrapper for an API, and I'm trying to unit test a part of it that requires a file to be uploaded. I would like to verify the filename and the content are sent properly by my client.</p>

<p>I'm using Python's <a href=""https://docs.python.org/3/library/unittest.html"" rel=""nofollow noreferrer""><code>unittest</code></a> library, along with <a href=""http://docs.python-requests.org/en/master/"" rel=""nofollow noreferrer""><code>requests</code></a> and <a href=""http://requests-mock.readthedocs.io/en/latest/index.html"" rel=""nofollow noreferrer""><code>requests_mock</code></a> for testing this.</p>

<p>The way that I was planning to approach this problem was to have a callback function for validating the file is sent and all the headers are properly set. Here's what I have so far:</p>

<pre><code>import unittest
import requests
import requests_mock

from my_class import my_class

from my_class.API import API

class  TestAPI(unittest.TestCase):

    def setUp(self):
        self.hostname = 'https://www.example.com'

    def validate_file_upload(self, request, context, filename, content):
        # self.assertEqual(something, something_else)
        # better solution goes here

    def test_submit_file(self):
        API_ENDPOINT = self.hostname + '/api/tasks/create/file/'
        DUMMY_FILE = 'file'
        DUMMY_CONTENT = 'here is the\ncontent of our\nfile'

        s = API(self.hostname)

        with open(DUMMY_FILE, 'w+') as f:
            f.write(DUMMY_CONTENT)

        with requests_mock.Mocker() as m:
            def json_callback(request, context):
                self.validate_file_upload(request, context, DUMMY_FILE,
                    DUMMY_CONTENT)
                return {}

            m.post(API_ENDPOINT, json=json_callback)
            s.upload_file(DUMMY_FILE)
</code></pre>

<p>I have determined that, upon successful file upload, the <code>request</code> parameter to the <code>validate_file_upload</code> has a couple relevant bits of data, namely <code>request.headers</code> and <code>request.text</code>. Here is the content of both of them after the <code>validate_file_upload</code> function is called:</p>

<p><strong><code>request.headers</code></strong></p>

<pre><code>{'User-Agent': 'python-requests/2.19.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Length': '171', 'Content-Type': 'multipart/form-data; boundary=e1a0aa05f83735e85ddca089c450a21b'}
</code></pre>

<p><strong><code>request.text</code></strong></p>

<pre><code>'--e1a0aa05f83735e85ddca089c450a21b\r\nContent-Disposition: form-data; name=""file""; filename=""file""\r\n\r\nhere is the\ncontent of our\nfile\r\n--e1a0aa05f83735e85ddca089c450a21b--\r\n'
</code></pre>

<hr>

<p>Now, here's the thing. I <strong>know that I can just parse</strong> the <code>request.text</code>  string and get the data I want; it's easy enough to validate. </p>

<p>However, that sort of logic seems like it really doesn't belong in my unit testing. I can't imagine there isn't a better solution to this; either someone has implemented this functionality already in a different module or I'm overlooking something obvious.</p>

<p><strong>I shouldn't have to implement the <a href=""https://stackoverflow.com/questions/8659808/how-does-http-file-upload-work"">HTTP spec</a> for file uploads</strong> to unit test something as simple as a file upload, right? Is there a better way of doing this?</p>

<hr>

<p>Here is the output of <code>dir(request)</code>:</p>

<pre><code>['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattr__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_allow_redirects', '_case_sensitive', '_cert', '_create', '_matcher', '_proxies', '_qs', '_request', '_stream', '_timeout', '_url_parts', '_url_parts_', '_verify', 'allow_redirects', 'cert', 'hostname', 'json', 'matcher', 'netloc', 'path', 'port', 'proxies', 'qs', 'query', 'scheme', 'stream', 'text', 'timeout', 'verify']
</code></pre>

<p>I have checked all of the non-underscore attributes for any other representation of the file upload data, to no avail. I've also tried searching <a href=""https://stackoverflow.com/search?q=requests_mock+file+upload"">StackOverflow</a> and <a href=""https://www.google.com/search?q=&quot;requests+mock&quot;+file+upload"" rel=""nofollow noreferrer"">Google</a>, and am no closer to finding a better way of doing this. This is the only post that shows up for either of the searches.</p>
",https://stackoverflow.com/questions/51715711/how-can-i-use-requests-mock-to-unit-test-a-file-upload,"['python', 'python-requests', 'python-unittest']",1525,TRUE,3,2
How are aggregates instantiated to test other aggregates with?,"<p>Suppose I have an aggregate that, for some operation, requires the existence of another aggregate. Let's assume I have a <code>car</code> and a <code>garage</code>. There might be a command called <code>ParkInGarage</code> that looks like this:</p>
<pre><code>public class ParkInGarage {

    @TargetAggregateIdentifier
    public final UUID carId;

    public final Garage garage;

    //... constructor omitted
}
</code></pre>
<p>I've <a href=""https://softwareengineering.stackexchange.com/a/319808/312886"">read</a> that to validate the existence of an aggregate, it is good practice to use the loaded aggregate in commands since that already implies its existence (as opposed to passing a <code>garageId</code>).</p>
<p>Now when unit-testing the <code>Car</code> using <a href=""https://docs.axoniq.io/reference-guide/v/3.0/part-ii-domain-logic/testing"" rel=""nofollow noreferrer"">Axon's fixtures</a>, I can not simply instantiate my <code>Garage</code> by saying <code>new Garage(buildGarageCmd)</code>. It will say:</p>
<blockquote>
<p>java.lang.IllegalStateException: Cannot request current Scope if none is active</p>
</blockquote>
<p>Because no infrastructure was set up.
How would I test such a case, or should I design the aggregate differently?</p>
<h2>Abstracted, real-world example</h2>
<p>The aggregate root I am working with may have a reference to itself to form a tree-structure of said aggregate root. Let's call it <code>Node</code>.</p>
<pre><code>@Aggregate
public class Node {
    private Node parentNode;
}
</code></pre>
<p>Upon creation, I can pass an <code>Optional&lt;Node&gt;</code> as parent, or set the parent at a later time using a separate command. Whether the parent should be defined as instance or by ID is part of the question.</p>
<pre><code>public class AttachNodeCmd {
    @TargetAggregateIdentifier
    public final UUID nodeId;
    public final Optional&lt;Node&gt; parentNode;
}
</code></pre>
<p>In the command handler, I need to check if attaching the node to given parent would introduce a cycle (the structure is supposed to be a tree, not a common graph).</p>
<pre><code>@CommandHandler
public Node(AttachNodeCmd command) {
    if (command.parentNode.isPresent()) {
        Node currentNode = command.parentNode.get();
        while (currentNode != null) {
            if (currentNode.equals(this)) throw new RecursionException();
            currentNode = currentNode.parentNode.orElse(null);
        }
    }

    //Accept the command by applying() an Event
}
</code></pre>
<p>At some point, the parent needs to be instantiated to perform those checks. This could either be done by supplying the aggregate instance in the command (discouraged), or by supplying a <code>Repository&lt;Node&gt;</code> and the <code>nodeId</code> to the command handler, which is the aggregate itself and also discouraged. Currently I don't see a right way to do this and further down the road a way to test it.</p>
",https://stackoverflow.com/questions/53322271/how-are-aggregates-instantiated-to-test-other-aggregates-with,"['unit-testing', 'domain-driven-design', 'aggregateroot', 'axon']",572,TRUE,1,2
javascript private variable does not point to shared object in unit test,"<p>We have an SPA application with a shared scope variable var <em>WIDGET</em>.  Each module adds itself to the shared <em>WIDGET</em> object or creates the <em>WIDGET</em> if it was not created.</p>

<p>Using a couple of frameworks for unit tests the shared <em>WIDGET</em> is available but the variable on the required files do not point to it.</p>

<p>var <em>WIDGET</em> = <em>WIDGET</em> || {};</p>

<p>if I change this line of code to <em>WIDGET</em> = <em>WIDGET</em> || {}  or if I remove it all together then the objects will work as expected in the unit test</p>

<p><strong>things to know:</strong></p>

<ul>
<li>we do NOT use nodejs in production, it is just for testing </li>
<li>code executes properly in production</li>
<li>test frameworks have been mocha and jest</li>
</ul>

<p><strong>Q1 what can I do to ensure the private variable is pointing to the shared object when unit testing?</strong></p>

<p><strong>Q2 why does this happen in testing but not in the DOM during application execution?</strong></p>

<p><code>test application creation:
     TypeError: Cannot read property 'getInstance' of undefined
      at new widget_application (widgetApplication.js:23:41)
      at Object.getInstance (widgetApplication.js:33:16)
      at Context.&lt;anonymous&gt; (test\testApp.js:16:39)</code></p>

<p>first module that adds itself to the <em>WIDGET</em> object</p>

<pre><code>var _WIDGET_ = _WIDGET_ || {};
//adds itself to the _WIDGET_ to be shared
_WIDGET_.widgetLogger = (function(){
    var INSTANCE;
    var _config = {};
    var _widgetLog = {};

    function widget_logger(config){
        if(config){_config = config;}
    }

    widget_logger.prototype.stageLog = stageLog;
    // widget_logger.prototype.startUpLog = startUpLog;
    // widget_logger.prototype.dataRefreshLog = dataRefreshLog;
    // widget_logger.prototype.widgetNotReadyLog = widgetNotReadyLog;
    // widget_logger.prototype.finalizeLog = finalizeLog;
    // widget_logger.prototype.getLog = getLog;

    return {
        getInstance:function(c){
            if(!INSTANCE){
                INSTANCE = new widget_logger(c);
            }
            return INSTANCE;
        }
    };

    function stageLog(data) {
        console.log(""widget logger called to stage log"");
        if(data){

            _widgetLog = {};
            _legacyLog = {};

            _widgetLog.widgetProgramCode = _config.versionData.programCode;
            _widgetLog.widgetVersion = _config.versionData.version;
            _widgetLog.startTime = data.startTime || new Date();

            console.log(""widget logger staged this log "",_widgetLog);

        }
    }

})();

//export is only for testing - nodejs NOT used in production
var module = module || {};
module.exports = _WIDGET_;
</code></pre>

<p>next module that adds itself and uses the logger module</p>

<pre><code>var _WIDGET_ = _WIDGET_ || {};//remove this line of code and unit test run
var _API_ = _API_ || {};
_WIDGET_.smallApplication = (function(){

    var INSTANCE;
    var widgetLogger;
    var _config = {
        versionData:{
            programCode:""smallApplication"",
            version:""1.0.2.0""
        }
    };

    function widget_application(config){
        console.log(""make the instance "");
        // var elem = document.getElementById('apprunning');
        // elem.innerHTML += ""    smallApplication is online "";
        if(config){_config = config;}
        //expects to have a shared object already
        //fails after this call because this module create a new _WIDGET_ variable
    //this does not happen in production - all components are created
        widgetLogger = _WIDGET_.widgetLogger.getInstance(_config);
    }

    widget_application.prototype.runApplication = runApplication;


    return {
        getInstance:function(c){
            console.log(""get instance was called"");
            if(!INSTANCE){
                INSTANCE = new widget_application(c);
            }
            return INSTANCE;
        }
    };

    //run some functions and hello world and all that happiness...
    function runApplication(){
        console.log(""widget application runs - will call logger"");
        widgetLogger.stageLog(true);
    }

})();

//export is only for testing - nodejs NOT used in production
var module = module || {};
module.exports = _WIDGET_;
</code></pre>

<p>mocha test script</p>

<pre><code>var assert = require('assert');

_WIDGET_ = {name: 'small application'};

describe('small application',function(){
    //_WIDGET_ = {name: 'small application'};
    //var _WIDGET_ {name: 'small application'};
    //global._WIDGET_ {name: 'small application'};
    it('test logger creation',function(){
        _WIDGET_ = require('../widgetLogger');
        console.log('_WIDGET_');
    });
    it('test application creation',function(){
        var app = require('../widgetApplication');
        _WIDGET_ = require('../widgetApplication');
    });
});
</code></pre>

<p><strong>A2 to Q2</strong> found at <a href=""https://medium.freecodecamp.org/requiring-modules-in-node-js-everything-you-need-to-know-e7fbd119be8"" rel=""nofollow noreferrer"">free code camp - require modules</a> In a browser, when we declare a variable in a script like this:</p>

<pre><code>var answer = 42;
</code></pre>

<p>That answer variable will be globally available in all scripts after the script that defined it.</p>

<p>This is not the case in Node. When we define a variable in one module, the other modules in the program will not have access to that variable. So how come variables in Node are magically scoped?</p>

<p>The answer is simple. Before compiling a module, Node wraps the module code in a function, which we can inspect using the wrapper property of the module module.</p>
",https://stackoverflow.com/questions/53027110/javascript-private-variable-does-not-point-to-shared-object-in-unit-test,"['javascript', 'unit-testing', 'global-variables']",170,TRUE,1,1
Visual Studio 2017 Enterprise won&#39;t stop running all tests on build,"<p>I have a project, composed of a 3 C#/.NET Core class libraries, targeting .NET Standard 2.0. In addition, I have a XUnit test project, where I use FluentAssertions.</p>

<p>When working on the project, I use Visual Studio 2017 Enterprise, with Resharper Ultimate installed.</p>

<p>When running the full suite of tests, my SQL Server 2016 Express database is hit around 8100 times.
If I leave my profiler running while working in Visual Studio, I can see that the full suite of tests is executed, whenever I change code and do a build.
It's a bit of a nuisance, since it takes a good 1-1½ minute for the tests to finish, and often, I will only want to run a specific subset of the tests, when making incremental changes.</p>

<p>My problem: I can't seem to stop the tests running from running on build.</p>

<p>What puzzles me the most is, that I can't cancel the tests from Test explorer or Resharpers Test window, as they appear not to be running at all.
Also, the Test pane of the output window does not show anything except ""....Discovering unittests"" without progressing any further.
My impressions is, that from Visual Studios perspective, the tests are not running at all.</p>

<p>Getting the primary suspects out of the way:</p>

<ul>
<li>The ""Run tests after build"" button in test explorer is not toggled
on.</li>
<li>Live unit testing appears to be disabled (The only option from the
menu is ""Start"")</li>
</ul>

<p>I've spent hours browsing the net trying to figure out what is going on, with no luck. I'm hoping someone here can help me find out why the tests are running, and how to stop them.</p>

<p><em>This is my first ever StackOverflow question. I hope my questions meets the requirements for asking. If not, please let me know what to do better.</em></p>
",https://stackoverflow.com/questions/49424651/visual-studio-2017-enterprise-wont-stop-running-all-tests-on-build,"['c#', 'visual-studio-2017', '.net-core', 'xunit']",751,TRUE,6,1
"TypeScript, Vue and experimentalDecorators","<p>I've created a Vue project through Vue-CLI v3.0.0-beta.15, now, everything is working, I mean, when I do <code>npm run serve</code> it compiles and runs fine but TypeScript throws the following error message and <strong>only inside the editor!</strong></p>

<pre><code>Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning.
</code></pre>

<p><strong>The things I've tried and didn't work:</strong></p>

<ol>
<li><p>I double check that the <code>experimentalDecorators</code> is set to true in my <code>tsconfig.json</code> file which Vue does by default.</p></li>
<li><p>I tried to create a <code>jsconfig.json</code> file with the following options:</p>

<pre><code>{
    ""compilerOptions"": {
        ""experimentalDecorators"": true
    }
}
</code></pre></li>
<li><p>I tried to change the following options in VSCode <code>""javascript.implicitProjectConfig.experimentalDecorators"": true</code></p></li>
</ol>

<p>Now, I'm using the Vetur extension with VSCode which I already posted an <a href=""https://github.com/vuejs/vetur/issues/815"" rel=""nofollow noreferrer"">issue</a> on their repo <strong>but I don't use any extensions with Visual Studio for Vue and yet I get the same error</strong> so I don't know what triggers it but I think that something doesn't pick the <code>tsconfig.json</code> file.</p>

<p><strong>Here are the steps I've taken to generate the project:</strong></p>

<ol>
<li>mkdir experiment &amp;&amp; cd $_</li>
<li>npm init</li>
<li>npm install -D <code>@vue/cli</code></li>
<li>./node_modules/.bin/vue create dashboard</li>
<li><p>I've used the following options:</p>

<ul>
<li>Check the features needed for your project: Babel, TS, PWA, Router, Vuex, CSS Pre-processors, Linter, Unit, E2E</li>
<li>Use class-style component syntax? Yes</li>
<li>Use Babel alongside TypeScript for auto-detected polyfills? Yes</li>
<li>Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): SCSS/SASS</li>
<li>Pick a linter / formatter config: TSLint</li>
<li>Pick additional lint features: Lint on save</li>
<li>Pick a unit testing solution: Mocha</li>
<li>Pick a E2E testing solution: Cypress</li>
<li>Where do you prefer placing config for Babel, PostCSS, ESLint, etc.? In dedicated config files</li>
<li>Save this as a preset for future projects? No</li>
</ul></li>
<li><p>Then navigate to dashboard/src/views/Home.vue</p></li>
</ol>

<p>That's how it looks like in <strong>Visual Studio</strong>:</p>

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

<p>And that's how it looks like in <strong>VSCode</strong>:</p>

<p><a href=""https://i.stack.imgur.com/5ejTt.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/5ejTt.png"" alt=""enter image description here""></a></p>
",https://stackoverflow.com/questions/50782749/typescript-vue-and-experimentaldecorators,"['typescript', 'vue.js', 'visual-studio-code', 'vetur']",3848,TRUE,5,2
Visual Studio 2017 requires restart after exception during debug,"<p>I have a strange problem in Visual Studio 2017 (version 15.7.1). Visual Studio fails to build after an exception occurs during a debug session. This is happening in a WebApi project that uses net462. One of the libraries in use is a custom library built in .NET 4.6.2 that uses Entity Framework 6, Automapper, and LinqKit.</p>

<p>After an exception, if I attempt to build, I get the following build errors and I have to restart Visual Studio to get a successful build:</p>

<pre><code>1&gt;Build FAILED.
1&gt;
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\WebApiApplication.exe"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\WebApiApplication.exe' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\AutoMapper.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\AutoMapper.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\EntityFramework.SqlServer.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\EntityFramework.SqlServer.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\EntityFramework.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\EntityFramework.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.DataProtection.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.DataProtection.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.Diagnostics.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.Diagnostics.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.Hosting.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.Hosting.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.Http.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.Http.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.Http.Abstractions.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.Http.Abstractions.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.Mvc.Abstractions.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.Mvc.Abstractions.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.Mvc.Core.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.Mvc.Core.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.Mvc.Razor.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.Mvc.Razor.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.Mvc.Razor.Extensions.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.Mvc.Razor.Extensions.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.Mvc.RazorPages.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.Mvc.RazorPages.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.Mvc.TagHelpers.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.Mvc.TagHelpers.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.Mvc.ViewFeatures.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.Mvc.ViewFeatures.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.Razor.Language.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.Razor.Language.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.Routing.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.Routing.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.Server.Kestrel.Core.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.Server.Kestrel.Core.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.StaticFiles.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.StaticFiles.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.WebUtilities.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.AspNetCore.WebUtilities.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.CodeAnalysis.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.CodeAnalysis.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.CodeAnalysis.CSharp.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.CodeAnalysis.CSharp.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.IdentityModel.Protocols.OpenIdConnect.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.IdentityModel.Protocols.OpenIdConnect.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.IdentityModel.Tokens.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.IdentityModel.Tokens.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.Net.Http.Headers.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.Net.Http.Headers.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.VisualStudio.Web.CodeGeneration.Core.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.VisualStudio.Web.CodeGeneration.Core.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.VisualStudio.Web.CodeGeneration.EntityFrameworkCore.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.VisualStudio.Web.CodeGenerators.Mvc.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Microsoft.VisualStudio.Web.CodeGenerators.Mvc.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Newtonsoft.Json.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Newtonsoft.Json.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Swashbuckle.AspNetCore.SwaggerUI.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Swashbuckle.AspNetCore.SwaggerUI.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\System.Collections.Immutable.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\System.Collections.Immutable.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\System.IdentityModel.Tokens.Jwt.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\System.IdentityModel.Tokens.Jwt.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\System.Numerics.Vectors.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\System.Numerics.Vectors.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\System.Net.Http.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\System.Net.Http.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\System.ValueTuple.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\System.ValueTuple.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Camms.Wapi.Common.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Camms.Wapi.Common.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\CAMMS.WAPI.Repository.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\CAMMS.WAPI.Repository.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(5033,5): warning MSB3061: Unable to delete file ""C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Oracle.ManagedDataAccess.EntityFramework.dll"". Access to the path 'C:\PATH_TO_PROJECT_FOLDER\bin\Debug\net462\Oracle.ManagedDataAccess.EntityFramework.dll' is denied.
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(4172,5): warning MSB3026: Could not copy ""obj\Debug\net462\WebApiApplication.exe"" to ""bin\Debug\net462\WebApiApplication.exe"". Beginning retry 1 in 1000ms. The process cannot access the file 'bin\Debug\net462\WebApiApplication.exe' because it is being used by another process. The file is locked by: ""Microsoft Visual Studio 2017 (9520)""
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(4172,5): warning MSB3026: Could not copy ""obj\Debug\net462\WebApiApplication.exe"" to ""bin\Debug\net462\WebApiApplication.exe"". Beginning retry 2 in 1000ms. The process cannot access the file 'bin\Debug\net462\WebApiApplication.exe' because it is being used by another process. The file is locked by: ""Microsoft Visual Studio 2017 (9520)""
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(4172,5): warning MSB3026: Could not copy ""obj\Debug\net462\WebApiApplication.exe"" to ""bin\Debug\net462\WebApiApplication.exe"". Beginning retry 3 in 1000ms. The process cannot access the file 'bin\Debug\net462\WebApiApplication.exe' because it is being used by another process. The file is locked by: ""Microsoft Visual Studio 2017 (9520)""
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(4172,5): warning MSB3026: Could not copy ""obj\Debug\net462\WebApiApplication.exe"" to ""bin\Debug\net462\WebApiApplication.exe"". Beginning retry 4 in 1000ms. The process cannot access the file 'bin\Debug\net462\WebApiApplication.exe' because it is being used by another process. The file is locked by: ""Microsoft Visual Studio 2017 (9520)""
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(4172,5): warning MSB3026: Could not copy ""obj\Debug\net462\WebApiApplication.exe"" to ""bin\Debug\net462\WebApiApplication.exe"". Beginning retry 5 in 1000ms. The process cannot access the file 'bin\Debug\net462\WebApiApplication.exe' because it is being used by another process. The file is locked by: ""Microsoft Visual Studio 2017 (9520)""
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(4172,5): warning MSB3026: Could not copy ""obj\Debug\net462\WebApiApplication.exe"" to ""bin\Debug\net462\WebApiApplication.exe"". Beginning retry 6 in 1000ms. The process cannot access the file 'bin\Debug\net462\WebApiApplication.exe' because it is being used by another process. The file is locked by: ""Microsoft Visual Studio 2017 (9520)""
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(4172,5): warning MSB3026: Could not copy ""obj\Debug\net462\WebApiApplication.exe"" to ""bin\Debug\net462\WebApiApplication.exe"". Beginning retry 7 in 1000ms. The process cannot access the file 'bin\Debug\net462\WebApiApplication.exe' because it is being used by another process. The file is locked by: ""Microsoft Visual Studio 2017 (9520)""
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(4172,5): warning MSB3026: Could not copy ""obj\Debug\net462\WebApiApplication.exe"" to ""bin\Debug\net462\WebApiApplication.exe"". Beginning retry 8 in 1000ms. The process cannot access the file 'bin\Debug\net462\WebApiApplication.exe' because it is being used by another process. The file is locked by: ""Microsoft Visual Studio 2017 (9520)""
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(4172,5): warning MSB3026: Could not copy ""obj\Debug\net462\WebApiApplication.exe"" to ""bin\Debug\net462\WebApiApplication.exe"". Beginning retry 9 in 1000ms. The process cannot access the file 'bin\Debug\net462\WebApiApplication.exe' because it is being used by another process. The file is locked by: ""Microsoft Visual Studio 2017 (9520)""
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(4172,5): warning MSB3026: Could not copy ""obj\Debug\net462\WebApiApplication.exe"" to ""bin\Debug\net462\WebApiApplication.exe"". Beginning retry 10 in 1000ms. The process cannot access the file 'bin\Debug\net462\WebApiApplication.exe' because it is being used by another process. The file is locked by: ""Microsoft Visual Studio 2017 (9520)""
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(4172,5): error MSB3027: Could not copy ""obj\Debug\net462\WebApiApplication.exe"" to ""bin\Debug\net462\WebApiApplication.exe"". Exceeded retry count of 10. Failed. The file is locked by: ""Microsoft Visual Studio 2017 (9520)""
1&gt;C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets(4172,5): error MSB3021: Unable to copy file ""obj\Debug\net462\WebApiApplication.exe"" to ""bin\Debug\net462\WebApiApplication.exe"". The process cannot access the file 'bin\Debug\net462\WebApiApplication.exe' because it is being used by another process.
</code></pre>

<p>Here is the installation information for my Visual Studio:</p>

<pre><code>Microsoft Visual Studio Enterprise 2017 
Version 15.7.1
VisualStudio.15.Release/15.7.1+27703.2000
Microsoft .NET Framework
Version 4.7.02556

Installed Version: Enterprise

Architecture Diagrams and Analysis Tools   00369-60000-00001-AA311
Microsoft Architecture Diagrams and Analysis Tools

Visual C++ 2017   00369-60000-00001-AA311
Microsoft Visual C++ 2017

ActiveReports 11   11.2.10750.0
The first report writer for Microsoft .NET

Application Insights Tools for Visual Studio Package   8.12.10405.1
Application Insights Tools for Visual Studio

ASP.NET and Web Tools 2017   15.0.40501.0
ASP.NET and Web Tools 2017

ASP.NET Core Razor Language Services   15.7.31476
Provides languages services for ASP.NET Core Razor.

ASP.NET Web Frameworks and Tools 2012   4.0.21208.0
For additional information, visit https://www.asp.net/

ASP.NET Web Frameworks and Tools 2017   5.2.60419.0
For additional information, visit https://www.asp.net/

Azure App Service Tools v3.0.0   15.0.40424.0
Azure App Service Tools v3.0.0

C# Tools   2.8.0-beta6-62830-08. Commit Hash: e595ee276d14e14bfb3eb323fb57f2aa668bddea
C# components used in the IDE. Depending on your project type and settings, a different version of the compiler may be used.

Common Azure Tools   1.10
Provides common services for use by Azure Mobile Services and Microsoft Azure Tools.

JavaScript Language Service   2.0
JavaScript Language Service

JavaScript Project System   2.0
JavaScript Project System

JavaScript UWP Project System   2.0
JavaScript UWP Project System

JetBrains ReSharper Ultimate 2018.1    Build 112.0.20180414.70444
JetBrains ReSharper Ultimate package for Microsoft Visual Studio. For more information about ReSharper Ultimate, visit http://www.jetbrains.com/resharper. Copyright © 2018 JetBrains, Inc.

Merq   1.1.17-rc (cba4571)
Command Bus, Event Stream and Async Manager for Visual Studio extensions.

Microsoft Azure Tools   2.9
Microsoft Azure Tools for Microsoft Visual Studio 2017 - v2.9.10420.2

Microsoft Continuous Delivery Tools for Visual Studio   0.3
Simplifying the configuration of continuous build integration and continuous build delivery from within the Visual Studio IDE.

Microsoft JVM Debugger   1.0
Provides support for connecting the Visual Studio debugger to JDWP compatible Java Virtual Machines

Microsoft MI-Based Debugger   1.0
Provides support for connecting Visual Studio to MI compatible debuggers

Microsoft Visual C++ Wizards   1.0
Microsoft Visual C++ Wizards

Microsoft Visual Studio Tools for Containers   1.1
Develop, run, validate your ASP.NET Core applications in the target environment. F5 your application directly into a container with debugging, or CTRL + F5 to edit &amp; refresh your app without having to rebuild the container.

Microsoft Visual Studio VC Package   1.0
Microsoft Visual Studio VC Package

Mono Debugging for Visual Studio   4.10.5-pre (ab58725)
Support for debugging Mono processes with Visual Studio.

Node.js Tools   1.4.11027.3
Adds support for developing and debugging Node.js apps in Visual Studio

NuGet Package Manager   4.6.0
NuGet Package Manager in Visual Studio. For more information about NuGet, visit http://docs.nuget.org/.

ProjectServicesPackage Extension   1.0
ProjectServicesPackage Visual Studio Extension Detailed Info

ResourcePackage Extension   1.0
ResourcePackage Visual Studio Extension Detailed Info

Sandcastle Help File Builder   SHFB
Visual Studio integration for the Sandcastle Help File Builder.
https://GitHub.com/EWSoftware/SHFB

Snapshot Debugging Extension   1.0
Snapshot Debugging Visual Studio Extension Detailed Info

SQL Server Data Tools   15.1.61804.210
Microsoft SQL Server Data Tools

SQL Server Reporting Services   14.0.1016.246
Microsoft SQL Server Reporting Services Designers 
Version 14.0.1016.246

Syntax Visualizer   1.0
An extension for visualizing Roslyn SyntaxTrees.

TypeScript Tools   15.7.20419.2003
TypeScript Tools for Microsoft Visual Studio

Visual Basic Tools   2.8.0-beta6-62830-08. Commit Hash: e595ee276d14e14bfb3eb323fb57f2aa668bddea
Visual Basic components used in the IDE. Depending on your project type and settings, a different version of the compiler may be used.

Visual F# Tools 10.1 for F# 4.1   15.7.0.0.  Commit Hash: 16ecf5a30ad868d183c58e4a71a71c23d4ed3ba9.
Microsoft Visual F# Tools 10.1 for F# 4.1

Visual Studio Code Debug Adapter Host Package   1.0
Interop layer for hosting Visual Studio Code debug adapters in Visual Studio

Visual Studio Tools for Apache Cordova   15.123.7408.1
Visual Studio Tools for Apache Cordova

Visual Studio Tools for Universal Windows Apps   15.0.27703.01
The Visual Studio Tools for Universal Windows apps allow you to build a single universal app experience that can reach every device running Windows 10: phone, tablet, PC, and more. It includes the Microsoft Windows 10 Software Development Kit.

VisualStudio.Mac   1.0
Mac Extension for Visual Studio

Windows Machine Learning Generator Extension   1.0
Windows Machine Learning Visual Studio Extension Detailed Info

Xamarin   4.10.0.442 (396b18cef)
Visual Studio extension to enable development for Xamarin.iOS and Xamarin.Android.

Xamarin Designer   4.12.264 (fc37cd02e)
Visual Studio extension to enable Xamarin Designer tools in Visual Studio.

Xamarin.Android SDK   8.3.0.19 (HEAD/342b2ce96)
Xamarin.Android Reference Assemblies and MSBuild support.

Xamarin.iOS and Xamarin.Mac SDK   11.10.1.177 (7e782c1)
Xamarin.iOS and Xamarin.Mac Reference Assemblies and MSBuild support.
</code></pre>

<p>I've searched the web, but I can't find anything even remotely related. I even opened a help ticket with Microsoft, but they wanted me to give them a small project that has the problem reproduced. I was unable to reproduce the issue outside of our proprietary code, so I couldn't send them anything. However, I can add that if I remove the .NET 4.6.2 project from the mix, this does not happen. Since this is not a realistic expectation for our production code, I'm looking for a solution to the problem.</p>

<p>It's not happening for everyone on my team, only on my computer.</p>

<p>Here is what I have tried:</p>

<ul>
<li>Delete bin and obj folders - This is not possible after an exception because Visual Studio has files in these folders locked. It is possible to delete them after a restart and before a debug session</li>
<li>Install the latest Visual Studio update (15.7.1)</li>
<li>Disable Diagnostic tools during debugging</li>
<li>Disable Live Unit Testing during build and debug</li>
</ul>

<p>I'm at a loss. What can I do to get Visual Studio back to building after an exception? Has anyone else seen similar behavior?</p>

<p>Thanks</p>
",https://stackoverflow.com/questions/50471685/visual-studio-2017-requires-restart-after-exception-during-debug,"['c#', 'visual-studio', 'visual-studio-2017', 'visual-studio-debugging', 'asp.net-core-webapi']",1006,TRUE,3,1
Can you use mock_open to simulate serial connections?,"<p>Morning folks,</p>

<p>I'm trying to get a few unit tests going in Python to confirm my code is working, but I'm having a real hard time getting a Mock anything to fit into my test cases.  I'm new to Python unit testing, so this has been a trying week thus far.</p>

<p>The summary of the program is I'm attempting to do serial control of a commercial monitor I got my hands on and I thought I'd use it as a chance to finally use Python for something rather than just falling back on one of the other languages I know.  I've got pyserial going, but before I start shoving a ton of commands out to the TV I'd like to learn the unittest part so I can write for my expected outputs and inputs.</p>

<p>I've tried using a library called dummyserial, but it didn't seem to be recognising the output I was sending.  I thought I'd give mock_open a try as I've seen it works like a standard IO as well, but it just isn't picking up on the calls either.  Samples of the code involved:</p>

<pre><code>def testSendCmd(self):
    powerCheck = '{0}{1:&gt;4}\r'.format(SharpCodes['POWER'], SharpCodes['CHECK']).encode('utf-8')
    read_text = 'Stuff\r'
    mo = mock_open(read_data=read_text)
    mo.in_waiting = len(read_text)
    with patch('__main__.open', mo):
        with open('./serial', 'a+b') as com:
            tv = SharpTV(com=com, TVID=999, tvInput = 'DVI')
            tv.sendCmd(SharpCodes['POWER'], SharpCodes['CHECK'])
            com.write(b'some junk')
    print(mo.mock_calls)
    mo().write.assert_called_with('{0}{1:&gt;4}\r'.format(SharpCodes['POWER'], SharpCodes['CHECK']).encode('utf-8'))
</code></pre>

<p>And in the SharpTV class, the function in question:</p>

<pre><code>def sendCmd(self, type, msg):
    sent = self.com.write('{0}{1:&gt;4}\r'.format(type,msg).encode('utf-8'))
    print('{0}{1:&gt;4}\r'.format(type,msg).encode('utf-8'))
</code></pre>

<p>Obviously, I'm attempting to control a Sharp TV.  I know the commands are correct, that isn't the issue.  The issue is just the testing.  According to documentation on the mock_open page, calling <code>mo.mock_calls</code> should return some data that a call was made, but I'm getting just an empty set of []'s even in spite of the blatantly wrong <code>com.write(b'some junk')</code>, and <code>mo().write.assert_called_with(...)</code> is returning with an assert error because it isn't detecting the write from within sendCmd.  What's really bothering me is I can do the examples from the mock_open section in interactive mode and it works as expected.</p>

<p>I'm missing something, I just don't know what.  I'd like help getting either dummyserial working, or mock_open.</p>
",https://stackoverflow.com/questions/53327415/can-you-use-mock-open-to-simulate-serial-connections,"['python', 'python-3.x', 'python-unittest', 'pyserial']",914,TRUE,2,1
Azure Functions testing when using imperative binding,"<p>So far I've been able to setup unit testing for Azure Functions and it works great. However for my current project I need to use dynamic or imperative bindings.
<a href=""https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-csharp#imperative-bindings"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-csharp#imperative-bindings</a></p>

<p>This leads to issues for my unit test I cannot seem to solve.</p>

<p>My function looks like this:</p>

<pre><code>using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.ServiceBus.Messaging;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace My.Functions
{
    public static class MyFunc
    {
        [FunctionName(""my-func"")]
        public static async Task&lt;HttpResponseMessage&gt; Run([HttpTrigger(AuthorizationLevel.Function, ""post"", Route = null)] HttpRequestMessage req,
            Binder binder)
        {
            dynamic data = await req.Content.ReadAsAsync&lt;object&gt;();
            byte[] bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(data));
            MemoryStream stream = new MemoryStream(bytes, writable: false);

            var sbMsg = new BrokeredMessage(stream) { ContentType = ""application/json"" };
            var attributes = new Attribute[]
            {
                new ServiceBusAccountAttribute(""some-sb-account""),
                new ServiceBusAttribute(""some-queue-or-topic"", AccessRights.Send)
            };
            var outputSbMessage = await binder.BindAsync&lt;IAsyncCollector&lt;BrokeredMessage&gt;&gt;(attributes);
            await outputSbMessage.AddAsync(sbMsg);

            return req.CreateResponse(HttpStatusCode.OK, ""OK"");
        }
    }
}
</code></pre>

<p>Near the end of the code of the function, I configure this binder to hold a list of BrokeredMessages. This is done by calling the BindAsync on the binder.</p>

<p>The attributes are dynamically set and contain a servicebus connection and topic name. This all works great when deployed to Azure so functionality-wise everything is fine. 
So far so good.</p>

<p>However I'm stuggling with getting my test running. To be able to invoke the function, I need to provide parameters. The HttpTrigger this is pretty common, but for the Binder I don't know what to provide.</p>

<p>For testing I use this approach:</p>

<pre><code>[TestMethod]
public void SendHttpReq()
{
    // Setup
    var httpRequest = GetHttpRequestFromTestFile(""HttpRequest"");
    var sbOutput = new CustomBinder();

    // Act
    var response = SendToServicebus.Run(httpRequest, sbOutput);

    // Assert
    Assert.AreEqual(sbOutput.Count(), 1);

    // Clean up
}
</code></pre>

<p>I use a CustomBinder inherited from Binder, because just having an instance of Binder failed in the function on the 'BindAsync' throwing 'Object reference not set to an instance of an object'. It seems the constructor of the binder is actually not meant to be called.</p>

<p>In the CustomBinder I override the BindAsync to return a generic list of BrokeredMessages.</p>

<pre><code>public class CustomBinder : Binder
{
 public override async Task&lt;TValue&gt; BindAsync&lt;TValue&gt;(Attribute[] attributes, CancellationToken cancellationToken = new CancellationToken())
 {
  return (TValue)((object)(new List&lt;BrokeredMessage&gt;()));
  }
}
</code></pre>

<p>Not entirely surprising that also failed throwing:</p>

<blockquote>
  <p>InvalidCastException: Unable to cast object of type 'System.Collections.Generic.List'1[Microsoft.ServiceBus.Messaging.BrokeredMessage]' to type 'Microsoft.Azure.WebJobs.IAsyncCollector`1[Microsoft.ServiceBus.Messaging.BrokeredMessage]'.</p>
</blockquote>

<p>I cannot find an implementation of the IAsyncCollector, so maybe I need to approach this differently? </p>

<p>My actual goal is to be able to verify the list of brokered messages, as the function would output to Azure servicebus.</p>
",https://stackoverflow.com/questions/48215697/azure-functions-testing-when-using-imperative-binding,"['c#', 'unit-testing', 'azure-functions']",2499,TRUE,2,1
How do I correctly handle output directories for GCC test coverage profiling?,"<p>I am trying to generate coverage data for my unit tests, with the ultimate goal of displaying said data as part of our automated build output.</p>

<p>We build using makefiles and <code>cs-make</code>, with <code>cxxtest</code> as the unit test framework. The autogenerated test runner file is C++, with all our application files in C.</p>

<p>The unit test target and recipe for a unit test executable is:</p>

<pre><code>.SECONDEXPANSION:
UnitTest/%.exe: UnitTest/Tests/$$*/$$*Tests_cxx.cpp
    cs-rm *.gcda
    ..\cxxtest\bin\cxxtestgen --error-printer -o $@ $(addsuffix .h, $(basename $@))
    gcc -ftest-coverage -fprofile-arcs $(INCLUDES) $($*_SOURCES) -o $@
    ./$@
    gcovr -v
</code></pre>

<p>With <code>$(INCLUDES)</code> and <code>$(SOURCES)</code> as appropriate.</p>

<p>The recipe is executed by running (for example)</p>

<p><code>cs-make cs-make -C TestPlatform -f UnitTest\makefile UnitTest\Test1.exe</code></p>

<p>This builds <code>Test1.exe</code> and generates <code>.gcno</code> files. <code>Test1.exe</code> runs and generates <code>.gcda</code> files. <code>gcovr</code> correctly interprets these files and outputs coverage data.</p>

<p>So far, so good. But we are actually building and running several unit tests in parallel by executing:</p>

<p><code>cs-make -C TestPlatform -j -f UnitTest\makefile UnitTest\all</code></p>

<p>where <code>all</code> is dependent on all defined unit test executables.</p>

<p>To support parallel builds, I added this option to my GCC call:</p>

<pre><code>-fprofile-dir=UnitTest/Tests/$*/Coverage
</code></pre>

<p>which puts the .gcda files for each executable in a seperate directoy.</p>

<p>But now, gcovr does not process the files correctly:</p>

<pre><code>gcovr -v
Filters for --root: (1)
- &lt;_sre.SRE_Pattern object at 0x0000000004FED600&gt;
Filters for --filter: (1)
- DirectoryPrefixFilter(C\:\/Workspace\/CoverageTest\/TestPlatform\/)
Filters for --exclude: (0)
Filters for --gcov-filter: (1)
- AlwaysMatchFilter()
Filters for --gcov-exclude: (0)
Filters for --exclude-directories: (0)
Scanning directory . for gcda/gcno files...
Found 6 files (and will process 4)
Pool started with 1 threads
Processing file: C:\Workspace\CoverageTest\TestPlatform\UnitTest\Tests\Test1\Coverage\coverage.gcda
Running gcov: 'gcov C:\Workspace\CoverageTest\TestPlatform\UnitTest\Tests\Test1\Coverage\coverage.gcda --branch-counts --branch-probabilities --preserve-paths --object-directory C:\Workspace\CoverageTest\TestPlatform\UnitTest\Tests\Test1\Coverage' in 'c:\users\jfowkes\appdata\local\temp\tmpdfjja7'
Processing file: C:\Workspace\CoverageTest\TestPlatform\Test1Tests_cxx.gcda
Running gcov: 'gcov C:\Workspace\CoverageTest\TestPlatform\Test1Tests_cxx.gcda --branch-counts --branch-probabilities --preserve-paths --object-directory C:\Workspace\CoverageTest\TestPlatform' in 'c:\users\jfowkes\appdata\local\temp\tmpdfjja7'
Processing file: C:\Workspace\CoverageTest\TestPlatform\coverage.gcda
Running gcov: 'gcov C:\Workspace\CoverageTest\TestPlatform\coverage.gcda --branch-counts --branch-probabilities --preserve-paths --object-directory C:\Workspace\CoverageTest\TestPlatform' in 'c:\users\jfowkes\appdata\local\temp\tmpdfjja7'
Processing file: C:\Workspace\CoverageTest\TestPlatform\UnitTest\Tests\Test1\Coverage\Test1Tests_cxx.gcda
Running gcov: 'gcov C:\Workspace\CoverageTest\TestPlatform\UnitTest\Tests\Test1\Coverage\Test1Tests_cxx.gcda --branch-counts --branch-probabilities --preserve-paths --object-directory C:\Workspace\CoverageTest\TestPlatform\UnitTest\Tests\Test1\Coverage' in 'c:\users\jfowkes\appdata\local\temp\tmpdfjja7'
Gathered coveraged data for 0 files
------------------------------------------------------------------------------
                           GCC Code Coverage Report
Directory: .
------------------------------------------------------------------------------
File                                       Lines    Exec  Cover   Missing
------------------------------------------------------------------------------
------------------------------------------------------------------------------
TOTAL                                          0       0    --%
------------------------------------------------------------------------------
cs-make: Leaving directory `C:/Workspace/CoverageTest/TestPlatform'
</code></pre>

<p><code>gcovr</code> seems to be finding the files and handing them off to <code>gcov</code>, but no coverage data comes out.</p>

<p>I've tried various different <code>gcovr</code> options, but none seem to make this any better.</p>

<p>I'm running this build on Windows 10 in Eclipse CDT - this is requirement for us. I suspect based on other answers that there might be path and/or directory separator issues, but really I'm not sure of anything at the moment.</p>

<p>My question is: <em>what changes do I need to make to by makefile so I can add this coverage data to our build, which continuing to support parallel builds?</em></p>

<p>I can of course restructure our unit testing to have a makefile-per-unit-test-suite, but this is substantial work and I would like to avoid it if at all possible.</p>
",https://stackoverflow.com/questions/52970440/how-do-i-correctly-handle-output-directories-for-gcc-test-coverage-profiling,"['gcc', 'makefile', 'code-coverage', 'gcov', 'gcovr']",1538,TRUE,1,1
How do I get SonarQube to analyse Code Smells in unit tests but not count them for coverage reports?,"<p>I have C++ project being analysed with the commercial SonarQube plugin.</p>

<p>My project has, in my mind, an artificially high code coverage percentage reported as both the ""production"" source code lines and Unit Test code lines are counted.  It is quite difficult to write many unit test code lines that are not run as a part of the unit testing, so they give an immediate boost to the coverage reports.  </p>

<p>Is it possible to have the Unit Test code still analysed for Code Smells but not have it count towards the test coverage metric?  </p>

<p>I have tried setting the <code>sonar.tests=./Tests</code> parameter (where ./Tests is the directory with my test code.  This seems to exclude the test code from all analysis, leaving smells undetected.  I would rather check that the test code is of good quality than hope it is obeying the rules applied to the project.  </p>

<p>I tried adding the <code>sonar.test.inclusions=./Tests/*</code> in combination with the above.  However, I either got the file path syntax incorrect or setting this variable causes a complete omission of the Test code, so that it no longer appears under the 'Code' tab at all as well as being excluded.  </p>

<p>The <a href=""https://docs.sonarqube.org/display/SONAR/Narrowing+the+Focus"" rel=""nofollow noreferrer"">documentation on <strong>Narrowing the Focus</strong> of what is analysed</a> is not all the clear on what the expected behaviour is, at least to me.  Any help would be greatly appreciated as going through every permutation will be quite confusing.  </p>

<p>Perhaps I should just accept the idea that with ~300 lines of ""production"" code and 900 lines of stubs, mocks and unit tests a value of 75% test coverage could mean running 0 lines of ""production"" code.  I checked and currently, my very simple application is at about that ratio of test code to ""production"" code.  I'd expect the ratio to move more towards 50:50 over time but it might not do.  </p>
",https://stackoverflow.com/questions/50516502/how-do-i-get-sonarqube-to-analyse-code-smells-in-unit-tests-but-not-count-them-f,"['unit-testing', 'sonarqube', 'metrics', 'software-quality']",1607,FALSE,1,1
Is this method of data binding in Android suitable for production use? Does it contain hidden problems?,"<p>I'm working on an Android app and I want to implement the MVVM pattern, which is pretty much the standard pushed by Google, however, I'd like to avoid using Android Data Bindings library if possible, since I hate autogenerated XML magic.</p>

<p>I've tried to implement something essentially akin to databinding in RxJava (Kotlin) using Jake Wharton's data binding library, plus some helpful extension methods.</p>

<p>My question is, is this the right way to go about things? Is this good enough to use in production? Are there potential problems I'm not seeing with this approach that will pop up later?</p>

<hr>

<p>Essentially, I've implemented it like this:</p>

<p>I have a <code>MvvmFragment</code> (there is a similar class for activities) which takes care of setting up and managing the lifecycle of a <code>CompositeDisposable</code> object.</p>

<p>Then, in my <code>ViewModel</code> (part of the android Arch ViewModel package) I have all of the fields that will be bound to declared like this:</p>

<pre><code>var displayName = BindableVar("""")
var email = BindableVar("""")
var signInProvider = BindableVar&lt;AuthProvider&gt;(defaultValue = AuthProvider.PASSWORD)
</code></pre>

<p>(Side note - Since Rx doesn't allow null values, I'm not sure how to handle the case of defaults for objects where the concept of a default doesn't really make sense, such as the <code>AuthProvider</code> above)</p>

<p>The <code>BindableVar</code> class is implemented like this:</p>

<pre><code>class BindableVar&lt;T&gt;(defaultValue: T) {

    var value: T = defaultValue
        set(value) {
            field = value
            observable.onNext(value)
        }

    var observable = BehaviorSubject.createDefault(value)!!

}
</code></pre>

<p>Using Jake Wharton's RxBindings library, I have created some helpful extension methods on top of that, such as:</p>

<pre><code>fun Disposable.addTo(compositeDisposable: CompositeDisposable): Disposable {
    compositeDisposable.add(this)
    return this
}

fun TextView.bindTextTo(string: BindableVar&lt;String&gt;): Disposable {
    return string.observable.subscribe(this.text())
}

fun View.bindVisibilityTo(visibility: Int) {
    // ... not shown
}

fun ImageView.bindImageUriTo(
        src: BindableVar&lt;Uri&gt;, @DrawableRes placeholder: Int? = null
): Disposable {
    return if (placeholder == null) {
        src.observable.subscribe {
            GlideApp.with(context).load(it).into(this)
        }
    } else {
        src.observable.subscribe {
            GlideApp.with(context).load(it).placeholder(placeholder).into(this)
        }
    }
}
</code></pre>

<p>Using these extension methods, I then obtain the <code>ViewModel</code> instance on Fragment initialization, and call a method <code>initBindings()</code>, which looks something like this:</p>

<pre><code>item_display_name_value.bindTextTo(viewModel.displayName).addTo(bindings)
item_email_address_value.bindTextTo(viewModel.email).addTo(bindings)
item_profile_picture_view.bindImageUrlTo(viewModel.avatarUrl).addTo(bindings)
</code></pre>

<p>I want to avoid getting a week into fleshing out this architecture and then suddenly realizing there is some critical problem that can't be solved easily, or some other hidden gotcha. Should I just go with XML based data binding? I've heard a lot of complaints about the difficulty of unit-testing it, and the difficulty of reusing code with it.</p>
",https://stackoverflow.com/questions/51676306/is-this-method-of-data-binding-in-android-suitable-for-production-use-does-it-c,"['android', 'mvvm', 'data-binding', 'kotlin', 'rx-java2']",315,FALSE,1,0
How to unit test objects that depend on previous values,"<p>Over time I've improved my unit testing by refactoring functions so they are <a href=""https://en.wikipedia.org/wiki/Pure_function"" rel=""nofollow noreferrer"">pure functions</a> meaning a set of inputs always produces the same output without depending on any sort of state and without causing side effects.</p>

<p>Occasionally I encounter scenarios for which I'm not sure how to write good unit tests such as when a function (or object) must depend on previous values. For purposes of demonstration I include this excerpt of code for an averaging filter here but really my question is quite general.</p>

<p>One of the reasons I created the method CAvgFilter::Clear was so that I could always insure the filter responds in a desirable way while it is being primed. While being primed CAvgFilter::Push outputs track the inputs quite closely but once the m_samples list is full, deviations to the inputs to CAvgFilter::Push are less pronounced due to the filtering.</p>

<p>With objects like these I usually want a way to call a method with several series of inputs while checking the outputs and ideally my unit test has as few dependencies on data ordering as possible (ideally none).</p>

<p>When creating test vectors I often log data from the function output, verify it manually, and then use that for future tests (to insure the class doesn't break if I refactor or modify it later). Anyway, it occurred to me that I can't exactly just use any series of inputs/outputs in the middle of some range. I have to start with the filter clear (or add some functionality to otherwise initialize it for test purposes). Can anyone offer some suggestions on how this sort of thing is tackled in unit tests? Do you always start your test in the initialized state or do you offer the unit test some way to set the initial condition?</p>

<pre><code>CAvgFilter::CAvgFilter(int length)
{
    m_maxLength = length;
}

//pass the new value and receive the moving average
long CAvgFilter::Push(long newValue)
{
    m_samples.push_back(newValue);

    if ((int) m_samples.size() &gt; m_maxLength)
    {
        m_samples.pop_front();
    }

    long sum = 0;

    for (FILTER_CONTAINER_IT it = m_samples.begin(); it != m_samples.end(); ++it)
    {
        sum += *it;
    }

    return (sum / (long) m_samples.size()); //cast size() as long to preserve sign of the average value
}

void CAvgFilter::Clear(void)
{
    m_samples.clear();
}
</code></pre>
",https://stackoverflow.com/questions/48445967/how-to-unit-test-objects-that-depend-on-previous-values,['unit-testing'],247,TRUE,1,1
Instrument Netty&#39;s EventLoop for deterministic execution of scheduled tasks,"<p>I'd like to instrument Netty's <code>EventLoop</code> in order to:</p>

<ul>
<li>Run tasks in a deterministic order.</li>
<li>Grab the deadline of scheduled tasks.</li>
<li>Fast-forward a virtual clock, triggering execution of deadlined tasks. </li>
</ul>

<p>I know about <code>EmbeddedChannel</code> and I use it in some tests. But what I want is something between unit testing, and integration testing that remains blind about some corner cases. Deconnection-reconnection and ping scenarios use scheduled tasks a lot. I could add determinism with huge delays, but I don't want my tests to wait for seconds or more. So instrumenting Netty's <code>EventLoop</code> looks like the solution.</p>

<p>I've already written code that makes sense at least to me.</p>

<ul>
<li>I modify <code>ScheduledFutureTask#nanoTime</code> to return a value of mine.</li>
<li>I derive <code>NioEventLoopGroup</code> so I grab tasks deadlines.</li>
<li>I alter the value returned by <code>ScheduledFutureTask#nanoTime</code>.</li>
</ul>

<p>What is nice is that Netty code only relies on the value returned by <code>ScheduledFutureTask#nanoTime</code> (great design!) so it is a very limited change. I use ByteBuddy to avoid copy-pasting Netty code, but this is not important.</p>

<p>A very simple test like <code>InstrumentedNioEventLoopGroupTest</code> fails when scheduling only 1 task because <code>AbstractScheduledEventExecutor#pollScheduledTask(long)</code> has a null queue. </p>

<p>I discovered that each <code>NioEventLoop</code> has its own task queue, and queue polling might not happen because <code>NioEventLoopGroup</code> waits for a <code>Selector</code> to signal something, which makes sense. So I increased the thread count of the <code>NioEventLoopGroup</code> to 2. I also tried to set <code>ioRatio</code> to 1 and schedule more tasks, with no better results. Using the debugger, it seems that my tasks always ""falls"" in the task queue that is not polled.</p>

<p>Any idea to make this work? I'm using Netty 4.1.24.Final.</p>

<p><em><code>ScheduledFutureTaskHack.java</code></em></p>

<pre><code>package com.otcdlink.chiron.integration.harness;

import com.otcdlink.chiron.toolbox.ToStringTools;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.agent.ByteBuddyAgent;
import net.bytebuddy.dynamic.loading.ClassReloadingStrategy;
import net.bytebuddy.implementation.MethodDelegation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.Future;
import java.util.function.LongSupplier;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static net.bytebuddy.matcher.ElementMatchers.isPackagePrivate;
import static net.bytebuddy.matcher.ElementMatchers.isStatic;
import static net.bytebuddy.matcher.ElementMatchers.named;
import static net.bytebuddy.matcher.ElementMatchers.returns;
import static net.bytebuddy.matcher.ElementMatchers.takesArguments;

/**
 *
 * Got the delegation working with the help of
 * https://www.infoq.com/articles/Easily-Create-Java-Agents-with-ByteBuddy
 */
final class ScheduledFutureTaskHack {

  private static final Logger LOGGER = LoggerFactory.getLogger( ScheduledFutureTaskHack.class ) ;

  private static final Class&lt; ? &gt; SCHEDULEDFUTURETASK_CLASS ;
  private static final Method SCHEDULEDFUTURETASK_NANOTIME_METHOD ;
  private static final Method SCHEDULEDFUTURETASK_DEADLINENANOS_METHOD ;
  private static final Field SCHEDULEDFUTURETASK_DEADLINENANOS_FIELD ;
  private static final Field SCHEDULEDFUTURETASK_STARTTIME_FIELD ;
  static {
    try {
      SCHEDULEDFUTURETASK_CLASS = Class.forName( ""io.netty.util.concurrent.ScheduledFutureTask"" ) ;
      SCHEDULEDFUTURETASK_NANOTIME_METHOD =
          SCHEDULEDFUTURETASK_CLASS.getDeclaredMethod( ""nanoTime"" ) ;
      SCHEDULEDFUTURETASK_NANOTIME_METHOD.setAccessible( true ) ;
      SCHEDULEDFUTURETASK_DEADLINENANOS_METHOD =
          SCHEDULEDFUTURETASK_CLASS.getDeclaredMethod( ""deadlineNanos"") ;
      SCHEDULEDFUTURETASK_DEADLINENANOS_METHOD.setAccessible( true ) ;
      SCHEDULEDFUTURETASK_DEADLINENANOS_FIELD =
          SCHEDULEDFUTURETASK_CLASS.getDeclaredField( ""deadlineNanos"" ) ;
      SCHEDULEDFUTURETASK_DEADLINENANOS_FIELD.setAccessible( true ) ;
      SCHEDULEDFUTURETASK_STARTTIME_FIELD =
          SCHEDULEDFUTURETASK_CLASS.getDeclaredField( ""START_TIME"" ) ;
      SCHEDULEDFUTURETASK_STARTTIME_FIELD.setAccessible( true ) ;
    } catch( ClassNotFoundException | NoSuchMethodException | NoSuchFieldException e ) {
      throw new Error( e ) ;
    }
  }

  /**
   * Everything is this class must be visible from the redefined class.
   */
  @SuppressWarnings( ""unused"" )
  public static final class StaticMethodDelegate {
    /**
     * Calls to {@link io.netty.util.concurrent.ScheduledFutureTask#nanoTime()} are redirected
     * to this method.
     * Sadly we can't use parameter annotated with {@link @This} or something giving a hint
     * about the call context. It looks like a consequence of JVMTI reload not supporting method
     * addition (adding a parameter would imply creating a new method).
     */
    public static long nanoTime() {
      final long supplied = longSupplier.getAsLong() ;
      LOGGER.debug( ""Called "" + StaticMethodDelegate.class.getSimpleName() + ""#nanoTime(), "" +
          ""returns "" + supplied + ""."" ) ;
      return supplied ;
    }

  }

  private static LongSupplier longSupplier = null ;

  static void install( final LongSupplier longSupplier ) {
    install( longSupplier, true ) ;
  }

  /**
   *
   * @param longSupplier
   * @param suppliedNanosRelativeToClassloadingTime if {@code true}, supplied nanoseconds are
   *     relative to {@link io.netty.util.concurrent.ScheduledFutureTask#START_TIME}.
   *     Original behavior of the hacked method is to substract
   *     {@link io.netty.util.concurrent.ScheduledFutureTask#START_TIME} from value returned
   *     by {@link System#nanoTime()} (probably to make number more readable and reduce the risk
   *     of an overflow). During tests we prefer to not care about start time so there is this
   *     option to add it automatically.
   */
  static void install(
      final LongSupplier longSupplier,
      final boolean suppliedNanosRelativeToClassloadingTime
  ) {
    checkState( ScheduledFutureTaskHack.longSupplier == null ) ;
    if( suppliedNanosRelativeToClassloadingTime ) {
      final long startTime = START_TIME ;
      LOGGER.debug(
          ""Installing with value of "" +
          SCHEDULEDFUTURETASK_STARTTIME_FIELD.toGenericString() +
          "" = "" + startTime + "" automatically added to the values supplied.""
      ) ;
      class AdjustedLongSupplier implements LongSupplier {
        @Override
        public long getAsLong() {
          return longSupplier.getAsLong() + startTime ;
        }
        @Override
        public String toString() {
          return ToStringTools.getNiceClassName( this ) + ""{startTime="" + startTime + ""}"" ;
        }
      }
      ScheduledFutureTaskHack.longSupplier = new AdjustedLongSupplier() ;
    } else {
      ScheduledFutureTaskHack.longSupplier = checkNotNull( longSupplier ) ;
    }
    ByteBuddyAgent.install() ;
    LOGGER.info( ""Successfully installed ByteBuddy Agent."" ) ;
    redefineClass() ;
    LOGGER.info( ""Successfully redefined static method implementation."" ) ;
  }

  private static void redefineClass() {
    new ByteBuddy()
        .redefine( SCHEDULEDFUTURETASK_CLASS )
        .method( named( ""nanoTime"" )
            .and( isStatic() )
            .and( isPackagePrivate() )
            .and( takesArguments( 0 ) )
            .and( returns( long.class ) )
        )
        .intercept( MethodDelegation.to( StaticMethodDelegate.class ) )
        .make()
        .load( ScheduledFutureTaskHack.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent() )
    ;
  }

  /**
   * Invokes method replacing {@link io.netty.util.concurrent.ScheduledFutureTask#nanoTime()}.
   */
  public static long invokeNanoTime() {
    try {
      return ( long ) SCHEDULEDFUTURETASK_NANOTIME_METHOD.invoke( null ) ;
    } catch( IllegalAccessException | InvocationTargetException e ) {
      throw new Error( e ) ;
    }
  }

  /**
   * The {@link io.netty.util.concurrent.ScheduledFutureTask#deadlineNanos()} method returns
   * the value made from {@link System#nanoTime()},
   * minus {@link io.netty.util.concurrent.ScheduledFutureTask#START_TIME},
   * plus the delay before executing the task.
   */
  public static Long invokeDeadlineNanos( final Future future ) {
    try {
      if( SCHEDULEDFUTURETASK_DEADLINENANOS_METHOD.getDeclaringClass()
          .isAssignableFrom( future.getClass() )
      ) {
        return ( long ) SCHEDULEDFUTURETASK_DEADLINENANOS_METHOD.invoke( future ) ;
      } else {
        return null ;
      }
    } catch( IllegalAccessException | InvocationTargetException e ) {
      throw new Error(
          ""Could not access method "" + SCHEDULEDFUTURETASK_DEADLINENANOS_METHOD + "" in "" + future,
          e
      ) ;
    }
  }

  private static long readStartTime() {
    try {
      return ( long ) SCHEDULEDFUTURETASK_STARTTIME_FIELD.get( null ) ;
    } catch( IllegalAccessException e ) {
      throw new Error(
          ""Could not access static field "" + SCHEDULEDFUTURETASK_STARTTIME_FIELD,
          e
      ) ;
    }
  }

  public static final long START_TIME = readStartTime() ;


}
</code></pre>

<p><em><code>ScheduledFutureTaskHackTest.java</code></em></p>

<pre><code>package com.otcdlink.chiron.integration.harness;

import com.otcdlink.chiron.toolbox.ToStringTools;
import com.otcdlink.chiron.toolbox.netty.NettyTools;
import io.netty.channel.nio.NioEventLoopGroup;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

import static org.assertj.core.api.Assertions.assertThat;

public class ScheduledFutureTaskHackTest {

  @Test
  public void fastForward() throws InterruptedException {

    final AtomicLong nanotimeHolder = new AtomicLong( 0 ) ;
    ScheduledFutureTaskHack.install( nanotimeHolder::get ) ;
    final long startTime = hackedNanoTime() ;

    final NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup() ;
    final Semaphore scheduledTaskCompleted = new Semaphore( 0 ) ;
    nioEventLoopGroup.schedule(
        () -&gt; {
          scheduledTaskCompleted.release() ;
          LOGGER.info( ""Scheduled task completed."" ) ;
        },
        1,
        TimeUnit.HOURS
    ) ;
    LOGGER.info( ""Scheduled task for in 1 hour, now fast-forwarding Netty's clock ..."" ) ;

    // Test fails when disabling fast-forward below.
    nanotimeHolder.set( startTime + TimeUnit.HOURS.toNanos( 1 ) + 1 ) ;
    Thread.sleep( 1000 ) ;
    hackedNanoTime() ;
    // Amazingly Netty detected clock change and ran the task!
    assertThat( scheduledTaskCompleted.tryAcquire( 1, TimeUnit.SECONDS ) )
        .describedAs( ""Scheduled task should have completed within 1 second"" )
        .isTrue()
    ;

  }


// =======
// Fixture
// =======

  private static final Logger LOGGER = LoggerFactory.getLogger(
      ScheduledFutureTaskHackTest.class ) ;

  static {
    NettyTools.forceNettyClassesToLoad() ;
  }

  private static long hackedNanoTime() {
    final long nanoTime = ScheduledFutureTaskHack.invokeNanoTime() ;
    LOGGER.info(
        ToStringTools.getNiceName( ScheduledFutureTaskHack.StaticMethodDelegate.class ) +
        ""#nanoTime(): "" + nanoTime + "".""
    ) ;
    return nanoTime ;
  }

}
</code></pre>

<p><em><code>InstrumentedNioEventLoopGroup.java</code></em></p>

<pre><code>package com.otcdlink.chiron.integration.harness;

import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.ScheduledFuture;

import javax.annotation.Nonnull;
import java.time.Instant;
import java.util.concurrent.Callable;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

import static com.google.common.base.Preconditions.checkNotNull;

class InstrumentedNioEventLoopGroup extends NioEventLoopGroup {

  /**
   * Consume the value obtained from
   * {@link io.netty.util.concurrent.ScheduledFutureTask#deadlineNanos()}.
   * This is hardly mappable to an exact {@link Instant} (even if the Java flavor retains
   * nanoseconds) but this is enough to compare with {@link System#nanoTime()}.
   */
  private final Consumer&lt; Long &gt; scheduledTaskMomentConsumer ;

  public InstrumentedNioEventLoopGroup(
      final ThreadFactory threadFactory,
      final Consumer&lt; Long &gt; scheduledTaskMomentConsumer
  ) {
    // Need 2 threads because one will block on Socket Selector if there is no IO,
    // so we add one to poll Tasks.
    super( 2, threadFactory ) ;
    this.scheduledTaskMomentConsumer = checkNotNull( scheduledTaskMomentConsumer ) ;
  }

  private &lt; FUTURE extends Future &gt; FUTURE recordDeadlineNanos( final FUTURE future ) {
    final Long deadlineNanos = ScheduledFutureTaskHack.invokeDeadlineNanos( future ) ;
    if( deadlineNanos != null ) {
      scheduledTaskMomentConsumer.accept( deadlineNanos ) ;
    }
    return future ;
  }


  @Nonnull
  @Override
  public Future&lt; ? &gt; submit( final Runnable task ) {
    return recordDeadlineNanos( super.submit( task ) ) ;
  }

  @Nonnull
  @Override
  public &lt; T &gt; Future&lt; T &gt; submit(
      final Runnable task,
      final T result
  ) {
    return recordDeadlineNanos( super.submit( task, result ) ) ;
  }

  @Nonnull
  @Override
  public &lt; T &gt; Future&lt; T &gt; submit( final Callable&lt; T &gt; task ) {
    return recordDeadlineNanos( super.submit( task ) ) ;
  }

  @Nonnull
  @Override
  public ScheduledFuture&lt; ? &gt; schedule(
      final Runnable command,
      final long delay,
      final TimeUnit unit
  ) {
    return recordDeadlineNanos( super.schedule( command, delay, unit ) ) ;
  }

  @Nonnull
  @Override
  public &lt; V &gt; ScheduledFuture&lt; V &gt; schedule(
      final Callable&lt; V &gt; callable,
      final long delay,
      final TimeUnit unit
  ) {
    return recordDeadlineNanos( super.schedule( callable, delay, unit ) ) ;
  }

  @Nonnull
  @Override
  public ScheduledFuture&lt; ? &gt; scheduleAtFixedRate(
      final Runnable command,
      final long initialDelay,
      final long period,
      final TimeUnit unit
  ) {
    return recordDeadlineNanos(
        super.scheduleAtFixedRate( command, initialDelay, period, unit ) ) ;
  }

  @Nonnull
  @Override
  public ScheduledFuture&lt; ? &gt; scheduleWithFixedDelay(
      final Runnable command,
      final long initialDelay,
      final long delay,
      final TimeUnit unit
  ) {
    return recordDeadlineNanos(
        super.scheduleWithFixedDelay( command, initialDelay, delay, unit ) ) ;
  }
}
</code></pre>

<p><em><code>InstrumentedNioEventLoopGroupTest.java</code></em></p>

<pre><code>package com.otcdlink.chiron.integration.harness;

import com.otcdlink.chiron.toolbox.concurrent.ExecutorTools;
import com.otcdlink.chiron.toolbox.netty.NettyTools;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.ScheduledFuture;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

import static org.assertj.core.api.Assertions.assertThat;

public class InstrumentedNioEventLoopGroupTest {

  @Test
  public void recordAndAdjust() throws InterruptedException {

    final int delay = 10 ;
    final TimeUnit timeUnit = TimeUnit.SECONDS ;

    final AtomicLong nanoInstantSupplier = new AtomicLong() ;
    ScheduledFutureTaskHack.install( nanoInstantSupplier::get ) ;

    final List&lt; Long &gt; taskDeadlineRecorder = Collections.synchronizedList( new ArrayList&lt;&gt;() ) ;
    final InstrumentedNioEventLoopGroup executor = new InstrumentedNioEventLoopGroup(
        ExecutorTools.newThreadFactory( ""executor"" ), taskDeadlineRecorder::add ) ;
    executor.setIoRatio( 1 ) ;  // Silly but worth trying to see what can get wrong.

    final Semaphore doneSemaphore = new Semaphore( 0 ) ;
    final ScheduledFuture&lt; ? &gt; scheduledFuture1 =
        executor.schedule( ( Runnable ) doneSemaphore::release, delay, timeUnit ) ;
    LOGGER.info( ""Scheduled "" + scheduledFuture1 + ""."" ) ;

    assertThat( taskDeadlineRecorder ).hasSize( 1 ) ;
    final Long nanoTime = taskDeadlineRecorder.get( 0 ) - ScheduledFutureTaskHack.START_TIME ;
    LOGGER.info( ""Recorded "" + nanoTime + "" as nanoTime deadline for next task."" ) ;

    assertThat( nanoTime ).isEqualTo( timeUnit.toNanos( delay ) ) ;
    final long pastDeadline = nanoTime + 1 ;
    nanoInstantSupplier.set( pastDeadline ) ;
    LOGGER.info(
        ""Did set nanoTime to "" + pastDeadline + "", past to Task's deadline. "" +
        ""Invocation of hacked nanoTime() returns "" +
        ScheduledFutureTaskHack.invokeNanoTime() + "".""
    ) ;
    LOGGER.info( ""Now waiting for task completion ..."" ) ;
    assertThat( doneSemaphore.tryAcquire( 3, TimeUnit.SECONDS ) ).isTrue() ;
  }

  /**
   * Fails when ran after {@link #recordAndAdjust()} because JUnit doesn't reload classes for
   * each method inside a test class.
   */
  @Test
  public void noInstrumentation() throws InterruptedException {
    final NioEventLoopGroup executor =
        new NioEventLoopGroup( 1, ExecutorTools.newThreadFactory( ""executor"" ) ) ;
    final Semaphore doneSemaphore = new Semaphore( 0 ) ;
    executor.submit( () -&gt; LOGGER.info( ""Plain submission works!"" ) ) ;
    final ScheduledFuture&lt; ? &gt; scheduledFuture =
        executor.schedule( ( Runnable ) doneSemaphore::release, 1, TimeUnit.SECONDS ) ;
    LOGGER.info( ""Scheduled "" + scheduledFuture + ""."" ) ;
    assertThat( doneSemaphore.tryAcquire( 3, TimeUnit.SECONDS ) ).isTrue() ;
  }


// =======
// Fixture
// =======

  private static final Logger LOGGER =
      LoggerFactory.getLogger( InstrumentedNioEventLoopGroupTest.class ) ;

  static {
    NettyTools.forceNettyClassesToLoad() ;
  }

}
</code></pre>

<p>I'm the author of the <a href=""https://github.com/OTCdLink/Chiron-framework"" rel=""nofollow noreferrer"" title=""Chiron Framework"">Chiron Framework</a>
, a WebSocket-based networking framework with a pure Java client, and non-blocking 2-factor authentication. It uses Netty a lot. Sadly there are many JMockit-based tests which don't run reliably because the execution order may be non-deterministic (this is a problem with every piece of code that schedules tasks).</p>
",https://stackoverflow.com/questions/50811262/instrument-nettys-eventloop-for-deterministic-execution-of-scheduled-tasks,"['java', 'netty']",1255,TRUE,11,1
Google Test: Android vs Linux EXPECT_DEATH Tests,"<p>I am running into a problem while working on unit testing my system that I don't even know how to approach debugging. My code operates either on a linux machine with mock input or on an android device. I am using Google Test to run unit tests on it. I have it set up so that a call to ""$ make all"" will run my unit tests on both the linux machine and through adb shell on my device. This part is working fine.</p>

<p>However, when I introduce a test with EXPECT_DEATH(...) in it, the linux build runs the same as usual but the android build stops at that test and appears to freeze (I have to Ctrl + C to stop execution). As I said, I'm not at all sure how to try to fix this problem as I can't seem to get any output or error messages from it.</p>

<p>If you have any suggestions please let me know. If there is critical information I'm leaving out about my build, comment and I can add that in.</p>

<p>Edit:</p>

<p>When I run the function that I'm expecting to die outside of EXPECT_DEATH the same behavior occurs. This indicates that the assert in the function is working and EXPECT_DEATH is not doing what it should to handle that.</p>

<p>Before: (Works fine on Linux build but not on Android build)</p>

<pre><code>EXPECT_DEATH(pObj-&gt;fxn(deathlyParam), """");
</code></pre>

<p>After: (Same result on Android build; core dump error due to assert on Linux build which is what I would expect both times from the Android build)</p>

<pre><code>EXPECT_EQ(pObj-&gt;fxn(deathlyParam), 0);
</code></pre>

<p>For reference, fxn() looks something like this:</p>

<pre><code>int fxn(int param)
{
   assert(param != deathlyParam);
   ...
}
</code></pre>

<p>In light of this, it looks more like assert is acting improperly and not causing the error it should be. Therefore, EXPECT_DEATH has nothing to expect. </p>
",https://stackoverflow.com/questions/51294474/google-test-android-vs-linux-expect-death-tests,"['android', 'c++', 'googletest']",299,TRUE,0,1
Add package name to symbol,"<p>This is a general symbol question in a specific context.  The question I think I need to answer is: given a parameter containing a symbol 'foo, how do I manipulate the package part of the symbol so that it is eql to 'package:foo?</p>

<p>The more specific context:  There is a unit-testing package, fiveam, that stores test functions in a hash table (<code>it.bese.fiveam::*tests</code>) with keys like <code>package::test-name</code> that hash to an object containing the tests.  To run a test, one normally passes to the <code>run!</code> function a symbol that is a hash key:  <code>(run! 'package::test-name</code>.  If I'm calling <code>run!</code> from the <code>tests</code> package in which I defined the tests, I can just C-x C-e on <code>(run! 'test-name)</code>.  When calling from the SLIME REPL, I have to do <code>(tests::run! 'tests::test-name)</code>, which is a mild inconvenience.</p>

<p>I'd like to run tests from cl-user with <code>(run! 'test-name)</code> and omit the package name.  I thought it would be simple to wrap <code>run!</code> and add the missing package to the symbol, but all my tries fail, I guess in part because <code>CL-USER:test-name</code> is a different thing from <code>tests:test-name</code>.</p>

<p>The hash table in question uses <code>eql</code> to test equality.  In the <code>tests</code> package:</p>

<pre><code>(eql 'tests::foo 'foo) =&gt; T
</code></pre>

<p>In CL-USER:</p>

<pre><code>(eql 'tests::foo 'foo) =&gt; nil
</code></pre>

<p>Various functions can return symbols (e.g. intern, make-symbol or format-symbol) but none of them are eql to the keys in the hash table:</p>

<pre><code>(eql (alexandria:format-symbol t ""foo::bar"") 'foo::bar) =&gt; nil
(eql (make-symbol ""foo::bar"") 'foo::bar) =&gt; nil
</code></pre>

<p>Taking this out of the SLIME/REPL/FIVEAM context to generalize where I think the problem is, I can't figure out how to take <code>'bar</code> and turn it into <code>'foo:bar</code> as a symbol.  I can specify it manually as <code>'foo:bar</code>, but I can't seem to get anything to eql <code>'foo:bar</code>, given <code>'bar</code>.</p>

<p>Note: I don't really care about typing the extra few letters for a package name.  What I'm really trying to do here is improve my understanding of scoping and specifying symbols.</p>

<p>Thank you.</p>
",https://stackoverflow.com/questions/52119793/add-package-name-to-symbol,"['common-lisp', 'symbols']",163,TRUE,0,2
Unit testing methods which do not produce a distinct output,"<p>In my Vaadin GUI application, there are so many methods which look like below.</p>

<pre><code>@Override
protected void loadLayout() {
    CssLayout statusLayout = new CssLayout();

    statusLayout.addComponent(connectedTextLabel);
    statusLayout.addComponent(connectedCountLabel);
    statusLayout.addComponent(notConnectedTextLabel);
    statusLayout.addComponent(notConnectedCountLabel);

    connectionsTable.getCustomHeaderLayout().addComponent(statusLayout);
    connectionsTable.getCustomHeaderLayout().addComponent(commandLayout);
    connectionsTable.getCustomHeaderLayout().addComponent(historyViewCheckbox);

    bodySplitter.addComponent(connectionsTable);
    bodySplitter.addComponent(connectionHistoryTable);
    bodySplitter.setSplitPosition(75, Sizeable.Unit.PERCENTAGE);
    bodySplitter.setSizeFull();
    bodyLayout.addComponent(bodySplitter);

    if (connectionDef.getConnectionHistoryDef() == null) {
        historyViewCheckbox.setVisible(false);
    }
    if (connectionDef.getConnectionStatusField() == null || connectionDef.getConnectedStatusValue() == null || connectionDef.getConnectedStatusValue().isEmpty()) {
        connectedTextLabel.setVisible(false);
        connectedCountLabel.setVisible(false);
        notConnectedTextLabel.setVisible(false);
        notConnectedCountLabel.setVisible(false);
    }
}


protected void setStyleNamesAndControlIds() {
    mainLayout.setId(""mainLayout"");
    header.setId(""header"");
    footer.setId(""footer"");
    propertyEditorLayout.setId(""propertyEditorLayout"");
    propertyEditor.setId(""propertyEditor"");

    mainLayout.setStyleName(""mainLayout"");
    propertyEditorLayout.setStyleName(""ui_action_edit"");
    header.setStyleName(""TopPane"");
    footer.setStyleName(""footer"");
}
</code></pre>

<p>These methods are used for setting up the layout of GUIs. They do not produce a single distinct output. Almost every line in these methods is doing a separate job, which is not almost relevant to other lines.</p>

<p>Usually, when unit testing a method, I check the return value of the method, or validate calls on a limited number of external objects such as database connections.</p>

<p>But, for methods like above, there is no such single output. If I wrote unit tests for such methods, My test code checks for each method call happens in every line in the method, and in the end, it looks almost like the method itself.</p>

<p>If someone altered the code in any way, the test will break and they will have to update the test to match the change. But, there is no assurance that the change didn't actually break anything since test doesn't check the actual UI drawn in the browser.</p>

<p>For an example, if someone changed a style name of a control, he will have to update the test code with the new style name and the test will pass. But, for things to actually work without any issue, he has to change the relevant scss style files too. But the test didn't make any contribution to detect this issue. Same applies to layout setup code as well.</p>

<p>Is there any advantage of writing unit tests like above, other than keeping the code coverage rating at a higher level? For me, it feels useless and writing a test to compare the decompiled bytecode of the method to the original decompiled bytecode kept as a string in the test looks much better than these kinds of tests.</p>
",https://stackoverflow.com/questions/49765720/unit-testing-methods-which-do-not-produce-a-distinct-output,"['java', 'unit-testing', 'vaadin']",60,TRUE,0,2
SQLAlchemy doesn&#39;t let me set up Flask apps multiple times in a test fixture,"<p>I am writing a <a href=""http://flask.pocoo.org/"" rel=""nofollow noreferrer"">Flask</a> application that uses <a href=""http://flask-sqlalchemy.pocoo.org/2.3/"" rel=""nofollow noreferrer"">SQLAlchemy</a> for its database backend.</p>

<p>The Flask application is created with an app factory called <code>create_app</code>.</p>

<pre><code>from flask import Flask

def create_app(config_filename = None):
    app = Flask(__name__)
    if config_filename is None:
        app.config.from_pyfile('config.py', silent=True)
    else:
        app.config.from_mapping(config_filename)

    from .model import db
    db.init_app(app)
    db.create_all(app=app)

    return app
</code></pre>

<p>The database model consists of a single object called <code>Document</code>.</p>

<pre><code>from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class Document(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    document_uri = db.Column(db.String, nullable=False, unique=True)
</code></pre>

<p>I am using <a href=""https://docs.pytest.org/en/latest/"" rel=""nofollow noreferrer"">pytest</a> to do unit testing. I create a pytest <a href=""https://docs.pytest.org/en/latest/fixture.html"" rel=""nofollow noreferrer"">fixture</a> called <code>app_with_documents</code> that calls the application factory to create an application and adds some <code>Document</code> objects to the database before the test is run, then empties out the database after the unit test has completed.</p>

<pre><code>import pytest
from model import Document, db
from myapplication import create_app

@pytest.fixture
def app():
    config = {
        'SQLALCHEMY_DATABASE_URI': f""sqlite:///:memory:"",
        'TESTING': True,
        'SQLALCHEMY_TRACK_MODIFICATIONS': False
    }
    app = create_app(config)
    yield app
    with app.app_context():
        db.drop_all()

@pytest.fixture
def app_with_documents(app):
    with app.app_context():
        document_1 = Document(document_uri='Document 1')
        document_2 = Document(document_uri='Document 2')
        document_3 = Document(document_uri='Document 3')
        document_4 = Document(document_uri='Document 4')
        db.session.add_all([document_1, document_2, document_3, document_4])
        db.session.commit()
    return app
</code></pre>

<p>I have multiple unit tests that use this fixture.</p>

<pre><code>def test_unit_test_1(app_with_documents):
    ...

def test_unit_test_2(app_with_documents):
    ...
</code></pre>

<p>If I run a single unit test everything works. If I run more than one test, subsequent unit tests crash at the <code>db.session.commit()</code> line in the test fixture setup with ""no such table: document"".</p>

<pre><code>    def do_execute(self, cursor, statement, parameters, context=None):
&gt;       cursor.execute(statement, parameters)
E       sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: document [SQL: 'INSERT INTO document (document_uri) VALUES (?)'] [parameters: ('Document 1',)] (Background on this error at: http://sqlalche.me/e/e3q8)
</code></pre>

<p>What I expect is that each unit test gets its own brand-new identical prepopulated database so that all the tests would succeed.</p>

<p>(This is an issue with the database tables, not the unit tests. I see the bug even if my unit tests consist of just <code>pass</code>.)</p>

<p>The fact that the error message mentions a missing table makes it look like the <code>db.create_all(app=app)</code> in <code>create_app</code> is not being called after the first unit test runs. However, I have verified in the debugger that this application factory function is called once for every unit test as expected.</p>

<p>It is possible that my call to <code>db.drop_all()</code> is an incorrect way to clear out the database. So instead of an in-memory database, I tried creating one on disk and then deleting it as part of the test fixture cleanup. (This is the technique <a href=""http://flask.pocoo.org/docs/1.0/testing/#the-testing-skeleton"" rel=""nofollow noreferrer"">recommended</a> in the Flask documentation.)</p>

<pre><code>@pytest.fixture
def app():
    db_fd, db_filename = tempfile.mkstemp(suffix='.sqlite')
    config = {
        'SQLALCHEMY_DATABASE_URI': f""sqlite:///{db_filename}"",
        'TESTING': True,
        'SQLALCHEMY_TRACK_MODIFICATIONS': False
    }
    yield create_app(config)
    os.close(db_fd)
    os.unlink(db_filename)
</code></pre>

<p>This produces the same error.</p>

<ul>
<li>Is this a bug in Flask and/or SQLAlchemy?</li>
<li>What is the correct way to write Flask test fixtures that prepopulate an application's database?</li>
</ul>

<p>This is Flask 1.0.2, Flask-SQLAlchemy 2.3.2, and pytest 3.6.0, which are all the current latest versions.</p>
",https://stackoverflow.com/questions/50520200/sqlalchemy-doesnt-let-me-set-up-flask-apps-multiple-times-in-a-test-fixture,"['flask', 'flask-sqlalchemy']",666,TRUE,0,1
Track local object state and interrupt flow with (Power)Mockito?,"<p>I am unit testing a Spring Boot micro-service. I want to use Mockito to throw an exception when a method is called in a certain process so that I can improve unit test coverage. The problem is that this method (let's call it <code>doB()</code>) is called by an object that only exists in the method's local scope (<code>B</code>), created by a static final factory object (<code>A</code>). </p>

<p>I want to do something along the lines of:</p>

<pre><code>doThrow(new RuntimeException()).when(mockedB).doB(anyString());
</code></pre>

<p>so that I can assert that <code>fooResult</code> returns <code>null</code> and therefore improve test coverage by covering the catch exception case.</p>

<p>But, is it even possible to create a <code>mockedB</code> in a useful way? If so, how?</p>

<p>I have tried various combinations of <code>mock()</code> and <code>spy()</code>, admittedly with little success. I'm new to using Mockito, but I'm pretty sure the crux of the problem is because if I just mock Foo then I won't be able to see the <code>A</code> and <code>B</code> inside doing things, but trying to mock or spy <code>A</code> or <code>B</code> doesn't work either since they aren't the same as the <code>A</code> or <code>B</code> created inside of <code>Foo</code>. <code>A</code> being final and static probably isn't doing me any favors here either.</p>

<p>I have removed pretty much all but the bare essential functionality as an example. The class I am testing is <code>Foo</code> which uses <code>A</code> and <code>B</code> internally.</p>

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

<pre><code>public class Foo {
    private static final A localA = new A();

    public FooResult doFoo(String fooString) {
        try {
            B localB = localA.createB();
            return localB.doB(fooString);
        } catch (RuntimeException e) {
            //exception handling here
        }
        return null;
    }

}
</code></pre>

<p>And this is <code>A</code>:</p>

<pre><code>public class A {

    //unimportant internal details
    private Object property;

    public A() {
        this(null);
    }

    public A(Object property) {
        this.property = property;
    }

    public B createB() {
        //assume for sake of example that this constructor 
        //is not easily accessible to classes other than A
        return new B();
    }
}
</code></pre>

<p>And now <code>B</code>:</p>

<pre><code>public class B {    

    public FooResult doB(String str) throws RuntimeException {

        //lots of processing, yada yada...
        //assume this exception is difficult to trigger just
        //from input due to details out of our control
        return new FooResult(str);
    }
}
</code></pre>

<p>Here is <code>FooResult</code></p>

<pre><code>public class FooResult {
    private String fooString;
    public FooResult(String str) {
        this.fooString = str;
    }
    public String getFooString() {
        return fooString;
    }
}
</code></pre>

<p>Finally, here is the test:</p>

<pre><code>@RunWith(PowerMockRunner.class)
public class FooTest {

    @InjectMocks
    Foo foo;

    @Test
    public void testDoFoo() {
        String fooString = ""Hello Foo"";
        FooResult fooResult = foo.doFoo(fooString);
        assertEquals(fooResult.getFooString(), fooString);
        //works fine, nothing special here
    }

  @Test
  @PrepareForTest({Foo.class, A.class, B.class})
  public void testDoFooException() throws Exception {

    //magic goes here???
    A mockedA = PowerMockito.mock(A.class);
    B mockedB = PowerMockito.mock(B.class);

    PowerMockito.when(mockedA.createB()).thenReturn(mockedB);
    PowerMockito.doThrow(new RuntimeException()).when(mockedB).doB(Mockito.anyString());

    FooResult fooResult = foo.doFoo(""Hello Foo"");

    //expect doFoo() to fail and return null
    assertNull(fooResult);
  }


}
</code></pre>

<p>As I said earlier, I expect the mock to trigger when <code>doB()</code> is called, causing <code>doB()</code> to return <code>null</code>. This doesn't work and the exception is not thrown.</p>

<p>I have a feeling this is bad practice to be trying this. A better way would probably be to change the method so that I could pass in my own <code>A</code> object instead so that I could observe it. But, let's just say that I can't change any source code. Is this even possible?</p>
",https://stackoverflow.com/questions/53890540/track-local-object-state-and-interrupt-flow-with-powermockito,"['java', 'spring-boot', 'junit', 'mockito', 'powermockito']",138,TRUE,0,1
how to avoid repeating function declaration in a wrapper,"<p>I know it is possible to write something like so:</p>

<pre><code>struct Impl {
    static bool f(int);
};

template&lt;class Impl&gt; struct Helper {
    static constexpr auto f = Impl::f;
};
</code></pre>

<p>But is there any way to avoid copy paste of function parameters and return values in such case:</p>

<pre><code>struct Impl {
    static bool f(int);
};

struct Helper {
    static const auto f = bind(*Impl::f, not_really_pimpl);

    static Impl *not_really_pimpl;
};
</code></pre>

<p>I don't expect it to work (and it doesn't) but is there any sensible way to avoid repeating f() parameters and return value in such wrapper?</p>

<p><strong>EDIT:</strong> Hundreds of stupid tests do Helper::f(). Now someone wanted to mock Helper. Helper is just a namespace of static functions which by chance appeared to be a class. Yes, I know that static functions do not allow mocking and blablabla, but they just want it.</p>

<p>I don't want to change a lot of code for just mocking. Also some amount of tests which would have to be rewritten if choosing between Helper : Impl and Helper : MockImpl is to be done at compile time for all of them, because they do use original Helper::f().</p>

<p>Also changing all this places where Helper::f() is called to some other syntax doesn't seem to be a good idea. So I'm just following a hack: <a href=""https://stackoverflow.com/questions/8942330/google-mock-unit-testing-static-methods-c"">Google Mock unit testing static methods c++</a> with this only difference that I cannot switch Helper with a template parameter for everything in compile time. It is simpler to just add a static pointer to implementation and call it from static functions. Then it is mockable/unmockable at runtime. It just adds even more copy-pasting than  mocks itself. </p>

<p>I was thinking there exist a sensible (not too many code to make it make sense comparing to repeating) to somehow base this parameters on templates but as I'm switching pointer in runtime I think it's not possible? So I would have to write </p>

<pre><code>struct Helper {
    static bool f(int) { not_really_pimpl-&gt;f(); }
    static NotReallyPimpl real_impl;
    static Impl* not_really_pimpl = &amp;real_pimpl; // pseudocode
};
</code></pre>

<p>and also</p>

<pre><code>struct NotReallyPimpl {
   virtual bool f(int) { /* here is the job done */ }
};
</code></pre>

<p>and also </p>

<pre><code>struct MockNotReallyPimpl : public NotReallyPimpl {
    MOCK_METHOD1(f, bool(int));
};
</code></pre>

<p>Then old test code will use Helper::f(). Some new test code which wishes to mock Helper would do:</p>

<pre><code>MockNotReallyPimpl mock;
Helper::not_really_pimpl = &amp;mock;
EXPECT_CALL(mock, f, blablabla).WillBlabla(WithBlablabla())).
Helper::not_really_pimpl = Helper::real_impl; // in TearDown
</code></pre>
",https://stackoverflow.com/questions/53674802/how-to-avoid-repeating-function-declaration-in-a-wrapper,"['c++', 'bind']",147,FALSE,0,0
